all files / cli/params/ index.js

86.21% Statements 25/29
71.43% Branches 10/14
60% Functions 3/5
86.21% Lines 25/29
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              1× 1×                                                       2×                 1× 1×   1×   1× 1× 3×   3× 6× 3× 3× 3×       3× 3× 1×     1×       3×                 1× 2× 2×   2×       1×       1×  
'use strict';
 
/**
 * Class for CLI params orchestration
 */
class Params {
  constructor(sqz) {
    this.sqz    = sqz;
    this.params = this.parse(process.argv.slice(2));
  }
 
  /**
   * Set CLI params object
   * @name this.sqz.cli.params.set
   */
  set(params) {
    this.params = params;
  }
 
  /**
   * Set an option value
   * @name this.sqz.cli.params.setOption
   */
  setOption(name, value) {
    if (!this.params.options[name]) {
      this.params.options[name] = value;
    }
  }
 
 
  /**
   * Return CLI params
   * @returns {Object}
   * @name this.sqz.cli.params.get
   */
  get() {
    return this.params;
  }
 
  /**
   * Return CLI params
   * @returns {Object}
   * @name this.sqz.cli.params.get
   */
  parse(args) {
    let commands = args.shift();
    commands     = commands ? commands.split(':') : [];
 
    const raw = args.join(' ');
 
    let curArgType = 'args';
    args           = args.reduce((argsRet, val) => {
      let newArg = false;
 
      ['flags', 'options'].forEach((argType) => {
        if (val[0] === '-') {
          val        = val.substr(1);
          curArgType = argType;
          newArg     = true;
        }
      });
 
      newArg && argsRet[curArgType].push([val]); // eslint-disable-line no-unused-expressions
      if (!newArg) {
        Iif (curArgType === 'args') {
          argsRet[curArgType].push(val);
        } else {
          argsRet[curArgType][argsRet[curArgType].length - 1].push(val);
        }
      }
 
      return argsRet;
    }, {
      names   : commands,
      args    : [],
      flags   : [],
      options : [],
      buffer  : new Buffer(raw)
    });
 
    ['flags', 'options'].forEach((argType) => {
      args[argType] = args[argType].reduce((obj, arr) => {
        obj[arr[0]] = arr.slice(1)[0] || null;
 
        return obj;
      }, {});
    });
 
    return args;
  }
}
 
module.exports = Params;