@tuzki/cli
Version:
🐇 lowcode-cli is an efficient cli tool for Rabbitpre plugin component secondary development. ❤️
138 lines (137 loc) • 3.66 kB
JavaScript
/*
* shelljs模块相关辅助函数
*
* @Author: xu.jin
* @Date: 2022-12-07 11:02:14
*
* Copyright © 2014-2022 Rabbitpre.com. All Rights Reserved.
*/
import shell from 'shelljs';
/**
* 执行单个`unix`命令
*
* @export
* @param {ExecCommandOption} opts 执行选项
*/
export function execCommand(opts) {
const { cmd, async, cwd, silent = true, env, callback = () => { } } = opts;
const isAsync = !!async;
for (const [key, value] of Object.entries(env || {})) {
/** shell 会自动传入环境变量 */
process.env[key] = value;
}
// 如果需要 cd 到某个目录之后再执行
if (cwd) {
shell.cd(cwd);
}
// 异步
if (isAsync) {
shell.exec(cmd, { silent }, callback);
return null;
}
// 同步
return shell.exec(cmd, {
silent,
});
}
/**
* 异步执行`unix`命令
*
* @export
* @param {(Omit<ExecCommandOption, 'async' | 'callback'>)} opts
* @return {*} {Promise<number>}
*/
export function execCommandPromise(opts) {
return new Promise(resolve => {
execCommand(Object.assign(Object.assign({}, opts), { async: true, callback: code => {
resolve(Promise.resolve(code));
} }));
});
}
/**
* 批量执行`unix`命令
*
* @export
* @param {BatchExecCommandOption} opts 执行选项
*/
export 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);
}
}
}
/**
* 检查当前环境变量中是否存在指定命令
*
* @export
* @param {string} cmd 命令
* @return {*} {boolean}
*/
export function isCommandExist(cmd) {
const rlt = shell.which(cmd);
if (rlt && rlt.code === 0)
return true;
return false;
}
/**
* cd 路径文件夹
*
* @export
* @param {string} targetDir 目标文件夹
*/
export function cdTargetDir(targetDir) {
shell.cd(targetDir);
}
/**
* 清除 shell 输出的空格
*
* @export
* @param {string} [stdout=''] shell 输出
* @return {*} {string}
*/
export function removeStdoutSpace(stdout = '') {
return stdout.replace(/\s+|\\n/g, '');
}