UNPKG

@criticalmanufacturing/node-package-bundler

Version:
292 lines 11.6 kB
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Operations = void 0; const inversify_1 = require("inversify"); const types_1 = require("../types"); const log_1 = require("./log"); const path = require("path"); const io = require("fs-extra"); const child_process_1 = require("child_process"); let Operations = class Operations { /** * Copy one file from one place to another * @param file Name of the file * @param source Directory path where the file is located * @param destination Directory path where the file is to be copied */ copyFile(file, source, destination, isOptional = false) { const sourcePath = path.join(source, file); const destinationPath = path.join(destination, file); if (io.existsSync(sourcePath)) { io.ensureDirSync(destination); io.copySync(sourcePath, destinationPath); this._logger.info(`[Copy] '${file}' to '${destination}'`); } else { if (isOptional) { this._logger.warn(`[Copy Ignored] File '${sourcePath}' doesn't exist`); } else { throw new Error(`[Copy FAIL] File '${sourcePath}' doesn't exist!!!`); } } } /** * Move a file from one location into another * @param file File to move * @param source Directory path where the file is located * @param destination Directory path where the file is to be moved */ moveFile(file, source, destination) { const sourcePath = path.join(source, file); const destinationPath = path.join(destination, file); if (io.existsSync(sourcePath)) { io.ensureDirSync(destination); io.copySync(sourcePath, destinationPath); io.unlinkSync(sourcePath); this._logger.info(`[Move] '${file}' from '${source}' to '${destination}'`); } else { throw new Error(`[Move FAIL] File '${sourcePath}' doesn't exist!!!`); } } /** * Rename an existing file * @param source Full path of the original file * @param destination Full path of the destination file */ renameFile(source, destination) { if (io.existsSync(source)) { io.moveSync(source, destination); this._logger.info(`[Rename] '${source}' to '${destination}'`); } else { throw new Error(`[Rename FAIL] File '${source}' doesn't exist!!!`); } } /** * Delete a file * @param filePath Path of the file */ deleteFile(filePath) { if (io.existsSync(filePath)) { io.unlinkSync(filePath); this._logger.info(`[Deleted] '${filePath}'`); } else { this._logger.warn(`[Delete Ignored] '${filePath}'`); } } createFile(destination, contents) { const baseDirectory = path.dirname(destination); io.ensureDirSync(baseDirectory); io.writeFileSync(destination, contents, "utf8"); this._logger.info(`[CreateFile] Created file '${destination}'`); } /** * Replaces a text from a file with another text * @param file Full path of the file * @param search Token to search * @param replace Token to replace */ replaceTextInFile(file, search, replace, isRegularExpression) { if (io.existsSync(file) || search === "") { let contents = io.readFileSync(file, "utf8"); let wasChanged = false; if (isRegularExpression === false) { let iPos = contents.indexOf(search); while (iPos > 0) { this._logger.info(`[ReplaceText] '${search}' with '${replace}'`); contents = contents.replace(search, replace); wasChanged = true; iPos = contents.indexOf(search); } } else { const previous = contents; contents = contents.replace(new RegExp(search, "g"), replace); wasChanged = contents !== previous; if (wasChanged) { this._logger.info(`[ReplaceText] '${search}' with '${replace}'`); } } if (wasChanged) { io.writeFileSync(file, contents, "utf8"); } } else { this._logger.warn(`[ReplaceText IGNORED] ReplaceText in '${file}' because it doesn't exist!!!`); } } /** * Remove from package.json all dependencies and dev dependencies * @param file Full path of the package.json file */ removeDependenciesFromPackageJson(file) { const contents = JSON.parse(io.readFileSync(file, "utf8")); contents.scripts = {}; contents.dependencies = {}; contents.devDependencies = {}; if (contents.cmfLinkDependencies != null) { contents.cmfLinkDependencies = undefined; } io.writeFileSync(file, JSON.stringify(contents, null, 2), "utf8"); this._logger.info(`[Stripped Dependencies] '${file}'`); } /** * Change the version stated in a package.json file * @param file Full path of the package.json file * @param version Version to change to */ changePackageJsonVersion(file, version) { const contents = JSON.parse(io.readFileSync(file, "utf8")); contents.version = version; io.writeFileSync(file, JSON.stringify(contents, null, 2), "utf8"); this._logger.info(`[NewVersion] '${file}' (${version})`); } setPackageJsonAsPacked(file) { const contents = JSON.parse(io.readFileSync(file, "utf8")); if (contents.criticalManufacturing == null) { contents.criticalManufacturing = {}; } contents.criticalManufacturing.isPacked = true; io.writeFileSync(file, JSON.stringify(contents, null, 2), "utf8"); this._logger.info(`[IsPacked] '${file}' (true)`); } /** * Create a new Directory * @param directoryPath Full path of the directory to create */ createDirectory(directoryPath) { if (io.existsSync(directoryPath)) { this._logger.warn(`[CreateDirectory Ignored] '${directoryPath}'`); } else { io.mkdirSync(directoryPath, 0o777); this._logger.info(`[CreateDirectory] '${directoryPath}'`); } } /** * Delete an entire directory, even if it is not empty * @param directoryPath Full path of the directory to delete */ deleteDirectory(directoryPath) { if (io.existsSync(directoryPath)) { io.removeSync(directoryPath); this._logger.info(`[Deleted] '${directoryPath}'`); } else { this._logger.warn(`[Delete Ignored] '${directoryPath}'`); } } /** * Copy entire directory from one place to another * @param source Full path of the original directory * @param destination Full path of the destination directory */ copyDirectory(source, destination) { if (io.existsSync(source)) { io.copySync(source, destination, { // recursive: true, overwrite: true, preserveTimestamps: true, }); this._logger.info(`[CopyDirectory] '${source}' to '${destination}'`); } else { throw new Error(`[CopyDirectory FAIL] Directory '${source}' doesn't exist!!!`); } } /** * Run an external application * @param command Command to execute * @param args Arguments to pass to the command * @param cwd Directory where the command will run */ run(command, args, cwd) { this._logger.info(`[Run] ${cwd != null ? cwd + "> " : ""}${command} ${args.join(" ")}`); const child = (0, child_process_1.spawnSync)(command, args, { cwd: cwd, shell: true }); if (child.error != null) { throw (child.error); } if (child.stderr) { this._logger.warn(`[Run Err] ` + child.stderr.toString().trim()); } if (child.stdout != null) { this._logger.info(`[Run Out] ` + child.stdout.toString().trim()); } if (child.status !== 0) { throw new Error(`[Run FAIL] Failed to execute command '${command}'. ExitCode='${child.status}'`); } return (true); } /** * Utility function to convert ReadableStream<Uint8Array> to Buffer * @param readableStream ReadableStream to convert */ readStreamToBuffer(readableStream) { return __awaiter(this, void 0, void 0, function* () { const reader = readableStream.getReader(); const chunks = []; let done = false; while (!done) { const { value, done: isDone } = yield reader.read(); if (value) { chunks.push(value); } done = isDone; } // Concatenate all chunks into a single Buffer const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0); const buffer = Buffer.concat(chunks, totalLength); return buffer; }); } /** * Utility function to convert ReadableStream<Uint8Array> to Buffer * @param urlToValidate String representing the url to validate */ isValidUrl(urlToValidate) { let url; try { url = new URL(urlToValidate); if (url !== null && (url.protocol === "http:" || url.protocol === "https:")) { return true; } } catch (_) { return false; } return false; } }; exports.Operations = Operations; __decorate([ (0, inversify_1.inject)(types_1.TYPES.Logger), __metadata("design:type", log_1.Log) ], Operations.prototype, "_logger", void 0); exports.Operations = Operations = __decorate([ (0, inversify_1.injectable)() ], Operations); //# sourceMappingURL=operations.js.map