UNPKG

kist

Version:

Lightweight Package Pipeline Processor with Plugin Architecture

89 lines 3.86 kB
import { __awaiter } from "tslib"; import { promises as fs } from "fs"; import path from "path"; import { Action } from "../../core/pipeline/Action.js"; export class VersionWriteAction extends Action { execute(options) { return __awaiter(this, void 0, void 0, function* () { const files = options.files; let version = options.version; if (!files) { throw new Error(`Missing required option: files.`); } if (!version) { version = yield this.getVersionFromPackageJson(); if (!version) { throw new Error(`Version is not provided in options and could not be retrieved from package.json.`); } } this.logInfo(`Replacing version "${version}" in specified files.`); try { yield Promise.all(files.map(({ path: filePath, key }) => this.replaceVersionInFile(filePath, version, key || "version:"))); this.logInfo(`Version "${version}" replaced successfully in all specified files.`); } catch (error) { this.logError(`Failed to replace version in one or more files.`, error); throw error; } }); } getVersionFromPackageJson() { return __awaiter(this, void 0, void 0, function* () { try { const packageJsonPath = path.resolve(process.cwd(), "package.json"); const packageJsonContent = yield fs.readFile(packageJsonPath, "utf8"); const packageJson = JSON.parse(packageJsonContent); const version = packageJson.version; if (version && /^\d+\.\d+\.\d+$/.test(version)) { this.logInfo(`Version "${version}" retrieved from package.json.`); return version; } else { this.logWarn(`Invalid or missing version in package.json.`); return undefined; } } catch (error) { this.logError(`Error reading package.json for version retrieval.`, error); return undefined; } }); } replaceVersionInFile(filePath, version, key) { return __awaiter(this, void 0, void 0, function* () { try { const content = yield fs.readFile(filePath, "utf8"); const endsWithNewline = content.endsWith("\n"); const lines = content.split("\n"); if (endsWithNewline && lines[lines.length - 1] === "") { lines.pop(); } const updatedLines = lines.map((line) => { const regex = new RegExp(`^\\s*${key}\\s*\\d+\\.\\d+\\.\\d+`); if (regex.test(line)) { return line.replace(/\d+\.\d+\.\d+$/, version); } return line; }); const finalContent = endsWithNewline ? updatedLines.join("\n") + "\n" : updatedLines.join("\n"); yield fs.writeFile(filePath, finalContent, "utf8"); this.logInfo(`Version replaced in file "${filePath}" for key "${key}".`); } catch (error) { throw new Error(`Error replacing version in file "${filePath}": ${error.message}`); } }); } describe() { const description = ` Replaces a version string in one or more specified files based on a key and pattern. Can retrieve the version from package.json or set it manually. `; return description; } } //# sourceMappingURL=VersionWriteAction.js.map