@aiot-toolkit/commander 2.0.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,168 @@
1
+ # `commander`
2
+
3
+ 仅需配置即可生成命令行工具,支持
4
+
5
+ 1. 默认命令
6
+ 1. 命令参数
7
+ 1. 询问式参数
8
+ 1. 常驻式操作
9
+
10
+ ## 询问式参数与命令参数的关系
11
+
12
+ - 询问式参数是普通参数的子集,询问式参数一定可以直接在命令中输入,以确保工具可自动化运行
13
+
14
+ * 某参数在命令中填写后,不会在询问中出现
15
+
16
+ ## 快速开始
17
+
18
+ 1. 创建配置内容
19
+
20
+ ```typescript
21
+ // bin.ts
22
+
23
+ import { Command, IProgram } from '@aiot-toolkit/commander'
24
+
25
+ const config: IProgram = {
26
+ name: 'myTool',
27
+ description: 'myTool is ...',
28
+ version: '1.0.1',
29
+ // 命令列表
30
+ commandList: [
31
+ {
32
+ // 命令名称
33
+ name: 'start',
34
+ // 命令描述
35
+ description: 'start command is ...',
36
+ // 参数列表
37
+ paramList: [
38
+ {
39
+ // 参数名称
40
+ name: 'path',
41
+ // 参数描述
42
+ description: 'path is ...',
43
+ // 是否可询问(true 表示未输入时,则询问)
44
+ enableInquirer: true
45
+ },
46
+ {
47
+ name: 'path2',
48
+ description: 'path2 is ...',
49
+ enableInquirer: true
50
+ }
51
+ ],
52
+ // 命令对应的方法
53
+ action: (option: any) => {
54
+ console.log(option)
55
+ },
56
+ // 常驻式操作
57
+ waiter: new PersistentCommand({
58
+ description: 'start 的常驻式操作',
59
+ options: [
60
+ {
61
+ // 按键
62
+ key: 'a',
63
+ description: 'a 的描述',
64
+ // 按下 a 执行的方法
65
+ action: () => {}
66
+ }
67
+ ]
68
+ })
69
+ }
70
+ ]
71
+ }
72
+
73
+ Command.registeProgram(config)
74
+ ```
75
+
76
+ 2. 执行命令
77
+
78
+ - 执行 `ts-node bin.ts start --path /Documents/temp`
79
+
80
+ * 此时,会询问 path2 的值;输入后,进入 action,输出 option
81
+
82
+ - 命令执行完成后,会显示常驻操作菜单
83
+
84
+ ## 配置
85
+
86
+ ### IProgram
87
+
88
+ | 属性 | 描述 | 类型 | 必填 |
89
+ | -------------- | ---------------------------------- | ---------- | ----- |
90
+ | name | 工具名称 | string | true |
91
+ | description | 工具描述 | string | true |
92
+ | version | 版本号 | string | true |
93
+ | defaultCommand | 默认命令,无命令名称时,执行此命令 | ICommand | false |
94
+ | commandList | 命令列表 | ICommand[] | false |
95
+
96
+ ### ICommand
97
+
98
+ | 属性 | 描述 | 类型 | 必填 |
99
+ | ------------ | -------------------------------------------------- | --------- | ----- |
100
+ | name | 命令名称 | string | true |
101
+ | description | 命令描述 | string | true |
102
+ | argumentList | 无名称参数, `tool arg1 arg2` | string[] | false |
103
+ | paramList | 有名称参数 | ParamType | false |
104
+ | action | 命令的执行函数,`action:(arg1, arg2, options)=>{}` | true |
105
+
106
+ ### ParamType
107
+
108
+ ParamType 分为4类,继承自IParam
109
+
110
+ #### IParam
111
+
112
+ 参数基础结构
113
+
114
+ | 属性 | 描述 | 类型 | 必填 |
115
+ | -------------- | ------------------ | ------- | ----- |
116
+ | name | 参数名称 | string | true |
117
+ | description | 参数描述 | string | true |
118
+ | defaultValue | 默认值 | any | false |
119
+ | enableInquirer | 是否启用交互式询问 | boolean | false |
120
+
121
+ #### 1. InputParam
122
+
123
+ 文本式参数,在IParam的基础上,增加
124
+
125
+ | 属性 | 描述 | 类型 | 必填 |
126
+ | -------- | -------------------- | -------- | ----- |
127
+ | type | 固定值 string | 'string' | true |
128
+ | validate | 校验输入合法性的方法 | Function | false |
129
+
130
+ #### 2. SelectParam
131
+
132
+ 单选参数,在 IParam 的基础上,增加
133
+
134
+ | 属性 | 描述 | 类型 | 必填 |
135
+ | ------- | ------------- | ------------------------------------------------------------------------------------------- | ---- |
136
+ | type | 固定值 select | 'select' | true |
137
+ | choices | 选项列表 | {<br/>value:选项值(必填), <br/> name:选项名称(可选),<br/>description: 描述(可选)<br/>}[] | true |
138
+
139
+ #### 3. CheckboxParam
140
+
141
+ 多选参数,在SelectParam 基础上,修改
142
+
143
+ | 属性 | 描述 | 类型 | 必填 |
144
+ | ---- | --------------- | ---------- | ---- |
145
+ | type | 固定值 checkbox | 'checkbox' | true |
146
+
147
+ #### 4. ConfirmParam
148
+
149
+ boolean 参数,在 IParam 的基础上,增加
150
+
151
+ | 属性 | 描述 | 类型 | 必填 |
152
+ | ---- | -------------- | --------- | ---- |
153
+ | type | 固定值 confirm | 'confirm' | true |
154
+
155
+ ### waiter
156
+
157
+ | 属性 | 描述 | 类型 | 必填 |
158
+ | ----------- | ------------ | ------------------------ | ---- |
159
+ | description | 常驻命令描述 | string | true |
160
+ | options | 常驻命令列表 | IPersistentCommandItem[] | true |
161
+
162
+ #### IPersistentCommandItem
163
+
164
+ | 属性 | 描述 | 类型 | 必填 |
165
+ | ----------- | -------------------- | ----------------------------- | ---- |
166
+ | key | 按键,只能是一个字符 | string | true |
167
+ | description | 描述 | string | true |
168
+ | action | 按键执行的方法 | () => Promise<void>, ()=>void | true |
@@ -0,0 +1,16 @@
1
+ import IProgram from './interface/IProgram';
2
+ declare class Command {
3
+ /**
4
+ * 注册命令行项目
5
+ * @param programConfig 配置
6
+ */
7
+ static registeProgram(programConfig: IProgram): void;
8
+ private static registeCommand;
9
+ /**
10
+ * 采集参数。 根据不同的参数类型使用不同的询问方式
11
+ * @param param
12
+ * @returns
13
+ */
14
+ private static collectParam;
15
+ }
16
+ export default Command;
package/lib/Command.js ADDED
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const StringUtil_1 = __importDefault(require("@aiot-toolkit/shared-utils/lib/utils/StringUtil"));
16
+ const prompts_1 = require("@inquirer/prompts");
17
+ const commander_1 = require("commander");
18
+ class Command {
19
+ /**
20
+ * 注册命令行项目
21
+ * @param programConfig 配置
22
+ */
23
+ static registeProgram(programConfig) {
24
+ const { name, description, version, commandList, defaultCommand } = programConfig;
25
+ commander_1.program.name(name).description(description).version(version);
26
+ if (defaultCommand) {
27
+ this.registeCommand(defaultCommand);
28
+ }
29
+ if (commandList) {
30
+ commandList.forEach((item) => {
31
+ Command.registeCommand(item);
32
+ });
33
+ }
34
+ commander_1.program.parse();
35
+ }
36
+ static registeCommand(command) {
37
+ const { name, description, argumentList, action, paramList, waiter } = command;
38
+ const instance = name ? commander_1.program.command(name).description(description) : commander_1.program;
39
+ // 设置argument
40
+ argumentList === null || argumentList === void 0 ? void 0 : argumentList.forEach((item) => {
41
+ const { name, description, defaultValue } = item;
42
+ instance.argument(name, description, defaultValue);
43
+ });
44
+ // 设置option
45
+ paramList === null || paramList === void 0 ? void 0 : paramList.forEach((item) => {
46
+ const { type, name, description, defaultValue } = item;
47
+ const effectName = type === 'confirm' ? `--${name}` : `--${name} <value>`;
48
+ instance.option(effectName, description, defaultValue);
49
+ });
50
+ // 设置交互式问题
51
+ instance.action((...args) => __awaiter(this, void 0, void 0, function* () {
52
+ let option = args[args.length - 2];
53
+ if (paramList) {
54
+ for (let item of paramList) {
55
+ const { name, enableInquirer } = item;
56
+ const cameName = StringUtil_1.default.middleLinetoCame(name);
57
+ const valueSource = instance.getOptionValueSource(cameName);
58
+ const haveSet = valueSource && valueSource !== 'default';
59
+ // 如果启用询问,且未已显式设置值,则通过询问收集参数
60
+ if (enableInquirer && !haveSet) {
61
+ const result = yield this.collectParam(item);
62
+ if (result) {
63
+ for (let key in result) {
64
+ option[key] = result[key];
65
+ }
66
+ }
67
+ }
68
+ }
69
+ }
70
+ yield action.apply(null, args);
71
+ if (waiter) {
72
+ waiter.describe();
73
+ waiter.start();
74
+ }
75
+ }));
76
+ }
77
+ /**
78
+ * 采集参数。 根据不同的参数类型使用不同的询问方式
79
+ * @param param
80
+ * @returns
81
+ */
82
+ static collectParam(param) {
83
+ return __awaiter(this, void 0, void 0, function* () {
84
+ const { name, description, type, defaultValue } = param;
85
+ const cameName = StringUtil_1.default.middleLinetoCame(name);
86
+ let result;
87
+ switch (type) {
88
+ case 'string':
89
+ const { validate } = param;
90
+ result = yield (0, prompts_1.input)(Object.assign({ message: description, default: defaultValue === null || defaultValue === void 0 ? void 0 : defaultValue.toString() }, (validate ? { validate } : {})));
91
+ break;
92
+ case 'confirm':
93
+ result = yield (0, prompts_1.confirm)({ message: description, default: Boolean(defaultValue) });
94
+ break;
95
+ case 'select':
96
+ result = yield (0, prompts_1.select)({
97
+ message: description,
98
+ choices: param.choices
99
+ });
100
+ break;
101
+ case 'checkbox':
102
+ result = yield (0, prompts_1.checkbox)({
103
+ message: description,
104
+ choices: param.choices
105
+ });
106
+ break;
107
+ default:
108
+ break;
109
+ }
110
+ return {
111
+ [cameName]: result
112
+ };
113
+ });
114
+ }
115
+ }
116
+ exports.default = Command;
117
+
118
+ //# sourceMappingURL=Command.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["Command.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,iGAAwE;AACxE,+CAAoE;AACpE,yCAAmC;AAKnC,MAAM,OAAO;IACX;;;OAGG;IACH,MAAM,CAAC,cAAc,CAAC,aAAuB;QAC3C,MAAM,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,GAAG,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E,YAAY,EAAE,GAAG,KAAK,CAAA;YACvD,MAAM,QAAQ,GAAG,oBAAU,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAA;YAClD,IAAI,MAAW,CAAA;YACf,QAAQ,IAAI,EAAE;gBACZ,KAAK,QAAQ;oBACX,MAAM,EAAE,QAAQ,EAAE,GAAG,KAAK,CAAA;oBAC1B,MAAM,GAAG,MAAM,IAAA,eAAK,kBAClB,OAAO,EAAE,WAAW,EACpB,OAAO,EAAE,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,QAAQ,EAAE,IAC9B,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EACjC,CAAA;oBACF,MAAK;gBACP,KAAK,SAAS;oBACZ,MAAM,GAAG,MAAM,IAAA,iBAAO,EAAC,EAAE,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,OAAO,CAAC,YAAY,CAAC,EAAE,CAAC,CAAA;oBAChF,MAAK;gBACP,KAAK,QAAQ;oBACX,MAAM,GAAG,MAAM,IAAA,gBAAM,EAAC;wBACpB,OAAO,EAAE,WAAW;wBACpB,OAAO,EAAE,KAAK,CAAC,OAAO;qBACvB,CAAC,CAAA;oBACF,MAAK;gBACP,KAAK,UAAU;oBACb,MAAM,GAAG,MAAM,IAAA,kBAAQ,EAAC;wBACtB,OAAO,EAAE,WAAW;wBACpB,OAAO,EAAE,KAAK,CAAC,OAAO;qBACvB,CAAC,CAAA;oBACF,MAAK;gBACP;oBACE,MAAK;aACR;YAED,OAAO;gBACL,CAAC,QAAQ,CAAC,EAAE,MAAM;aACnB,CAAA;QACH,CAAC;KAAA;CACF;AAED,kBAAe,OAAO,CAAA","file":"Command.js","sourcesContent":["import StringUtil from '@aiot-toolkit/shared-utils/lib/utils/StringUtil'\nimport { checkbox, confirm, input, select } from '@inquirer/prompts'\nimport { program } from 'commander'\nimport ICommand from './interface/ICommand'\nimport ParamType from './interface/IParam'\nimport IProgram from './interface/IProgram'\n\nclass Command {\n /**\n * 注册命令行项目\n * @param programConfig 配置\n */\n static registeProgram(programConfig: IProgram) {\n const { name, description, version, commandList, defaultCommand } = programConfig\n\n program.name(name).description(description).version(version)\n if (defaultCommand) {\n this.registeCommand(defaultCommand)\n }\n\n if (commandList) {\n commandList.forEach((item) => {\n Command.registeCommand(item)\n })\n }\n\n program.parse()\n }\n\n private static registeCommand(command: ICommand) {\n const { name, description, argumentList, action, paramList, waiter } = command\n\n const instance = name ? program.command(name).description(description) : program\n\n // 设置argument\n argumentList?.forEach((item) => {\n const { name, description, defaultValue } = item\n instance.argument(name, description, defaultValue)\n })\n\n // 设置option\n paramList?.forEach((item) => {\n const { type, name, description, defaultValue } = item\n const effectName = type === 'confirm' ? `--${name}` : `--${name} <value>`\n instance.option(effectName, description, defaultValue)\n })\n\n // 设置交互式问题\n instance.action(async (...args: any) => {\n let option = args[args.length - 2]\n if (paramList) {\n for (let item of paramList) {\n const { name, enableInquirer } = item\n\n const cameName = StringUtil.middleLinetoCame(name)\n\n const valueSource = instance.getOptionValueSource(cameName)\n const haveSet = valueSource && valueSource !== 'default'\n // 如果启用询问,且未已显式设置值,则通过询问收集参数\n if (enableInquirer && !haveSet) {\n const result = await this.collectParam(item)\n if (result) {\n for (let key in result) {\n option[key] = result[key]\n }\n }\n }\n }\n }\n await action.apply(null, args)\n\n if (waiter) {\n waiter.describe()\n waiter.start()\n }\n })\n }\n\n /**\n * 采集参数。 根据不同的参数类型使用不同的询问方式\n * @param param\n * @returns\n */\n private static async collectParam(param: ParamType) {\n const { name, description, type, defaultValue } = param\n const cameName = StringUtil.middleLinetoCame(name)\n let result: any\n switch (type) {\n case 'string':\n const { validate } = param\n result = await input({\n message: description,\n default: defaultValue?.toString(),\n ...(validate ? { validate } : {})\n })\n break\n case 'confirm':\n result = await confirm({ message: description, default: Boolean(defaultValue) })\n break\n case 'select':\n result = await select({\n message: description,\n choices: param.choices\n })\n break\n case 'checkbox':\n result = await checkbox({\n message: description,\n choices: param.choices\n })\n break\n default:\n break\n }\n\n return {\n [cameName]: result\n }\n }\n}\n\nexport default Command\n"],"sourceRoot":"../src"}
package/lib/index.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ export { default as Command } from './Command';
2
+ export { default as ICommand } from './interface/ICommand';
3
+ export { default as IParam } from './interface/IParam';
4
+ export { default as IProgram } from './interface/IProgram';
5
+ export { default as IPersistentCommandData } from './persistentCommand/IPersistentCommandData';
6
+ export { default as PersistentCommand } from './persistentCommand/PersistentCommand';
package/lib/index.js ADDED
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.PersistentCommand = exports.Command = void 0;
7
+ var Command_1 = require("./Command");
8
+ Object.defineProperty(exports, "Command", { enumerable: true, get: function () { return __importDefault(Command_1).default; } });
9
+ var PersistentCommand_1 = require("./persistentCommand/PersistentCommand");
10
+ Object.defineProperty(exports, "PersistentCommand", { enumerable: true, get: function () { return __importDefault(PersistentCommand_1).default; } });
11
+
12
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["index.ts"],"names":[],"mappings":";;;;;;AAAA,qCAA8C;AAArC,mHAAA,OAAO,OAAW;AAK3B,2EAAoF;AAA3E,uIAAA,OAAO,OAAqB","file":"index.js","sourcesContent":["export { default as Command } from './Command'\nexport { default as ICommand } from './interface/ICommand'\nexport { default as IParam } from './interface/IParam'\nexport { default as IProgram } from './interface/IProgram'\nexport { default as IPersistentCommandData } from './persistentCommand/IPersistentCommandData'\nexport { default as PersistentCommand } from './persistentCommand/PersistentCommand'\n"],"sourceRoot":"../src"}
@@ -0,0 +1,78 @@
1
+ import PersistentCommand from '../persistentCommand/PersistentCommand';
2
+ import ParamType from './IParam';
3
+ /**
4
+ * 命令
5
+ *
6
+ * @description 用于定义一条命令,其中
7
+ * + argumentList 表示有序的必填参数
8
+ * ```js
9
+ * // 设置
10
+ * name arg1 arg2
11
+ *
12
+ * // 获取
13
+ * action(arg1, arg2) => { }
14
+ * ```
15
+ * + paramList 表示无序的参数
16
+ *
17
+ * paramList的参数有两种途径设置
18
+ * 1. 输入命令时:所有参数都可通过此途径设置
19
+ * 2. 询问式设置:enableInquirer=true,且未通过途径1设置的参数
20
+ * ```
21
+ * // 设置
22
+ * name arg1 arg2 --option1 value
23
+ *
24
+ * // 获取
25
+ * action(arg1, arg2, options) => {
26
+ * console.log(options.option1)
27
+ * }
28
+ * ```
29
+ *
30
+ * @example 对于命令`mytool exec arg1 --option1 123`,且希望option1未设置时,可通过询问的方式的设置,则配置如下
31
+ * ```
32
+ * {
33
+ * name:"exec",
34
+ * description:"命令描述",
35
+ * argumentList:[
36
+ * {
37
+ * name: "arg1",
38
+ * description:"",
39
+ * }
40
+ * ],
41
+ * paramList:[
42
+ * {
43
+ * name: "option1",
44
+ * type: "string",
45
+ * description: "",
46
+ * enableInquirer: true,
47
+ * }
48
+ * ],
49
+ * action: (arg, option) = >{}
50
+ * }
51
+ * ```
52
+ */
53
+ export default interface ICommand {
54
+ name: string;
55
+ description: string;
56
+ argumentList?: {
57
+ name: string;
58
+ description: string;
59
+ defaultValue?: string;
60
+ }[];
61
+ paramList?: ParamType[];
62
+ /**
63
+ * 待者命令
64
+ *
65
+ * 一个按键对应一个功能
66
+ *
67
+ * 如设置此属性,当主命令执行完成后,此命令将启动
68
+ */
69
+ waiter?: PersistentCommand;
70
+ /**
71
+ * 命令完成后的处理函数
72
+ * @param arg 参数列表,依次为argumentList[0], argumentList[1]...., param对象
73
+ *
74
+ * @example action(arg1, arg2, option)=>{}
75
+ * @returns
76
+ */
77
+ action: (...arg: any) => void | Promise<void>;
78
+ }
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+
4
+ //# sourceMappingURL=ICommand.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["interface/ICommand.ts"],"names":[],"mappings":"","file":"ICommand.js","sourcesContent":["import PersistentCommand from '../persistentCommand/PersistentCommand'\nimport ParamType from './IParam'\n\n/**\n * 命令\n *\n * @description 用于定义一条命令,其中\n * + argumentList 表示有序的必填参数\n * ```js\n * // 设置\n * name arg1 arg2\n *\n * // 获取\n * action(arg1, arg2) => { }\n * ```\n * + paramList 表示无序的参数\n *\n * paramList的参数有两种途径设置\n * 1. 输入命令时:所有参数都可通过此途径设置\n * 2. 询问式设置:enableInquirer=true,且未通过途径1设置的参数\n * ```\n * // 设置\n * name arg1 arg2 --option1 value\n *\n * // 获取\n * action(arg1, arg2, options) => {\n * console.log(options.option1)\n * }\n * ```\n *\n * @example 对于命令`mytool exec arg1 --option1 123`,且希望option1未设置时,可通过询问的方式的设置,则配置如下\n * ```\n * {\n * name:\"exec\",\n * description:\"命令描述\",\n * argumentList:[\n * {\n * name: \"arg1\",\n * description:\"\",\n * }\n * ],\n * paramList:[\n * {\n * name: \"option1\",\n * type: \"string\",\n * description: \"\",\n * enableInquirer: true,\n * }\n * ],\n * action: (arg, option) = >{}\n * }\n * ```\n */\nexport default interface ICommand {\n name: string\n description: string\n\n argumentList?: {\n name: string\n description: string\n defaultValue?: string\n }[]\n\n paramList?: ParamType[]\n\n /**\n * 待者命令\n *\n * 一个按键对应一个功能\n *\n * 如设置此属性,当主命令执行完成后,此命令将启动\n */\n waiter?: PersistentCommand\n\n /**\n * 命令完成后的处理函数\n * @param arg 参数列表,依次为argumentList[0], argumentList[1]...., param对象\n *\n * @example action(arg1, arg2, option)=>{}\n * @returns\n */\n action: (...arg: any) => void | Promise<void>\n}\n"],"sourceRoot":"../../src"}
@@ -0,0 +1,65 @@
1
+ /**
2
+ * 参数基础结构
3
+ */
4
+ interface IParam {
5
+ /**
6
+ * 参数名
7
+ */
8
+ name: string;
9
+ /**
10
+ * 描述,为保证规范,设置为必填
11
+ */
12
+ description: string;
13
+ /**
14
+ * 默认值
15
+ */
16
+ defaultValue?: any;
17
+ /**
18
+ * 是否启用交互式询问
19
+ *
20
+ * 如果启用 且 未在命令中填写;则会进行询问
21
+ */
22
+ enableInquirer?: boolean;
23
+ }
24
+ /**
25
+ * 选项参数
26
+ */
27
+ interface ChoiceParam extends IParam {
28
+ choices: {
29
+ value: string | number;
30
+ name?: string;
31
+ description?: string;
32
+ }[];
33
+ }
34
+ /**
35
+ * 输入文本参数
36
+ */
37
+ interface InputParam extends IParam {
38
+ type?: 'string';
39
+ /**
40
+ * 校验参数值
41
+ * @param value
42
+ * @returns
43
+ */
44
+ validate?: (value: string) => boolean | string | Promise<boolean | string>;
45
+ }
46
+ /**
47
+ * boolean 参数
48
+ */
49
+ interface ConfirmParam extends IParam {
50
+ type: 'confirm';
51
+ }
52
+ /**
53
+ * 单选参数
54
+ */
55
+ interface SelectParam extends ChoiceParam {
56
+ type: 'select';
57
+ }
58
+ /**
59
+ * 多选参数
60
+ */
61
+ interface CheckboxParam extends ChoiceParam {
62
+ type: 'checkbox';
63
+ }
64
+ type ParamType = InputParam | SelectParam | CheckboxParam | ConfirmParam;
65
+ export default ParamType;
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+
4
+ //# sourceMappingURL=IParam.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["interface/IParam.ts"],"names":[],"mappings":"","file":"IParam.js","sourcesContent":["/**\n * 参数基础结构\n */\ninterface IParam {\n /**\n * 参数名\n */\n name: string\n\n /**\n * 描述,为保证规范,设置为必填\n */\n description: string\n\n /**\n * 默认值\n */\n defaultValue?: any\n\n /**\n * 是否启用交互式询问\n *\n * 如果启用 且 未在命令中填写;则会进行询问\n */\n enableInquirer?: boolean\n}\n\n/**\n * 选项参数\n */\ninterface ChoiceParam extends IParam {\n choices: {\n value: string | number\n name?: string\n description?: string\n }[]\n}\n\n/**\n * 输入文本参数\n */\ninterface InputParam extends IParam {\n type?: 'string'\n\n /**\n * 校验参数值\n * @param value\n * @returns\n */\n validate?: (value: string) => boolean | string | Promise<boolean | string>\n}\n\n/**\n * boolean 参数\n */\ninterface ConfirmParam extends IParam {\n type: 'confirm'\n}\n\n/**\n * 单选参数\n */\ninterface SelectParam extends ChoiceParam {\n type: 'select'\n}\n\n/**\n * 多选参数\n */\ninterface CheckboxParam extends ChoiceParam {\n type: 'checkbox'\n}\n\ntype ParamType = InputParam | SelectParam | CheckboxParam | ConfirmParam\n\nexport default ParamType\n"],"sourceRoot":"../../src"}
@@ -0,0 +1,18 @@
1
+ import ICommand from './ICommand';
2
+ /**
3
+ * 命令行项目
4
+ *
5
+ */
6
+ interface IProgram {
7
+ name: string;
8
+ description: string;
9
+ version: string;
10
+ defaultCommand?: ICommand;
11
+ /**
12
+ * 命令列表
13
+ *
14
+ * @see ICommand
15
+ */
16
+ commandList?: ICommand[];
17
+ }
18
+ export default IProgram;
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+
4
+ //# sourceMappingURL=IProgram.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["interface/IProgram.ts"],"names":[],"mappings":"","file":"IProgram.js","sourcesContent":["import ICommand from './ICommand'\n\n/**\n * 命令行项目\n *\n */\ninterface IProgram {\n name: string\n description: string\n version: string\n defaultCommand?: ICommand\n\n /**\n * 命令列表\n *\n * @see ICommand\n */\n commandList?: ICommand[]\n}\n\nexport default IProgram\n"],"sourceRoot":"../../src"}
@@ -0,0 +1,10 @@
1
+ interface IPersistentCommandItem {
2
+ key: string;
3
+ description: string;
4
+ action: () => Promise<void> | void;
5
+ }
6
+ interface IPersistentCommandData {
7
+ options: IPersistentCommandItem[];
8
+ description: string;
9
+ }
10
+ export default IPersistentCommandData;
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+
4
+ //# sourceMappingURL=IPersistentCommandData.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["persistentCommand/IPersistentCommandData.ts"],"names":[],"mappings":"","file":"IPersistentCommandData.js","sourcesContent":["interface IPersistentCommandItem {\n key: string\n description: string\n action: () => Promise<void> | void\n}\n\ninterface IPersistentCommandData {\n options: IPersistentCommandItem[]\n description: string\n}\n\nexport default IPersistentCommandData\n"],"sourceRoot":"../../src"}
@@ -0,0 +1,14 @@
1
+ import IPersistentCommandData from './IPersistentCommandData';
2
+ declare class PersistentCommand {
3
+ private readonly data;
4
+ private running;
5
+ private actionRunning;
6
+ constructor(data: IPersistentCommandData);
7
+ start(): void;
8
+ private dataHandler;
9
+ stop(): void;
10
+ private writeLine;
11
+ describe(): void;
12
+ clearLog(): void;
13
+ }
14
+ export default PersistentCommand;
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const chalk_1 = __importDefault(require("chalk"));
16
+ const CTRL_C = '\u0003';
17
+ const CTRL_L = '\u000C';
18
+ const BLT = '\u203A';
19
+ class PersistentCommand {
20
+ constructor(data) {
21
+ this.data = data;
22
+ this.running = false;
23
+ this.actionRunning = false;
24
+ this.dataHandler = (data) => __awaiter(this, void 0, void 0, function* () {
25
+ switch (data) {
26
+ case CTRL_C:
27
+ process.exit();
28
+ break;
29
+ case CTRL_L:
30
+ this.clearLog();
31
+ break;
32
+ default:
33
+ if (this.actionRunning) {
34
+ console.log(chalk_1.default.yellow(`Wait for the task to complete`));
35
+ return;
36
+ }
37
+ const item = this.data.options.find((item) => item.key === data);
38
+ if (item) {
39
+ this.actionRunning = true;
40
+ try {
41
+ yield item.action();
42
+ }
43
+ catch (error) {
44
+ console.error(error);
45
+ }
46
+ this.actionRunning = false;
47
+ }
48
+ break;
49
+ }
50
+ });
51
+ }
52
+ start() {
53
+ if (this.running) {
54
+ return;
55
+ }
56
+ const { stdin } = process;
57
+ stdin.setRawMode(true);
58
+ stdin.resume();
59
+ stdin.setEncoding('utf8');
60
+ stdin.on('data', this.dataHandler);
61
+ this.running = true;
62
+ }
63
+ stop() {
64
+ const { stdin } = process;
65
+ stdin.removeListener('data', this.dataHandler);
66
+ stdin.setRawMode(false);
67
+ stdin.resume();
68
+ this.running = false;
69
+ }
70
+ writeLine() {
71
+ const str = new Array(30)
72
+ .fill(0)
73
+ .map(() => '-')
74
+ .join('');
75
+ console.log(chalk_1.default.dim(str));
76
+ }
77
+ describe() {
78
+ const { description, options } = this.data;
79
+ this.writeLine();
80
+ // 输出描述
81
+ console.log(chalk_1.default.green(description));
82
+ console.log('');
83
+ // 输出命令列表
84
+ options.forEach((item) => {
85
+ const { key, description } = item;
86
+ console.log(`${BLT} ${chalk_1.default.bold(key)} | ${description}`);
87
+ });
88
+ // 输出退出的方法
89
+ console.log();
90
+ console.log(chalk_1.default.dim(`Press Ctrl+C to exit.`));
91
+ this.writeLine();
92
+ }
93
+ clearLog() {
94
+ process.stdout.write(process.platform === 'win32' ? '\x1B[2J\x1B[0f' : '\x1B[2J\x1B[3J\x1B[H');
95
+ }
96
+ }
97
+ exports.default = PersistentCommand;
98
+
99
+ //# sourceMappingURL=PersistentCommand.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["persistentCommand/PersistentCommand.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,kDAAyB;AAGzB,MAAM,MAAM,GAAG,QAAQ,CAAA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;QACV,OAAO,CAAC,GAAG,EAAE,CAAA;QACb,OAAO,CAAC,GAAG,CAAC,eAAK,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAC,CAAA;QAC/C,IAAI,CAAC,SAAS,EAAE,CAAA;IAClB,CAAC;IAED,QAAQ;QACN,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC,sBAAsB,CAAC,CAAA;IAChG,CAAC;CACF;AAED,kBAAe,iBAAiB,CAAA","file":"PersistentCommand.js","sourcesContent":["import chalk from 'chalk'\nimport IPersistentCommandData from './IPersistentCommandData'\n\nconst CTRL_C = '\\u0003'\nconst CTRL_L = '\\u000C'\nconst BLT = '\\u203A'\n\nclass PersistentCommand {\n private running = false\n private actionRunning = false\n constructor(private readonly data: IPersistentCommandData) {}\n\n start() {\n if (this.running) {\n return\n }\n const { stdin } = process\n stdin.setRawMode(true)\n stdin.resume()\n stdin.setEncoding('utf8')\n stdin.on('data', this.dataHandler)\n\n this.running = true\n }\n\n private dataHandler = async (data: any) => {\n switch (data) {\n case CTRL_C:\n process.exit()\n break\n case CTRL_L:\n this.clearLog()\n break\n default:\n if (this.actionRunning) {\n console.log(chalk.yellow(`Wait for the task to complete`))\n return\n }\n const item = this.data.options.find((item) => item.key === data)\n if (item) {\n this.actionRunning = true\n try {\n await item.action()\n } catch (error) {\n console.error(error)\n }\n this.actionRunning = false\n }\n break\n }\n }\n\n stop() {\n const { stdin } = process\n stdin.removeListener('data', this.dataHandler)\n stdin.setRawMode(false)\n stdin.resume()\n this.running = false\n }\n\n private writeLine() {\n const str = new Array(30)\n .fill(0)\n .map(() => '-')\n .join('')\n console.log(chalk.dim(str))\n }\n\n describe() {\n const { description, options } = this.data\n this.writeLine()\n // 输出描述\n console.log(chalk.green(description))\n console.log('')\n\n // 输出命令列表\n options.forEach((item) => {\n const { key, description } = item\n console.log(`${BLT} ${chalk.bold(key)} | ${description}`)\n })\n\n // 输出退出的方法\n console.log()\n console.log(chalk.dim(`Press Ctrl+C to exit.`))\n this.writeLine()\n }\n\n clearLog() {\n process.stdout.write(process.platform === 'win32' ? '\\x1B[2J\\x1B[0f' : '\\x1B[2J\\x1B[3J\\x1B[H')\n }\n}\n\nexport default PersistentCommand\n"],"sourceRoot":"../../src"}
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@aiot-toolkit/commander",
3
+ "version": "2.0.1-alpha.0",
4
+ "description": "A tool that generates complete commands with configuration",
5
+ "keywords": [
6
+ "aiot",
7
+ "commander"
8
+ ],
9
+ "homepage": "",
10
+ "license": "ISC",
11
+ "main": "lib/index",
12
+ "directories": {
13
+ "lib": "lib",
14
+ "test": "__tests__"
15
+ },
16
+ "files": [
17
+ "lib"
18
+ ],
19
+ "scripts": {
20
+ "test": "node ./__tests__/commander.test.js"
21
+ },
22
+ "dependencies": {
23
+ "@aiot-toolkit/shared-utils": "2.0.1-alpha.0",
24
+ "@inquirer/prompts": "^3.0.3",
25
+ "commander": "^11.0.0"
26
+ },
27
+ "gitHead": "cde5c75fa09622188ee4f1322ff9d53faf4d8520"
28
+ }