appbir
Version:
常用脚手架库 -【app-lib-cli】
695 lines (573 loc) • 21.6 kB
JavaScript
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("app-lib-commander"), require("app-lib-exec"), require("app-lib-log"), require("app-lib-nobuild"), require("app-lib-node"), require("app-lib-trans-storage"));
else if(typeof define === 'function' && define.amd)
define(["app-lib-commander", "app-lib-exec", "app-lib-log", "app-lib-nobuild", "app-lib-node", "app-lib-trans-storage"], factory);
else {
var a = typeof exports === 'object' ? factory(require("app-lib-commander"), require("app-lib-exec"), require("app-lib-log"), require("app-lib-nobuild"), require("app-lib-node"), require("app-lib-trans-storage")) : factory(root["app-lib-commander"], root["app-lib-exec"], root["app-lib-log"], root["app-lib-nobuild"], root["app-lib-node"], root["app-lib-trans-storage"]);
for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
}
})(this, (__WEBPACK_EXTERNAL_MODULE__558__, __WEBPACK_EXTERNAL_MODULE__86__, __WEBPACK_EXTERNAL_MODULE__668__, __WEBPACK_EXTERNAL_MODULE__305__, __WEBPACK_EXTERNAL_MODULE__583__, __WEBPACK_EXTERNAL_MODULE__550__) => {
return /******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 17:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const { log } = __webpack_require__(668);
/**
* 错误的定义
*
*/
const ERROR_CODE = {
ERROR: -1, // 终止程序 往往有 message
WARN: 1, // 警告 不终止程序
SUCESS: 0,
};
let CODES = [];
for (let key in ERROR_CODE) {
CODES.push(ERROR_CODE[key]);
}
const LOG_FN = {
[ERROR_CODE.ERROR]: "e",
[ERROR_CODE.WARN]: "w",
[ERROR_CODE.SUCESS]: "s",
};
/**
* msg 打印的内容
*/
class AppError {
/**
*
* @param {*} msg 打印的日志内容 可以是数组
* @param {*} code 打印日志的错误格式
* @param {*} cfg 配置
*/
constructor(msg, code = ERROR_CODE.WARN, cfg = {}) {
if (!CODES.includes(code)) {
throw log.me(
`create AppError code [${code}] is no't in ERROR_CODE [${CODES}] `
);
}
let message = Array.isArray(msg) ? msg : msg == void 0 ? [] : [msg];
let config = {
trace: false, // 默认打印堆栈
module: true, // 默认模块化打印
data: undefined, // 接受的数据
print: true,
...cfg,
};
this.options = { message, code, config };
config.print && this.print();
}
// 后续扩展功能
print(option = {}) {
let { message, code, config } = { ...this.options, ...option };
let { trace, module } = config;
if (message && message.length) {
let fnName = [module && "m", LOG_FN[code], trace ? "" : "n"].join("");
let fn = log[fnName];
if (fn) {
fn.apply(log, message);
} else {
throw log.me(`log no exist ${fnName} function`);
}
}
}
isError() {
return this.options.code === ERROR_CODE.ERROR;
}
noError() {
return this.options.code === ERROR_CODE.SUCESS;
}
}
module.exports = {
AppError,
ERROR_CODE: ERROR_CODE,
};
/***/ }),
/***/ 585:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const {LANGUAGE} = __webpack_require__(598)
// 常用常数配置
const ARGUMENTS = {
// 支持语言
language:(opt)=> [
'[language]',
`[${LANGUAGE.join('/')}] default(${LANGUAGE[0]})`,
(language) => {
if (!LANGUAGE.includes(language)) {
log.en('error', `command-argument value '${language}' is invalid for argument 'language' , please choice right language in [${LANGUAGE.join(',')}]`)
throw new opt.commander.InvalidArgumentError();
}
return language
}
,
LANGUAGE[0]
]
}
module.exports = {
ARGUMENTS
}
/***/ }),
/***/ 598:
/***/ ((module) => {
// 支持的包格式 目标类型
const TARGET = ['server', 'doc', 'build', 'process'];
// 支持的语言类型 static静态资源
const LANGUAGE = ['es', 'node','bin','react', 'vue','static'];
// 支持的编译类型
const LIBRARY_TARGET_OBJ = {
// umd的编译模式 使用与node 与 brower
umd: { key: 'umd' },
commonjs: { key: 'commonjs' },
window: { key: 'window' },
// es module 暂时为支持
// module: { key: 'module' },
// amd: { key: 'amd' },
// system: { key: 'system' },
}
// 数组形式
let LIBRARY_TARGET = (() => {
let res = [];
for (prop in LIBRARY_TARGET_OBJ) {
res.push(LIBRARY_TARGET_OBJ[prop].key)
}
return res;
})()
module.exports = {
TARGET,
LANGUAGE,
LIBRARY_TARGET_OBJ,
LIBRARY_TARGET
}
/***/ }),
/***/ 919:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const { TARGET, LIBRARY_TARGET } = __webpack_require__(598);
// 常用的OPTIONS
const OPTIONS = {
// 支持目标文档
target: ({ Option }) => new Option('-t, --target [string]', 'server target module').choices(TARGET),
// debug: new Option('-d, --debug', 'is show debug log').default(false, 'toggle show debug log'),
debug: ({ Option }) => new Option('-d, --debug', 'show debug log'),
// 默认的输出类型
libraryTarget: ({ Option }) => new Option('-t, --libraryTarget [string]', 'output libraryTarget').choices(LIBRARY_TARGET).default(LIBRARY_TARGET[0], 'default is umd'),
// message 用户输入信息
message: ({ Option }) => new Option('-msg, --message [string]', 'git submit or change log message'),
}
module.exports = OPTIONS;
/***/ }),
/***/ 783:
/***/ ((module) => {
const int = (error, val) => {
let value = 1 * val;
if (isNaN(value)) {
throw new error()
}
return value;
};
const port = int;
module.exports = {
int,
port,
}
/***/ }),
/***/ 174:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const { log } = __webpack_require__(668);
const { ERROR_CODE, AppError } = __webpack_require__(17);
const { getRootPath, resolve } = __webpack_require__(583);
const { autoRequire } = __webpack_require__(305);
const prase = __webpack_require__(783);
// 解析统一测脚本参数
const praseOpt = (opt) => {
let { options } = opt;
// 倒数第二个为配置参数
let option = options.slice(options.length - 2, options.length - 1)[0];
// 入参为前面内容
let arg = options.slice(0, options.length - 2);
return { arg, option };
}
/**
* 执行 参数传递 同事执行对应的start函数
* @param {*} args
* @param {...any} options
*/
const action = async (args, ...options) => {
let { commond, start, ...arg } = args;
let outOption = options.slice(0, options.length - 1);
const commondName = typeof options[0] === 'string' ? options[0] : '';
log.md(`${commond} ${commondName}::BEGAIN`, { ...arg, options: outOption })
// 构建
let error = await start({ commond, ...arg, options });
// 校验
if (error === void 0) {
return new AppError(`[./plugins/${commond}.commong.js] function need return `, ERROR_CODE.ERROR)
}
// 数字返回 则表示直接是ERROR_CODE的异常
if (typeof error != 'object') {
error = new AppError('', error, { print: false });
}
if (error.noError()) {
log.md(`${commond} ${options[0]}::SUCCESS`)
} else {
log.md(`execute [${commond} ${commondName}] result is not 0, confirm is execute success`, `exexute file is [./plugins/${commond}.commong.js]`)
if (error.isError()) {
log.men(`execute [${commond} ${commondName}] result is error!`)
} else {
log.mwn(`execute [${commond} ${commondName}] is not complete!`)
}
}
// TODO 后续很如处理
// 1. 错误统一处理 深入了解commonder和nodesjs child_process 中的数据回传 eg:process.stdout.write("xxxx")
// 将异常传递到父进程
return error;
}
// commander option 参数转换为 exec 执行的参数
const optionsToArray = (options = {}, except = []) => {
let res = [];
for (key in options) {
if (!except.includes(key)) {
res.push(`--${key}`);
res.push(options[key]);
}
}
return res;
}
// 对象绑定执行的参数
const bindArg = (obj, arg) => {
let newObj = {};
for (key in obj) {
newObj[key] = obj[key].bind(null, arg)
}
return newObj;
}
// 动态获取环境变量
const transEnv = (option, fileds = []) => {
let res = [];
for (let key in option) {
if (fileds.includes(key)) {
res.push(`${camelToConst(key)}=${option[key]}`);
}
}
return res;
}
/**
* ---
* ##### 驼峰转下划线
*
* @param {string} camelStr 驼峰字符串
* @returns {string} 下划线字符串
* @function
*/
const camelToUnderline = camelStr => camelStr.replace(/([A-Z])/g, "_$1").toLowerCase();
/**
* ---
* ##### 驼峰转常量格式
*
* @function
* @param {string} camelStr 驼峰字符串
* @returns {string} 常量字符串
*
*/
const camelToConst = str => camelToUnderline(str).toUpperCase();
/**
* // TODO 去掉
* 获取配置文件路径
* @param {object} param0
* @returns string 路径
* 文件名称命名规范
* commond + name + append+ .config.js
* 路径 工程跟路径 + 配置相对位置+ 文件
*/
const getConfigPath = (args) => {
let { opt, append } = args;
let { commond, options } = opt;
let fileName = [commond, options[0]].concat(append || []).concat(['config.js']).join('.');
return resolve(getRootPath(), './static/config', fileName);
}
// 获取静态资源路径下的
const getStaticPath = (path = "") => resolve(getRootPath(), './static/', path)
// 动态加载发布目录 或者当前工程目录的文件
const autoRequireFile = (path, isRoot = true) => autoRequire(isRoot ? resolve(getRootPath(), path) : resolve(path))
// 动态 加载发布目录下的静态文件
const autoRequireStaticFile = (path) => autoRequireFile(getStaticPath(path));
module.exports = {
praseOpt,
action,
optionsToArray,
bindArg,
prase,
transEnv,
getConfigPath,// TODO 去掉
getStaticPath,
autoRequireFile,
autoRequireStaticFile
}
/***/ }),
/***/ 625:
/***/ ((module) => {
// 支持的包格式 目标类型
const TARGET = ['server', 'doc', 'build', 'process'];
// 支持的语言类型
const LANGUAGE = ['es','bin','node', 'react', 'vue'];
// 支持的编译类型
const LIBRARY_TARGET_OBJ = {
// umd的编译模式 使用与node 与 brower
umd: { key: 'umd' },
commonjs: { key: 'commonjs' },
window: { key: 'window' },
// es module 暂时为支持
// module: { key: 'module' },
// amd: { key: 'amd' },
// system: { key: 'system' },
}
// 数组形式
let LIBRARY_TARGET = (() => {
let res = [];
for (prop in LIBRARY_TARGET_OBJ) {
res.push(LIBRARY_TARGET_OBJ[prop].key)
}
return res;
})()
module.exports = {
TARGET,
LANGUAGE,
LIBRARY_TARGET_OBJ,
LIBRARY_TARGET
}
/***/ }),
/***/ 424:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
/**
* 动态读取插件 注册到系统
* 命名生效两个条件
* 1: 需要配置或者用plugin命令
* 2: 需要启用 该命名 默认安装是启用
*/
const STATIC_FILE_DATA = __webpack_require__(177);
// 获取支持的命令
// const getSupportCommonds = ({ utils: { autoRequireStaticFile } }) => autoRequireStaticFile('plugin/plugin.config.json')
// 热注册命令
const hotRegisterCommond = (commonds, opts) => {
let { program, commander, utils: { autoRequireStaticFile, action }, OPTIONS, noBuild: { appRequire } } = opts;
const resitCommond = [];
commonds.forEach(commond => {
if (commond?.enable) { // 启用的时候才注册
let fileName = commond.path;
let commondName = commond.name;
try {
// 本地的时候 直接加载本地静态文件 包模式 直接加载包
let pluginFn = commond?.type == "local" ?
autoRequireStaticFile(`plugin/${fileName}`)
: appRequire(fileName);
const plugin = pluginFn?.start(opts);
if (!plugin.init) return log.me('need init method export in ' + fileName)
if (!plugin.start) return log.me('need start method export in ' + fileName)
// 添加命令名称
let instance = program.command(commondName)
// 自定义部分
plugin.init(instance, opts);
// 默认追加--debug参数和--message参数 已经 调用执行方法
instance.addOption(OPTIONS.debug(commander))
.action(action.bind(null, {
start: plugin.start, // 执行方法
commond: commondName, // 命令名称
}));
instance.addOption(OPTIONS.message(commander));
resitCommond.push(commond)
} catch (e) {
log.me(`regiter ${commondName} commond error,please check [${fileName}] file`, e)
}
}
});
log.md(`already success register ${resitCommond.length} commonds`);
let registerCommods = resitCommond.map(c => (
{
commond: c.name,
'see commond help': `appbir ${c.name} --help`,
enable: c.enable,
type: c.type,
discription: c.discription
}));
if (process.argv.includes('--debug')) {
log.T(registerCommods)
}
return registerCommods;
}
/**
* 初始化插件命令
*/
const initPluginCommond = (opts) => {
let {STATIC: { jsonToFile },utils: {autoRequireStaticFile }}=opts;
// 静态资源自动生成
jsonToFile(STATIC_FILE_DATA);
let commonds = autoRequireStaticFile("plugin.config.json");
// 如果命令失效 或者删除了static/store 则需要打开命令执行后再次隐藏即可
// let commonds = [
// {"name":"plugin","enable":true,"type":"package","path":"app-lib-cli-plugin-plugin","discription":"插件管理命令// TODO 进行插件管理的开发 "},
// {"name":"git","enable":true,"type":"package","path":"app-lib-cli-plugin-git","discription":"GIT操作"},
// {"name":"build","enable":true,"type":"package","path":"app-lib-cli-plugin-build","discription":"构建编译"},
// {"name":"md","enable":true,"type":"package","path":"app-lib-cli-plugin-md","discription":"markdown编译"},
// {"name":"run","enable":true,"type":"package","path":"app-lib-cli-plugin-run","discription":"自定义命令"},
// {"name":"server","enable":true,"type":"package","path":"app-lib-cli-plugin-server","discription":"启动服务"},
// {"name":"init","enable":true,"type":"package","path":"app-lib-cli-plugin-init","discription":"初始工程"},
// {"name":"doc","enable":true,"type":"package","path":"app-lib-cli-plugin-doc","discription":"API文档"}
// ];
let registerCommond = hotRegisterCommond(commonds, opts);
return { commonds, registerCommond };
}
module.exports = { initCommond: initPluginCommond }
/***/ }),
/***/ 555:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const { log } = __webpack_require__(668);
const commander = __webpack_require__(558);
const nodeUtils = __webpack_require__(583);
const STATIC = __webpack_require__(550);
const { exec } = __webpack_require__(86);
const utils = __webpack_require__(174);
const noBuild = __webpack_require__(305);
const OPTIONS = __webpack_require__(919);
const { ARGUMENTS } = __webpack_require__(585);
const Error = __webpack_require__(17);
const CONSTANT = __webpack_require__(625)
module.exports = {
nodeUtils,
utils,
exec,
commander,
log,
noBuild,
OPTIONS, // 常用的option
ARGUMENTS, // 常用debugger
Error,
STATIC,//静态文件存储
CONSTANT,//常量
}
/***/ }),
/***/ 558:
/***/ ((module) => {
;
module.exports = __WEBPACK_EXTERNAL_MODULE__558__;
/***/ }),
/***/ 86:
/***/ ((module) => {
;
module.exports = __WEBPACK_EXTERNAL_MODULE__86__;
/***/ }),
/***/ 668:
/***/ ((module) => {
;
module.exports = __WEBPACK_EXTERNAL_MODULE__668__;
/***/ }),
/***/ 305:
/***/ ((module) => {
;
module.exports = __WEBPACK_EXTERNAL_MODULE__305__;
/***/ }),
/***/ 583:
/***/ ((module) => {
;
module.exports = __WEBPACK_EXTERNAL_MODULE__583__;
/***/ }),
/***/ 550:
/***/ ((module) => {
;
module.exports = __WEBPACK_EXTERNAL_MODULE__550__;
/***/ }),
/***/ 177:
/***/ ((module) => {
;
module.exports = JSON.parse('[{"name":"plugin.config.json","content":"[\\r\\n {\\"name\\":\\"plugin\\",\\"enable\\":true,\\"type\\":\\"package\\",\\"path\\":\\"app-lib-cli-plugin-plugin\\",\\"discription\\":\\"//TODO 插件管理\\"},\\r\\n {\\"name\\":\\"git\\",\\"enable\\":true,\\"type\\":\\"package\\",\\"path\\":\\"app-lib-cli-plugin-git\\",\\"discription\\":\\"GIT操作\\"},\\r\\n {\\"name\\":\\"build\\",\\"enable\\":true,\\"type\\":\\"package\\",\\"path\\":\\"app-lib-cli-plugin-build\\",\\"discription\\":\\"构建编译\\"},\\r\\n {\\"name\\":\\"md\\",\\"enable\\":true,\\"type\\":\\"package\\",\\"path\\":\\"app-lib-cli-plugin-md\\",\\"discription\\":\\"markdown编译\\"},\\r\\n {\\"name\\":\\"run\\",\\"enable\\":true,\\"type\\":\\"package\\",\\"path\\":\\"app-lib-cli-plugin-run\\",\\"discription\\":\\"自定义命令\\"},\\r\\n {\\"name\\":\\"server\\",\\"enable\\":true,\\"type\\":\\"package\\",\\"path\\":\\"app-lib-cli-plugin-server\\",\\"discription\\":\\"启动服务\\"},\\r\\n {\\"name\\":\\"init\\",\\"enable\\":true,\\"type\\":\\"package\\",\\"path\\":\\"app-lib-cli-plugin-init\\",\\"discription\\":\\"初始工程\\"},\\r\\n {\\"name\\":\\"doc\\",\\"enable\\":true,\\"type\\":\\"package\\",\\"path\\":\\"app-lib-cli-plugin-doc\\",\\"discription\\":\\"API文档\\"}\\r\\n]"}]');
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
(() => {
/**
* * commonder 命令组件
* https://github.com/tj/commander.js/blob/master/Readme_zh-CN.md
*
*/
const { initCommond } = __webpack_require__(424);
const utils = __webpack_require__(555);
let { log, commander: { Command },
utils: { action, autoRequireFile } } = utils;
// log.mi("---------内置路径:", {
// getMainPath: inner.getMainPath(),
// getRootPath: inner.getRootPath(),
// getBinPath: inner.getBinPath(),
// getBin_appbir: inner.getBin('appbir'),
// getBin_npm: inner.getBin('npm'),
// getBin_node: inner.getBin('app-lib-node'),
// })
// log.mi("---------引用路径:", {
// getMainPath: nodes.getMainPath(),
// getRootPath: nodes.getRootPath(),
// getBinPath: nodes.getBinPath(),
// getBin_appbir: nodes.getBin('appbir'),
// getBin_npm: nodes.getBin('npm'),
// getBin_node: nodes.getBin('app-lib-node'),
// })
const program = new Command();
/**
* 初始化日志
*/
log.auotLevel();
/**
* 初始化命令
*/
let { registerCommond } = initCommond({ ...utils, program });
// 获取PKG.json的配置
const PKG = autoRequireFile('package.json');
// 打印显示内容
const display = async () => {
log.mi("usage [ appbir --help ] , show support commond >")
log.T(registerCommond);
return 0;
}
/**
* appbir 的总入口命令
* 所有的debugger 命令会被外出拦截 最好不要添加其他命令
*/
program
.version(`v${PKG.version}`, '-v,--version', 'the current version')
.description('appbir personal cli tool for speed work, you can connection email for appbir@163.com')
.action(action.bind(null, { start: display, commond: PKG.name }));
log.md("run.argv", JSON.stringify(process.argv.slice(2)))
/**
* 命令解析
*/
program.parse(process.argv);
})();
/******/ return __webpack_exports__;
/******/ })()
;
});
//# sourceMappingURL=cli.js.map