UNPKG

@lenne.tech/cli-plugin-helper

Version:

Helper plugin for Gluegun CLI Projects

224 lines 8.44 kB
"use strict"; 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.Helper = void 0; const gluegun_menu_1 = require("@lenne.tech/gluegun-menu"); const fs = require("fs"); const os = require("os"); const path_1 = require("path"); /** * Common helper functions */ class Helper { /** * Constructor for integration of toolbox */ constructor(toolbox) { this.toolbox = toolbox; } /** * Get configuration */ getConfig() { return __awaiter(this, void 0, void 0, function* () { // Toolbox feature const { config, filesystem, runtime: { brand }, } = this.toolbox; // Configuration in home directory (~/.brand) let homeDirConfig = {}; try { const homeDirConfigFile = (0, path_1.join)(filesystem.homedir(), `.${brand}`); if (yield filesystem.existsAsync(homeDirConfigFile)) { homeDirConfig = JSON.parse(yield filesystem.readAsync(homeDirConfigFile)); } } catch (e) { // Nothing } // Configuration in current directory (./.brand) let currentDirConfig = {}; try { const currentDirConfigFile = (0, path_1.join)(filesystem.cwd(), `.${brand}`); if (yield filesystem.existsAsync(currentDirConfigFile)) { currentDirConfig = JSON.parse(yield filesystem.readAsync(currentDirConfigFile)); } } catch (e) { // Nothing } return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, config[brand]), config.loadConfig((0, path_1.join)('~', `.${brand}`), brand)), homeDirConfig), config.loadConfig((0, path_1.join)(filesystem.cwd(), `.${brand}`), brand)), currentDirConfig); }); } /** * Get prepared directory path */ getDir(...dirPath) { if (!dirPath.join('')) { return null; } return (0, path_1.join)(...dirPath) // normalized path .replace('~', os.homedir()) // replace ~ with homedir .replace(/\/|\\/gm, path_1.sep); // set OS specific separators } /** * Get input if not set */ getInput(input, options) { return __awaiter(this, void 0, void 0, function* () { // Process options const opts = Object.assign({ initial: '', name: 'name', showError: false, }, options); if (!opts.errorMessage) { opts.errorMessage = `You must provide a valid ${opts.name}!`; } // Toolbox features const { print: { error }, prompt: { ask }, } = this.toolbox; // Get input if (!input || !this.trim(input)) { const answers = yield ask({ initial: opts.initial, message: `Enter ${opts.name}`, name: 'input', type: 'input', }); input = answers.input; if (!input && opts.showError) { error(opts.errorMessage); } } // Return input return input; }); } /** * String with minutes and seconds */ msToMinutesAndSeconds(ms) { const minutes = Math.floor((ms / 1000 / 60) << 0); const seconds = Math.floor((ms / 1000) % 60); return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`; } /** * Read a file */ readFile(path) { return new Promise((resolve, reject) => { fs.readFile(path, (err, data) => { if (err) { reject(err); } else { if (path.endsWith('.json')) { resolve(JSON.parse(data.toString())); } else { resolve(data); } } }); }); } /** * Trim and remove linebreaks from input */ trim(input) { // Check input if (input !== 0 && !input) { return input; } // Trim input return input .toString() .trim() .replace(/(\r\n|\n|\r)/gm, ''); } /** * Run update for cli */ updateCli(options) { return __awaiter(this, void 0, void 0, function* () { // Toolbox const { helper, meta, print: { info, spin, success }, runtime: { brand, defaultPlugin }, system: { run, startTimer }, } = this.toolbox; // Start timer const timer = startTimer(); // Get package.json const packageJson = yield helper.readFile((0, path_1.join)(meta.src ? meta.src : defaultPlugin.directory, '..', 'package.json')); // Process options const opts = Object.assign({ global: true, packageName: packageJson ? packageJson.name : '', showInfos: false, }, options); // Run without infos if (!opts.showInfos) { return run(`npm install${opts.global ? ' -g ' : ' '}${opts.packageName}`); } // Update const updateSpin = spin(`Update ${opts.packageName}`); yield run(`npm install${opts.global ? ' -g ' : ' '}${opts.packageName}`); updateSpin.succeed(); // Check new version const versionSpin = spin(`Get current version from ${opts.packageName}`); const version = helper.trim(yield run(`${brand} version`)); versionSpin.succeed(); // Success success(`🎉 Updated to ${version} from ${opts.packageName} in ${helper.msToMinutesAndSeconds(timer())}m.`); info(''); }); } /** * Show menu */ showMenu(parentCommands, options) { return __awaiter(this, void 0, void 0, function* () { // Toolbox feature const { config, filesystem: { existsAsync }, meta, runtime: { brand, defaultPlugin }, } = this.toolbox; // Process options const { checkUpdate } = Object.assign({ checkUpdate: true, }, options); // Check for updates if (checkUpdate // parameter && config[brand].checkForUpdate // current configuration && (yield this.getConfig()).checkForUpdate // extra configuration && !(yield existsAsync((0, path_1.join)(meta.src ? meta.src : defaultPlugin.directory, '..', 'src'))) // not development environment ) { config[brand].checkForUpdate = false; // tslint:disable-next-line:no-floating-promises meta .checkForUpdate() .then((update) => { if (update) { // tslint:disable-next-line:no-floating-promises this.updateCli().catch(() => { // do nothing }); } }) .catch(() => { // do nothing }); } // ShowMenu yield new gluegun_menu_1.Menu(this.toolbox).showMenu(parentCommands, options); }); } } exports.Helper = Helper; /** * Extend toolbox */ exports.default = (toolbox) => { toolbox.helper = new Helper(toolbox); }; //# sourceMappingURL=helper.extension.js.map