File size: 8,133 Bytes
369fac9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import { EventEmitter } from "https://deno.land/std@0.114.0/node/events.ts";
import mri from "https://cdn.skypack.dev/mri";
import Command, { GlobalCommand, CommandConfig, HelpCallback, CommandExample } from "./Command.ts";
import { OptionConfig } from "./Option.ts";
import { getMriOptions, setDotProp, setByType, getFileName, camelcaseOptionName } from "./utils.ts";
import { processArgs } from "./deno.ts";
interface ParsedArgv {
  args: ReadonlyArray<string>;
  options: {
    [k: string]: any;
  };
}

class CAC extends EventEmitter {
  /** The program name to display in help and version message */
  name: string;
  commands: Command[];
  globalCommand: GlobalCommand;
  matchedCommand?: Command;
  matchedCommandName?: string;
  /**
   * Raw CLI arguments
   */

  rawArgs: string[];
  /**
   * Parsed CLI arguments
   */

  args: ParsedArgv['args'];
  /**
   * Parsed CLI options, camelCased
   */

  options: ParsedArgv['options'];
  showHelpOnExit?: boolean;
  showVersionOnExit?: boolean;
  /**
   * @param name The program name to display in help and version message
   */

  constructor(name = '') {
    super();
    this.name = name;
    this.commands = [];
    this.rawArgs = [];
    this.args = [];
    this.options = {};
    this.globalCommand = new GlobalCommand(this);
    this.globalCommand.usage('<command> [options]');
  }
  /**
   * Add a global usage text.
   *
   * This is not used by sub-commands.
   */


  usage(text: string) {
    this.globalCommand.usage(text);
    return this;
  }
  /**
   * Add a sub-command
   */


  command(rawName: string, description?: string, config?: CommandConfig) {
    const command = new Command(rawName, description || '', config, this);
    command.globalCommand = this.globalCommand;
    this.commands.push(command);
    return command;
  }
  /**
   * Add a global CLI option.
   *
   * Which is also applied to sub-commands.
   */


  option(rawName: string, description: string, config?: OptionConfig) {
    this.globalCommand.option(rawName, description, config);
    return this;
  }
  /**
   * Show help message when `-h, --help` flags appear.
   *
   */


  help(callback?: HelpCallback) {
    this.globalCommand.option('-h, --help', 'Display this message');
    this.globalCommand.helpCallback = callback;
    this.showHelpOnExit = true;
    return this;
  }
  /**
   * Show version number when `-v, --version` flags appear.
   *
   */


  version(version: string, customFlags = '-v, --version') {
    this.globalCommand.version(version, customFlags);
    this.showVersionOnExit = true;
    return this;
  }
  /**
   * Add a global example.
   *
   * This example added here will not be used by sub-commands.
   */


  example(example: CommandExample) {
    this.globalCommand.example(example);
    return this;
  }
  /**
   * Output the corresponding help message
   * When a sub-command is matched, output the help message for the command
   * Otherwise output the global one.
   *
   */


  outputHelp() {
    if (this.matchedCommand) {
      this.matchedCommand.outputHelp();
    } else {
      this.globalCommand.outputHelp();
    }
  }
  /**
   * Output the version number.
   *
   */


  outputVersion() {
    this.globalCommand.outputVersion();
  }

  private setParsedInfo({
    args,
    options
  }: ParsedArgv, matchedCommand?: Command, matchedCommandName?: string) {
    this.args = args;
    this.options = options;

    if (matchedCommand) {
      this.matchedCommand = matchedCommand;
    }

    if (matchedCommandName) {
      this.matchedCommandName = matchedCommandName;
    }

    return this;
  }

  unsetMatchedCommand() {
    this.matchedCommand = undefined;
    this.matchedCommandName = undefined;
  }
  /**
   * Parse argv
   */


  parse(argv = processArgs, {
    /** Whether to run the action for matched command */
    run = true
  } = {}): ParsedArgv {
    this.rawArgs = argv;

    if (!this.name) {
      this.name = argv[1] ? getFileName(argv[1]) : 'cli';
    }

    let shouldParse = true; // Search sub-commands

    for (const command of this.commands) {
      const parsed = this.mri(argv.slice(2), command);
      const commandName = parsed.args[0];

      if (command.isMatched(commandName)) {
        shouldParse = false;
        const parsedInfo = { ...parsed,
          args: parsed.args.slice(1)
        };
        this.setParsedInfo(parsedInfo, command, commandName);
        this.emit(`command:${commandName}`, command);
      }
    }

    if (shouldParse) {
      // Search the default command
      for (const command of this.commands) {
        if (command.name === '') {
          shouldParse = false;
          const parsed = this.mri(argv.slice(2), command);
          this.setParsedInfo(parsed, command);
          this.emit(`command:!`, command);
        }
      }
    }

    if (shouldParse) {
      const parsed = this.mri(argv.slice(2));
      this.setParsedInfo(parsed);
    }

    if (this.options.help && this.showHelpOnExit) {
      this.outputHelp();
      run = false;
      this.unsetMatchedCommand();
    }

    if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
      this.outputVersion();
      run = false;
      this.unsetMatchedCommand();
    }

    const parsedArgv = {
      args: this.args,
      options: this.options
    };

    if (run) {
      this.runMatchedCommand();
    }

    if (!this.matchedCommand && this.args[0]) {
      this.emit('command:*');
    }

    return parsedArgv;
  }

  private mri(argv: string[],
  /** Matched command */
  command?: Command): ParsedArgv {
    // All added options
    const cliOptions = [...this.globalCommand.options, ...(command ? command.options : [])];
    const mriOptions = getMriOptions(cliOptions); // Extract everything after `--` since mri doesn't support it

    let argsAfterDoubleDashes: string[] = [];
    const doubleDashesIndex = argv.indexOf('--');

    if (doubleDashesIndex > -1) {
      argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
      argv = argv.slice(0, doubleDashesIndex);
    }

    let parsed = mri(argv, mriOptions);
    parsed = Object.keys(parsed).reduce((res, name) => {
      return { ...res,
        [camelcaseOptionName(name)]: parsed[name]
      };
    }, {
      _: []
    });
    const args = parsed._;
    const options: {
      [k: string]: any;
    } = {
      '--': argsAfterDoubleDashes
    }; // Set option default value

    const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
    let transforms = Object.create(null);

    for (const cliOption of cliOptions) {
      if (!ignoreDefault && cliOption.config.default !== undefined) {
        for (const name of cliOption.names) {
          options[name] = cliOption.config.default;
        }
      } // If options type is defined


      if (Array.isArray(cliOption.config.type)) {
        if (transforms[cliOption.name] === undefined) {
          transforms[cliOption.name] = Object.create(null);
          transforms[cliOption.name]['shouldTransform'] = true;
          transforms[cliOption.name]['transformFunction'] = cliOption.config.type[0];
        }
      }
    } // Set option values (support dot-nested property name)


    for (const key of Object.keys(parsed)) {
      if (key !== '_') {
        const keys = key.split('.');
        setDotProp(options, keys, parsed[key]);
        setByType(options, transforms);
      }
    }

    return {
      args,
      options
    };
  }

  runMatchedCommand() {
    const {
      args,
      options,
      matchedCommand: command
    } = this;
    if (!command || !command.commandAction) return;
    command.checkUnknownOptions();
    command.checkOptionValue();
    command.checkRequiredArgs();
    const actionArgs: any[] = [];
    command.args.forEach((arg, index) => {
      if (arg.variadic) {
        actionArgs.push(args.slice(index));
      } else {
        actionArgs.push(args[index]);
      }
    });
    actionArgs.push(options);
    return command.commandAction.apply(this, actionArgs);
  }

}

export default CAC;