UNPKG

@szzbmy/lowcode-cli

Version:

🐇 lowcode-cli is an efficient cli tool for Rabbitpre plugin component secondary development. ❤️

118 lines (117 loc) 3.48 kB
"use strict"; /** * shelljs模块相关辅助函数 * @author VenDream * @since 2021-1-11 */ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.isCommandExist = exports.batchExecCommand = exports.execCommandPromise = exports.execCommand = void 0; const shelljs_1 = __importDefault(require("shelljs")); /** * 执行单个`unix`命令 * * @export * @param {ExecCommandOption} opts 执行选项 */ function execCommand(opts) { const { cmd, async, silent = true, env, callback = () => { } } = opts; const isAsync = !!async; for (const [key, value] of Object.entries(env || {})) { /** shell 会自动传入环境变量 */ process.env[key] = value; } // 异步 if (isAsync) { shelljs_1.default.exec(cmd, { silent }, callback); return null; } // 同步 return shelljs_1.default.exec(cmd, { silent, }); } exports.execCommand = execCommand; function execCommandPromise(opts) { return new Promise(resolve => { execCommand({ ...opts, async: true, callback: code => { resolve(Promise.resolve(code)); }, }); }); } exports.execCommandPromise = execCommandPromise; /** * 批量执行`unix`命令 * * @export * @param {BatchExecCommandOption} opts 执行选项 */ function batchExecCommand(opts) { const { cmds, async, silent, callback } = opts; const isAsync = !!async; const isSilent = silent === undefined ? true : silent; if (isAsync) { // 顺序执行多个异步命令 const execNextCmd = (code, stdout, stderr) => { if (code === 0) { // 取命令集栈顶命令 const cmd = cmds.shift(); if (cmd) { // 有则执行 execCommand({ cmd, async: true, silent: isSilent, callback: execNextCmd, }); } else { // 没有说明已经全部执行成功 callback && callback(0, stdout, stderr); } } else { callback && callback(1, stdout, stderr); } }; execNextCmd(0, '', ''); } else { // 顺序执行多个同步命令 let isFailed = false; let lastExecRlt = { code: 1, stdout: '', stderr: '' }; for (const cmd of cmds) { const execRlt = execCommand({ cmd, async: false, silent: isSilent }); if (!execRlt || execRlt.code !== 0) { isFailed = true; execRlt && (lastExecRlt = execRlt); break; } lastExecRlt = execRlt; } if (callback) { const { stdout, stderr } = lastExecRlt; callback(isFailed ? 1 : 0, stdout, stderr); } } } exports.batchExecCommand = batchExecCommand; /** * 检查当前环境变量中是否存在指定命令 * * @export * @param {string} cmd 命令 */ function isCommandExist(cmd) { const rlt = shelljs_1.default.which(cmd); if (rlt && rlt.code === 0) return true; return false; } exports.isCommandExist = isCommandExist;