| 
 | 1 | +'use strict';  | 
 | 2 | + | 
 | 3 | +var arrayify = require('array-back');  | 
 | 4 | + | 
 | 5 | +/**  | 
 | 6 | + * A module for testing for and extracting names from options (e.g. `--one`, `-o`)  | 
 | 7 | + */  | 
 | 8 | + | 
 | 9 | +class Arg {  | 
 | 10 | +  constructor (re) {  | 
 | 11 | +    this.re = re;  | 
 | 12 | +  }  | 
 | 13 | + | 
 | 14 | +  test (arg) {  | 
 | 15 | +    return this.re.test(arg)  | 
 | 16 | +  }  | 
 | 17 | +}  | 
 | 18 | + | 
 | 19 | +const isShort = new Arg(/^-([^\d-])$/);  | 
 | 20 | +const isLong = new Arg(/^--(\S+)/);  | 
 | 21 | +const isCombined = new Arg(/^-([^\d-]{2,})$/);  | 
 | 22 | +const isOption = function (arg) {  | 
 | 23 | +  return isShort.test(arg) || isLong.test(arg) || isCombined.test(arg)  | 
 | 24 | +};  | 
 | 25 | + | 
 | 26 | +/**  | 
 | 27 | + * @module command-line-commands  | 
 | 28 | + * @example  | 
 | 29 | + * const commandLineCommands = require('command-line-commands')  | 
 | 30 | + */  | 
 | 31 | + | 
 | 32 | +/**  | 
 | 33 | + * Parses the `argv` value supplied (or `process.argv` by default), extracting and returning the `command` and remainder of `argv`. The command will be the first value in the `argv` array unless it is an option (e.g. `--help`).  | 
 | 34 | + *  | 
 | 35 | + * @param {string|string[]} - One or more command strings, one of which the user must supply. Include `null` to represent "no command" (effectively making a command optional).  | 
 | 36 | + * @param [argv] {string[]} - An argv array, defaults to the global `process.argv` if not supplied.  | 
 | 37 | + * @returns {{ command: string, argv: string[] }}  | 
 | 38 | + * @throws `INVALID_COMMAND` - user supplied a command not specified in `commands`.  | 
 | 39 | + * @alias module:command-line-commands  | 
 | 40 | + */  | 
 | 41 | +function commandLineCommands (commands, argv) {  | 
 | 42 | +  if (!commands || (Array.isArray(commands) && !commands.length)) {  | 
 | 43 | +    throw new Error('Please supply one or more commands')  | 
 | 44 | +  }  | 
 | 45 | +  if (argv) {  | 
 | 46 | +    argv = arrayify(argv);  | 
 | 47 | +  } else {  | 
 | 48 | +    /* if no argv supplied, assume we are parsing process.argv. */  | 
 | 49 | +    /* never modify the global process.argv directly. */  | 
 | 50 | +    argv = process.argv.slice(0);  | 
 | 51 | +    argv.splice(0, 2);  | 
 | 52 | +  }  | 
 | 53 | + | 
 | 54 | +  /* the command is the first arg, unless it's an option (e.g. --help) */  | 
 | 55 | +  const command = (isOption(argv[0]) || !argv.length) ? null : argv.shift();  | 
 | 56 | + | 
 | 57 | +  if (arrayify(commands).indexOf(command) === -1) {  | 
 | 58 | +    const err = new Error('Command not recognised: ' + command);  | 
 | 59 | +    err.command = command;  | 
 | 60 | +    err.name = 'INVALID_COMMAND';  | 
 | 61 | +    throw err  | 
 | 62 | +  }  | 
 | 63 | + | 
 | 64 | +  return { command, argv }  | 
 | 65 | +}  | 
 | 66 | + | 
 | 67 | +module.exports = commandLineCommands;  | 
0 commit comments