|
| 1 | +"use strict"; |
| 2 | + |
| 3 | +const fs = require("fs"); |
| 4 | +const path = require("path"); |
| 5 | +const tar = require("tar"); |
| 6 | +const micromatch = require("micromatch"); |
| 7 | +const { PassThrough } = require("stream"); |
| 8 | +const os = require("os"); // For accessing the system's temp directory |
| 9 | + |
| 10 | +/** |
| 11 | + * Create a tar.gz archive in memory. |
| 12 | + * @param {string} tempDir - The temporary directory containing files to archive. |
| 13 | + * @returns {Promise<Buffer>} - A promise that resolves to the tar.gz buffer. |
| 14 | + */ |
| 15 | +async function createTarInMemory(tempDir) { |
| 16 | + return new Promise((resolve, reject) => { |
| 17 | + const pass = new PassThrough(); |
| 18 | + const chunks = []; |
| 19 | + |
| 20 | + pass.on("data", (chunk) => chunks.push(chunk)); |
| 21 | + pass.on("error", (error) => reject(error)); |
| 22 | + pass.on("end", () => resolve(Buffer.concat(chunks))); |
| 23 | + |
| 24 | + tar |
| 25 | + .create( |
| 26 | + { |
| 27 | + gzip: true, |
| 28 | + cwd: tempDir, |
| 29 | + }, |
| 30 | + ["."] |
| 31 | + ) |
| 32 | + .pipe(pass) |
| 33 | + .on("error", (err) => reject(err)); |
| 34 | + }); |
| 35 | +} |
| 36 | + |
| 37 | +module.exports.register = function ({ config }) { |
| 38 | + const logger = this.getLogger("archive-attachments-extension"); |
| 39 | + const archives = config.data?.archives || []; |
| 40 | + |
| 41 | + // Validate configuration |
| 42 | + if (!archives.length) { |
| 43 | + logger.info("No `archives` configurations provided. Archive creation skipped."); |
| 44 | + return; |
| 45 | + } |
| 46 | + |
| 47 | + this.on("beforePublish", async ({ contentCatalog, siteCatalog }) => { |
| 48 | + logger.info("Starting archive creation process"); |
| 49 | + |
| 50 | + const components = contentCatalog.getComponents(); |
| 51 | + |
| 52 | + for (const archiveConfig of archives) { |
| 53 | + const { output_archive, component, file_patterns } = archiveConfig; |
| 54 | + |
| 55 | + // Validate individual archive configuration |
| 56 | + if (!output_archive) { |
| 57 | + logger.warn("An `archive` configuration is missing `output_archive`. Skipping this archive."); |
| 58 | + continue; |
| 59 | + } |
| 60 | + if (!component) { |
| 61 | + logger.warn(`Archive "${output_archive}" is missing component config. Skipping this archive.`); |
| 62 | + continue; |
| 63 | + } |
| 64 | + if (!file_patterns || !file_patterns.length) { |
| 65 | + logger.warn(`Archive "${output_archive}" has no file_patterns config. Skipping this archive.`); |
| 66 | + continue; |
| 67 | + } |
| 68 | + |
| 69 | + logger.debug(`Processing archive: ${output_archive} for component: ${component}`); |
| 70 | + |
| 71 | + // Find the specified component |
| 72 | + const comp = components.find((c) => c.name === component); |
| 73 | + if (!comp) { |
| 74 | + logger.warn(`Component "${component}" not found. Skipping archive "${output_archive}".`); |
| 75 | + continue; |
| 76 | + } |
| 77 | + |
| 78 | + for (const compVer of comp.versions) { |
| 79 | + const compName = comp.name; |
| 80 | + const compVersion = compVer.version; |
| 81 | + const latest = comp.latest?.version || "not latest"; |
| 82 | + |
| 83 | + const isLatest = latest === compVersion; |
| 84 | + |
| 85 | + logger.debug(`Processing component version: ${compName}@${compVersion}`); |
| 86 | + |
| 87 | + // Gather attachments for this component version |
| 88 | + const attachments = contentCatalog.findBy({ |
| 89 | + component: compName, |
| 90 | + version: compVersion, |
| 91 | + family: "attachment", |
| 92 | + }); |
| 93 | + |
| 94 | + logger.debug(`Found ${attachments.length} attachments for ${compName}@${compVersion}`); |
| 95 | + |
| 96 | + if (!attachments.length) { |
| 97 | + logger.debug(`No attachments found for ${compName}@${compVersion}, skipping.`); |
| 98 | + continue; |
| 99 | + } |
| 100 | + |
| 101 | + // Filter attachments based on file_patterns |
| 102 | + const attachmentsSegment = "_attachments/"; |
| 103 | + const matched = attachments.filter((attachment) => |
| 104 | + micromatch.isMatch(attachment.out.path, file_patterns) |
| 105 | + ); |
| 106 | + |
| 107 | + logger.debug(`Matched ${matched.length} attachments for ${compName}@${compVersion}`); |
| 108 | + |
| 109 | + if (!matched.length) { |
| 110 | + logger.debug(`No attachments matched patterns for ${compName}@${compVersion}, skipping.`); |
| 111 | + continue; |
| 112 | + } |
| 113 | + |
| 114 | + // Create a temporary directory and write matched attachments |
| 115 | + let tempDir; |
| 116 | + try { |
| 117 | + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), `${compName}-${compVersion}-`)); |
| 118 | + logger.debug(`Created temporary directory: ${tempDir}`); |
| 119 | + |
| 120 | + for (const attachment of matched) { |
| 121 | + const relPath = attachment.out.path; |
| 122 | + const attachmentsIndex = relPath.indexOf(attachmentsSegment); |
| 123 | + |
| 124 | + if (attachmentsIndex === -1) { |
| 125 | + logger.warn(`'${attachmentsSegment}' segment not found in path: ${relPath}. Skipping this file.`); |
| 126 | + continue; |
| 127 | + } |
| 128 | + |
| 129 | + // Extract the path starting after '_attachments/' |
| 130 | + const relativePath = relPath.substring(attachmentsIndex + attachmentsSegment.length); |
| 131 | + |
| 132 | + const destPath = path.join(tempDir, relativePath); |
| 133 | + fs.mkdirSync(path.dirname(destPath), { recursive: true }); |
| 134 | + fs.writeFileSync(destPath, attachment.contents); |
| 135 | + logger.debug(`Written file to tempDir: ${destPath}`); |
| 136 | + } |
| 137 | + |
| 138 | + // Asynchronously create the tar.gz archive in memory |
| 139 | + try { |
| 140 | + logger.debug(`Starting tar creation for ${compName}@${compVersion}`); |
| 141 | + const archiveBuffer = await createTarInMemory(tempDir); |
| 142 | + logger.debug(`Tar creation completed for ${compName}@${compVersion}`); |
| 143 | + |
| 144 | + // Define the output path for the archive in the site |
| 145 | + const archiveOutPath = `${compVersion ? compVersion + "-" : ""}${output_archive}`.toLowerCase(); |
| 146 | + |
| 147 | + // Add the archive to siteCatalog |
| 148 | + siteCatalog.addFile({ |
| 149 | + contents: archiveBuffer, |
| 150 | + out: { path: archiveOutPath }, |
| 151 | + }); |
| 152 | + |
| 153 | + if (isLatest) { |
| 154 | + siteCatalog.addFile({ |
| 155 | + contents: archiveBuffer, |
| 156 | + out: { path: path.basename(output_archive) }, |
| 157 | + }); |
| 158 | + } |
| 159 | + |
| 160 | + logger.info(`Archive "${archiveOutPath}" added to site.`); |
| 161 | + } catch (error) { |
| 162 | + logger.error(`Error creating tar archive for ${compName}@${compVersion}:`, error); |
| 163 | + continue; // Skip further processing for this version |
| 164 | + } |
| 165 | + } catch (error) { |
| 166 | + logger.error(`Error processing ${compName}@${compVersion}:`, error); |
| 167 | + } finally { |
| 168 | + // Clean up the temporary directory |
| 169 | + if (tempDir) { |
| 170 | + try { |
| 171 | + fs.rmSync(tempDir, { recursive: true, force: true }); |
| 172 | + logger.debug(`Cleaned up temporary directory: ${tempDir}`); |
| 173 | + } catch (cleanupError) { |
| 174 | + logger.error(`Error cleaning up tempDir "${tempDir}":`, cleanupError); |
| 175 | + } |
| 176 | + } |
| 177 | + } |
| 178 | + } |
| 179 | + } |
| 180 | + |
| 181 | + logger.info("Archive creation process completed"); |
| 182 | + }); |
| 183 | +}; |
0 commit comments