1 | const Commander = function () {
|
2 | this.argvs = [];
|
3 | this.commands = [];
|
4 | this.callback = [];
|
5 | this.options = [];
|
6 | this.actions = [];
|
7 | this.isCatch = false;
|
8 | this.catchCallback = () => { };
|
9 | };
|
10 |
|
11 | Commander.prototype.option = function (option, cb) {
|
12 | this.options.push(option);
|
13 | this.callback.push(cb);
|
14 | return this;
|
15 | };
|
16 |
|
17 | Commander.prototype.command = function (cmd) {
|
18 | this.commands.push(cmd);
|
19 | return this;
|
20 | };
|
21 |
|
22 | Commander.prototype.action = function (fn) {
|
23 | const cmd = this.commands.shift();
|
24 | const length = cmd.match(/<.+?>/).length;
|
25 | this.actions.push(() => {
|
26 | if (cmd && this.argvs[0] === cmd.split(" ")[0]) {
|
27 | this.isCatch = true;
|
28 | if (this.argvs.length > length) {
|
29 | fn(...this.argvs.slice(length));
|
30 | }
|
31 | else {
|
32 | fn("app")
|
33 | }
|
34 | }
|
35 | });
|
36 | return this;
|
37 | };
|
38 |
|
39 | Commander.prototype.catch = function (fn) {
|
40 | this.catchCallback = () => {
|
41 | if (!this.isCatch) {
|
42 | fn(this.argvs);
|
43 | }
|
44 | };
|
45 | };
|
46 |
|
47 | Commander.prototype.parse = function (argvs) {
|
48 | this.argvs = argvs.slice(2);
|
49 | this.run();
|
50 | return this;
|
51 | };
|
52 |
|
53 | Commander.prototype.run = function () {
|
54 | this.options.forEach((option, index) => {
|
55 | option.split(", ").forEach(item => {
|
56 | this.argvs.forEach(argv => {
|
57 | if (argv === item) {
|
58 | const cb = this.callback[index];
|
59 | this.isCatch = true;
|
60 | if (typeof cb === "function") {
|
61 | cb();
|
62 | } else {
|
63 | console.log(cb);
|
64 | }
|
65 | }
|
66 | });
|
67 | });
|
68 | });
|
69 | this.actions.forEach(action => {
|
70 | action();
|
71 | });
|
72 | this.catchCallback();
|
73 | };
|
74 |
|
75 | module.exports = new Commander();
|