All files / libs/tty cli.js

100% Statements 371/371
100% Branches 258/258
100% Functions 41/41
100% Lines 335/335
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 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779                1x 1x 1x 1x 1x 1x 1x 1x   1x                                                                                                                                     237x           119x 119x           119x           119x           119x           119x           119x           119x   119x           119x 119x           119x 119x   119x 119x 119x 119x                                                               1x 12x 9x                                                                               1x 90x 85x 85x   90x 89x 84x     1x 28x       210x     406x 406x 406x   406x 14x 8x 8x 6x 5x 5x 1x     4x 4x         1x   1x 1x   1x 1x 2x     1x 1x 1x         1x     12x 12x   392x 357x 356x 356x 356x 9x 9x 9x   3x 3x       1x   35x 34x 34x 34x   34x 33x   1x     1x     389x 389x 389x 389x   389x 389x 142x 139x   3x   142x   389x     401x 632x 629x             109x 109x 109x 108x   109x 108x 108x   109x       109x   109x 109x   109x 157x   157x 11x 146x 6x 6x 140x 1x   139x 139x 139x 20x 20x     139x 11x 1x   10x 10x   128x 88x 86x 40x   11x 3x   2x 1x 1x     8x 8x 7x 16x 6x 6x   10x             29x       151x     103x 103x 4x         99x   29x 29x 27x 27x   6x 6x   6x 6x   3x 3x   6x 4x 3x 6x   4x 3x 2x 4x   2x                                                     1x 109x 3x 3x     109x   109x 109x     10x 9x 9x           99x   97x         97x   97x 194x 545x 140x   545x 545x 158x         97x 97x   97x   97x   97x 18x 79x 3x   76x 76x 6x 6x 6x 70x 64x 64x     97x     1x 215x 215x 215x 146x 9x 4x   5x   146x   215x               1x 50x               1x 115x               1x 21x                 1x 2x 2x 2x           1x 20x 20x 107x 25x 20x 20x 20x 20x 3x 3x 2x 2x 2x 2x 2x   20x 2x 2x 2x     20x 20x 2x   20x 4x 3x   20x 3x 4x 3x     20x   20x 40x 20x 20x 21x 1x 1x 1x   21x 42x 42x     80x 42x 42x 42x 42x       20x 20x 20x 20x         20x 20x   20x   20x 20x       11x 11x 9x   2x         9x 1x   8x         115x 115x   108x 108x   108x 1x       107x       67x 67x   14x 13x 6x 13x   4x 4x     106x 106x       57x 57x 57x   57x 18x 39x 38x 38x 38x   3x 3x     17x 16x 15x 17x   6x 6x     12x 11x 10x   12x 1x       11x     1x         10x 8x 10x       14x     1x  
/**
 * @module      libs/sys/cli
 * @createdAt   2016-07-15
 *
 * @copyright   Copyright (c) 2016 Zhonglei Qiu
 * @license     Licensed under the MIT license.
 */
 
var format = require('../sys/clog').format
var table = require('./table')
var assign = require('../lang/assign')
var isPlainObject = require('../lang/isPlainObject')
var reOptionType = /^(bool|str|num|arr|count|bstr|bnum)[a-z]*$/
var reOption = /^\s*<(bool|str|num|arr|count|bstr|bnum)[a-z]*>\s*([\s\S]*?)(?:\{\{(.*)\}\})?$/
var undef = void 0
var DEFAULT_GROUP_NAME = '__default__:)'
 
var typeConfig = {
  bool: {
    label: 'boolean',
    needArgs: 0,
    needArgsWhenUseEqual: 1
  },
  str: {
    label: 'string',
    needArgs: 1
  },
  bstr: {
    label: 'boolean/string',
    needArgs: 1,
    boolean: true
  },
  num: {
    label: 'number',
    needArgs: 1
  },
  bnum: {
    label: 'boolean/number',
    needArgs: 1,
    boolean: true
  },
  arr: {
    label: 'array',
    needArgs: 1
  },
  count: {
    label: 'count',
    needArgs: 0
  }
}
 
/**
 * @class
 * @param {Object} conf  cli 程序的配置项
 * @param {String|Boolean} conf.help                              String: 帮助描述              Boolean: 是否启用系统默认的帮助选项
 * @param {String|Boolean|(() => String} conf.version             String: 版本号(默认为 0.0.0) Boolean: 是否启用系统默认的版本选项
 * @param {String|(() => String} conf.usage                       简短的描述
 * @param {String|Array<String>|(() => String} conf.desc          命令的一些介绍
 * @param {String|Array<String>|(() => String} conf.example       使用命令的一些样例
 * @param {String|(() => String} conf.epilog                      放在 help 结尾的一段话,一般用来声明版权,或者显示查看更多的链接
 *
 * @param {Boolean} conf.strict                     遇到无法解析的 option 是否要报错
 * @param {Boolean} conf.showHelpOnError            解析参数失败时不显示帮助信息
 * @param {Boolean} conf.stopParseOnFirstNoOption   在遇到第一个非 option 参数时就停止解析(很适用于运行子程序)
 *
 * @example
 * cli({
 *   usage: 'cli [options] <foo>'
 *   version: '1.0.0'
 * })
 * .options({
 *   'e | escape': '<bool> escape input string {{ defaultValue }}'
 * })
 * .parse(function (res) {
 *   if (res.escape) {
 *     // ...
 *   }
 * })
 *
 * @author Zhonglei Qiu
 * @since  2.0.0
 * @see    optimist, minimist, yargs, nomnom, nopt, commander
 */
function Cli(conf) {
  if (!(this instanceof Cli)) return new Cli(conf)
 
  /**
   * 配置信息
   * @type {Object}
   */
  this.conf = conf || {}
  conf = this.conf
 
  /**
   * 在遇到第一个非 option 参数时就停止解析(很适用于子程序)
   * @type {Boolean}
   */
  this.stopParseOnFirstNoOption = !!conf.stopParseOnFirstNoOption
 
  /**
   * 出错时显示帮助信息
   * @type {Boolean}
   */
  this.showHelpOnError = !!conf.showHelpOnError
 
  /**
   * 严格模式,遇到无法解析的 option 是就报错
   * @type {Boolean}
   */
  this.strict = !!conf.strict
 
  /**
   * 解析完后剩下的给程序的参数
   * @type {Array}
   */
  this._ = []
 
  /**
   * 所有 commands 的配置
   * @type {Object}
   */
  this.mapCommands = {}
 
  /**
   * 所有 options 的配置
   * @type {Object}
   */
  this.mapOptions = {}
 
  this.mapEnv = {}
 
  /**
   * 所有的选项分组名称
   * @type {Array}
   */
  this.groups = []
  this.groupsMap = {}
 
  /**
   * 所有的环境变量分组名称
   * @type {Array}
   */
  this.envGroups = []
  this.envGroupsMap = {}
 
  if (conf.usage) this.usage = conf.usage
  if (conf.desc) this.desc = [].concat(conf.desc)
  if (conf.example) this.example = [].concat(conf.example)
  if (conf.epilog) this.epilog = conf.epilog
}
 
/**
 * 设置 Cli 程序的子命令
 *
 * @param  {Object} opts 子命令配置
 *
 *   opts 是 key-value 对象,支持下面几种类型的配置
 *   - str1:str2... => function
 *   - str1:str2... => {desc: '', cmd: function}
 *
 * @return {Cli}
 *
 * @example
 *
 * cli.commands({
 *   'build:*': function (res) {
 *      // 匹配所有 build: 开头的子命令
 *    },
 *   'r | run': function (res) {
 *     // handle
 *   },
 *   second: {
 *     desc: 'this is sub-command with description',
 *     cmd: function (res) {
 *       // handle
 *     }
 *   }
 * })
 *
 */
Cli.prototype.commands = function(opts) {
  init.call(this, true, opts)
  return this
}
 
/**
 * 设置 Cli 程序支持的选项
 *
 * @param  {String} [group]     选项可以分组,此值可以指定分组的名称,在选项非常多的情况下,
 *                              使用 --help 时可以看到效果
 *
 * @param  {Object} opts        此分组下的所有选项
 *
 * opts 是 key-value 对象,支持下面几种类型的配置
 *   - str1:str2... => <type> desc
 *   - str1:str2... => {type: '', desc: '', defaultValue: ''}
 *
 * 说明:
 *   1. str1 是一个 option,":" 后面的 str2 等等表示 str1 的别名
 *   2. desc 表示 option 的描述
 *   3. type 表示 option 的类型,支持的类型有
 *     * boolean   bool
 *     * string    str   不能为空
 *     * number    num   不能为空
 *     * array     arr   可以为空
 *     * count
 *     * boolean/number   bnum
 *     * boolean/number   bstr
 *
 * @return {Cli}
 *
 * @example
 *
 * cli.options({
 *   'e | escape': '<boolean> enable escape',
 *   'l | linefeed': {
 *     type: 'boolean',
 *     desc: 'append a system linefeed at end'
 *   }
 * })
 *
 */
Cli.prototype.options = function(group, opts, isEnv) {
  if (typeof group !== 'string') {
    opts = group
    group = null
  }
  if (!opts) return
  init.call(this, false, opts, group, isEnv)
  return this
}
 
Cli.prototype.env = function(group, opts) {
  return this.options(group, opts, true)
}
 
function init(isCommand, opts, group, isEnv) {
  Object.keys(opts).forEach(function(origKey) {
    var key, type, value, cmd, desc, alias, defaultValue, target, map
 
    alias = origKey.trim().split(/\s*\|\s*/)
    key = alias[0]
    value = opts[origKey]
 
    if (isCommand) {
      if (typeof value === 'function') {
        cmd = value
        desc = ''
      } else if (isPlainObject(value)) {
        cmd = value.cmd
        if (typeof cmd !== 'function') {
          throw new Error('Command "' + origKey + '" should have a handle function.')
        }
 
        desc = value.desc || ''
        if (value.conf || value.options || value.groups) {
          /* istanbul ignore next */
          var conf = value.conf || {}
 
          /* istanbul ignore else */
          if (!conf.desc) conf.desc = desc
 
          var subCli = new Cli(conf)
          subCli.options(value.options)
          /* istanbul ignore else */
          if (value.groups) {
            Object.keys(value.groups).forEach(function(k) {
              subCli.options(k, value.groups[k])
            })
          }
          cmd = function(res, cli) {
            subCli.parse(res._, function(subres) {
              value.cmd.call(subCli, subres, subCli)
            })
          }
        }
      } else {
        throw new Error('Command "' + origKey + '" is invalid')
      }
 
      target = { key: key, alias: alias, cmd: cmd, type: 'command', desc: desc }
      map = this.mapCommands
    } else {
      if (typeof value === 'string') {
        if (reOption.test(value)) {
          type = RegExp.$1
          desc = RegExp.$2
          if (RegExp.$3) {
            defaultValue = RegExp.$3
            try {
              defaultValue = JSON.parse(defaultValue.trim())
            } catch (e) {
              desc += '{{' + defaultValue + '}}'
              defaultValue = undefined
            }
          }
        } else {
          throw new Error('Option "' + origKey + '" config "' + value + '" is invalid.')
        }
      } else if (isPlainObject(value)) {
        type = value.type
        desc = value.desc || ''
        defaultValue = value.defaultValue
 
        if (reOptionType.test(type)) {
          type = RegExp.$1
        } else {
          throw new Error('Option "' + origKey + '" type is invalid.')
        }
      } else {
        throw new Error('Option "' + origKey + '" is invalid.')
      }
 
      group = group || DEFAULT_GROUP_NAME
      var groups = isEnv ? this.envGroups : this.groups
      var groupsMap = isEnv ? this.envGroupsMap : this.groupsMap
      map = isEnv ? this.mapEnv : this.mapOptions
 
      target = { key: key, alias: alias, defaultValue: defaultValue, type: type, group: group, desc: desc }
      if (groups.indexOf(group) < 0) {
        if (group === DEFAULT_GROUP_NAME) {
          groups.unshift(group)
        } else {
          groups.push(group)
        }
        groupsMap[group] = []
      }
      groupsMap[group].push(target)
    }
 
    alias.forEach(function(k) {
      if (k in map) throw new Error((isCommand ? 'Command' : isEnv ? 'Env' : 'Option') + ' key "' + k + '" is duplicated.')
      map[k] = target
    })
  }, this)
}
 
// 确保将 -h, -v 放在 default group 的最后面
function parseInit() {
  var conf = this.conf
  var opts = {}
  if (conf.help !== false) {
    opts['help | h'] = '<bool> ' + (typeof conf.help === 'string' ? conf.help : 'show help')
  }
  if (conf.version !== false) {
    this.version = conf.version
    opts['version | v'] = '<bool> ' + 'show version'
  }
  init.call(this, false, opts)
}
 
function parse(args) {
  var _ = this._
  var i, arg, rawArg, stopped
  var ck = consumeKey.bind(this)
  var cv = consumeVal.bind(this)
 
  for (i = 0; i < args.length; i++) {
    rawArg = arg = args[i]
 
    if (stopped) {
      _.push(arg)
    } else if (_.length === 0 && this.getCommanderByKey(arg)) { // 运行子命令剩下的参数给子命令去解析
      stopped = true
      _.push(arg)
    } else if (arg === '--') {
      stopped = true
    } else {
      var equalValue = null
      var equalIndex = arg.indexOf('=')
      if (equalIndex >= 0) {
        equalValue = arg.substr(equalIndex + 1)
        arg = arg.substr(0, equalIndex)
      }
 
      if (arg.slice(0, 2) === '--') { // 长参数
        if (arg.length === 3) { // --a 类的参数不是 option,需要当作 value
          cv(rawArg)
        } else {
          ck(arg.slice(2), undefined, equalValue)
          if (equalValue != null) cv(equalValue, true)
        }
      } else if (arg[0] === '-' && arg.length === 2) { // 单个短参数
        ck(arg[1], undefined, equalValue)
        if (equalValue != null) cv(equalValue, true)
      } else if (arg[0] === '-' && arg.length >= 3) { // 多个短参数,或单个数字短参数
        // 这里的参数被打散处理了,所以 consume 前要先 check 整体参数是否 valid
        if (/^-\w(\d+)$/.test(arg)) {
          if (checkOpt.call(this, arg[1], rawArg)) {
            // 已经赋值,不应该再赋值
            if (equalValue != null) throw new Error('Error: can not parse arg "' + rawArg + '"')
            ck(arg[1])
            cv(arg.slice(2))
          }
        } else {
          arg = arg.slice(1).split('')
          if (checkOpt.call(this, arg, rawArg)) {
            arg.forEach(function(k, i, ref) {
              if (ref.length - 1 === i) {
                ck(k)    // 最后一个 option 可以接任意个参数
                if (equalValue != null) cv(equalValue, true)
              } else {
                ck(k, 'noNeedArgs') // 后面不能接参数
              }
            })
          }
        }
      } else {
        // 处理非 option
        cv(rawArg)
      }
    }
 
    if (_.length && this.stopParseOnFirstNoOption) stopped = true
  }
 
  var ct = this.consumeTarget
  if (ct && !ct.boolean && ct.needArgs > ct.currentArgs && ct.needArgs !== Infinity) {
    throw new Error('Error: ' + ct.type + ' option ' + this.formatOptionKey(ct.consumedKey) + ' need argument.')
  }
}
 
function parseEnv(mapEnv) {
  Object.keys(mapEnv).forEach(function(key) {
    // { key: key, alias: alias, defaultValue: defaultValue, type: type, group: group, desc: desc }
    var target = mapEnv[key]
    if (process.env.hasOwnProperty(key)) {
      var value = process.env[target.key]
      switch (target.type) {
        case 'str':
          target.value = value
          break
        case 'bool':
          target.value = !(!value || value === 'false' || value === 'no' || value === '0')
          break
        case 'num':
          target.value = parseFloat(value)
          break
        case 'bnum':
          if (value === 'false') target.value = false
          else if (value === 'true') target.value = true
          else target.value = parseFloat(value)
          break
        case 'bstr':
          if (value === 'false') target.value = false
          else if (value === 'true') target.value = true
          else target.value = value
          break
        default:
          throw new Error('Not supported env type "' + target.type + '"')
      }
    }
  })
}
 
/**
 * 解析传入的参数
 *
 * - 解析到 "--" 就停止解析
 * - array 类型的参数支持重复设置,其它类型的参数会被覆盖,array 形式的 option 如果不加参数会返回空数组
 * - 支持短标签加数字的快捷方式,如 "-n100",前提是 "-n" 需要是 number 类型
 * - 其它:https://github.com/yargs/yargs#parsing-tricks
 *
 * @param  {Array<String>} [args]  参数
 * @param {Function}      handle  parse 完成后,如果没有被内部 handle,则会调用此 handle
 * @return {Cli}
 *
 * @example
 *
 * cli.parse(process.argv.slice(2), function (res) {
 *   if (res.foo) {
 *     // do something
 *   }
 * })
 *
 */
Cli.prototype.parse = function(args, handle) {
  if (!Array.isArray(args)) {
    handle = args
    args = process.argv.slice(2)
  }
 
  parseInit.call(this)
 
  try {
    parse.call(this, args)
  } catch (e) {
    /* istanbul ignore else */
    if (/^Error: /.test(e.message)) {
      this.error(e.message)
      return this
    } else {
      throw e
    }
  }
 
  parseEnv(this.mapEnv)
 
  var res = this.res = {
    userDefinedOptions: {}, // 记录所有的使用了用户定义的字段
    userDefinedEnv: {},
    env: {}
  }
  res.userDefined = res.userDefinedOptions // 兼容老版本
 
  var run = function(opts, defined, assignTarget) {
    Object.keys(opts).forEach(function(k) {
      if ('value' in opts[k]) {
        defined[k] = true
      }
      var value = 'value' in opts[k] ? opts[k].value : opts[k].defaultValue
      if (value !== undefined) {
        assignTarget[k] = value
      }
    })
  }
 
  run(this.mapOptions, res.userDefinedOptions, res)
  run(this.mapEnv, res.userDefinedEnv, res.env)
 
  res.rawArgs = args
 
  var _ = this._
 
  if (res.help) {
    this.help()
  } else if (res.version) {
    console.log(this.version ? strOrFunToString(this.version) : '0.0.0')
  } else {
    var commander = this.getCommanderByKey(_[0])
    if (commander) {
      res.$command = _[0]
      res._ = _.slice(1)
      commander.cmd.call(this, res, this)
    } else if (typeof handle === 'function') {
      res._ = _
      handle.call(this, res, this)
    }
  }
  return this
}
 
Cli.prototype.getCommanderByKey = function(key) {
  var commanderMap = this.mapCommands
  var commander = key && commanderMap[key]
  if (key && !commander) {
    var newKey = Object.keys(commanderMap).find(function(k) {
      if (k.includes('*')) {
        return new RegExp('^' + k.replace(/\*/g, '.*') + '$').test(key)
      }
      return false
    })
    commander = newKey && commanderMap[newKey]
  }
  return commander
}
 
/**
 * 格式化 option 选项
 * @param  {String} key 选项名
 * @return {String}     带 "-" 或 "--" 的选项名
 */
Cli.prototype.formatOptionKey = function(key) {
  return key.length === 1 ? '-' + key : '--' + key
}
 
/**
 * 得到某个 option 的配置
 * @param  {String} key 选项名
 * @return {Object}     解析过后的配置
 */
Cli.prototype.getOptionConfig = function(key) {
  return this.mapOptions[key]
}
 
/**
 * 判断某个 option 是否存在
 * @param  {String}  key 选项名
 * @return {Boolean}
 */
Cli.prototype.isOptionKeyValid = function(key) {
  return key in this.mapOptions
}
 
/**
 * 输出错误信息
 *
 * @param {...*} arg 参数格式和 {@link module:libs/sys/clog.format} 的格式是一致的
 * @return {Cli}
 */
Cli.prototype.error = function() {
  console.log(format('\n%c%s\n', 'red', format.apply(null, arguments)))
  if (this.showHelpOnError) this.help()
  return this
}
 
/**
 * 根据 Cli 的配置,输出帮助信息
 */
Cli.prototype.help = function(returnStr) {
  var buffer = []
  var EOL = require('os').EOL
  var puts = function() { buffer.push(format.apply(null, arguments)) }
  var putsHeader = function(header) { puts('%c%s:\n', 'white.bold', header) }
  var putsCommands = function(header, obj) {
    var cache = []
    var rows = []
    Object.keys(obj).forEach(function(key) {
      var entry = obj[key]
      if (cache.indexOf(entry) >= 0) return
      cache.push(entry)
      var row = []
      row.push(format('  %c%s    ', 'green', entry.alias.join(', ')))
      row.push(format('%c%s', 'default', entry.desc))
      rows.push(row)
    })
    if (!rows.length) return
    putsHeader(header)
    puts(table(rows))
    puts()
  }
 
  puts()
  if (this.usage) {
    puts('%cUsage:  %c%s\n', 'white.bold', 'green', strOrFunToString(this.usage))
  }
  if (this.desc) {
    this.desc.forEach(function(row) { puts('  %c%s', 'gray', strOrFunToString(row)) })
    puts()
  }
  if (this.example) {
    putsHeader('Example')
    this.example.forEach(function(row) { puts('  %c%s', 'red.bg.white', strOrFunToString(row)) })
    puts()
  }
 
  putsCommands('Commands', this.mapCommands)
 
  var putsGroups = function(title, groups, groupsMap, isEnv) {
    if (groups.length) {
      var rows = []
      groups.forEach(function(group) {
        if (group !== DEFAULT_GROUP_NAME) {
          rows.push(['', '', ''])
          rows.push([format('  %c%s:', 'green.bold', group), '', ''])
          rows.push(['', '', ''])
        }
        groupsMap[group].forEach(function(entry) {
          var row = []
          var defaultValue = entry.defaultValue !== undef
            ? format('  %c[ default: %s ]', 'gray', JSON.stringify(entry.defaultValue))
            : ''
          var alias = isEnv ? entry.alias : entry.alias.map(function(a) { return (a.length === 1 ? '-' : '--') + a })
          row.push(format('  %c%s', 'green', alias.join(', ')))
          row.push(format('  %c%s  ', 'cyan', '<' + typeConfig[entry.type].label + '>'))
          row.push(format('%c%s', 'default', entry.desc + defaultValue))
          rows.push(row)
        })
      }, this)
      /* istanbul ignore else */
      if (rows.length) {
        putsHeader(title)
        puts(table(rows))
        puts()
      }
    }
  }
 
  putsGroups('Options', this.groups, this.groupsMap)
  putsGroups('Env', this.envGroups, this.envGroupsMap, true)
 
  if (this.epilog) puts('  %s\n', strOrFunToString(this.epilog))
 
  buffer = buffer.join(EOL)
  return returnStr ? buffer : /* istanbul ignore next */ console.log(buffer)
}
 
function checkOpt(opts, rawArg) {
  var optsArr = [].concat(opts)
  if (optsArr.every(this.isOptionKeyValid.bind(this))) {
    return true
  } else {
    invalidOpt.call(this, rawArg)
  }
}
 
function invalidOpt(rawArg) {
  if (this.strict) {
    throw new Error('Error: invalid option ' + rawArg + '.')
  } else {
    consumeVal.call(this, rawArg)
  }
}
 
function consumeKey(key, noNeedArgs, equalValue) {
  var conf = this.getOptionConfig(key)
  if (!conf) return invalidOpt.call(this, this.formatOptionKey(key))
 
  assign(conf, typeConfig[conf.type])
  conf.currentArgs = 0
 
  if (noNeedArgs && conf.needArgs > 0) {
    throw new Error('Error: ' + conf.type + ' option '
      + this.formatOptionKey(key) + ' need argument.')
  }
 
  switch (conf.type) {
    case 'bool':
    case 'bstr':
    case 'bnum':
      conf.value = true
      break
    case 'count':
      if (equalValue != null) throw new Error('Error: "' + key + '" option do not need argument.')
      if ('value' in conf) conf.value++
      else conf.value = 1
      break
    case 'arr':
      if (!conf.value) conf.value = []
      break
  }
 
  this.consumeTarget = conf
  conf.consumedKey = key
}
 
function consumeVal(val, isEqualValue) {
  var conf = this.consumeTarget
  var needArgs = conf ? conf.needArgs : 0
  if (isEqualValue && conf && conf.needArgsWhenUseEqual) needArgs = conf.needArgsWhenUseEqual
 
  if (!conf || needArgs === conf.currentArgs) {
    this._.push(val)
  } else if (needArgs > conf.currentArgs) {
    var consumedKey = this.formatOptionKey(conf.consumedKey)
    conf.currentArgs++
    switch (conf.type) {
      case 'arr':
        conf.value.push(val)
        break
      case 'str':
      case 'bstr':
        if (conf.type === 'bstr' && val === 'true') conf.value = true
        else if (conf.type === 'bstr' && val === 'false') conf.value = false
        else conf.value = val
        break
      case 'bool':
        conf.value = val === 'yes' || val === 'true'
        break
      case 'num':
      case 'bnum':
        if (conf.type === 'bnum' && val === 'true') conf.value = true
        else if (conf.type === 'bnum' && val === 'false') conf.value = false
        else conf.value = parseNumber(val)
 
        if (isNaN(conf.value)) {
          throw new Error('Error: invalid number value "'
            + val + '" for option "'
            + consumedKey + '".')
        }
        break
    }
  } else {
    throw new SyntaxError('Parse error.')
  }
}
 
function parseNumber(val, ctx) {
  if (/\./.test(val)) val = parseFloat(val)
  else val = parseInt(val, 10)
  return val
}
 
function strOrFunToString(val) {
  return typeof val === 'function' ? val() : val
}
 
module.exports = Cli