index.js 14.7 KB
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
var assert = require('assert')
var Completion = require('./lib/completion')
var Parser = require('./lib/parser')
var path = require('path')
var Usage = require('./lib/usage')
var Validation = require('./lib/validation')
var Y18n = require('y18n')

Argv(process.argv.slice(2))

var exports = module.exports = Argv
function Argv (processArgs, cwd) {
  processArgs = processArgs || [] // handle calling yargs().

  var self = {}
  var completion = null
  var usage = null
  var validation = null
  var y18n = Y18n({
    directory: path.resolve(__dirname, './locales'),
    updateFiles: false
  })

  if (!cwd) cwd = process.cwd()

  self.$0 = process.argv
    .slice(0, 2)
    .map(function (x, i) {
      // ignore the node bin, specify this in your
      // bin file with #!/usr/bin/env node
      if (i === 0 && /\b(node|iojs)$/.test(x)) return
      var b = rebase(cwd, x)
      return x.match(/^\//) && b.length < x.length ? b : x
    })
    .join(' ').trim()

  if (process.env._ !== undefined && process.argv[1] === process.env._) {
    self.$0 = process.env._.replace(
      path.dirname(process.execPath) + '/', ''
    )
  }

  var options
  self.resetOptions = self.reset = function () {
    // put yargs back into its initial
    // state, this is useful for creating a
    // nested CLI.
    options = {
      array: [],
      boolean: [],
      string: [],
      narg: {},
      key: {},
      alias: {},
      default: {},
      defaultDescription: {},
      choices: {},
      requiresArg: [],
      count: [],
      normalize: [],
      config: []
    }

    usage = Usage(self, y18n) // handle usage output.
    validation = Validation(self, usage, y18n) // handle arg validation.
    completion = Completion(self, usage)

    demanded = {}

    exitProcess = true
    strict = false
    helpOpt = null
    versionOpt = null
    commandHandlers = {}
    self.parsed = false

    return self
  }
  self.resetOptions()

  self.boolean = function (bools) {
    options.boolean.push.apply(options.boolean, [].concat(bools))
    return self
  }

  self.array = function (arrays) {
    options.array.push.apply(options.array, [].concat(arrays))
    return self
  }

  self.nargs = function (key, n) {
    if (typeof key === 'object') {
      Object.keys(key).forEach(function (k) {
        self.nargs(k, key[k])
      })
    } else {
      options.narg[key] = n
    }
    return self
  }

  self.choices = function (key, values) {
    if (typeof key === 'object') {
      Object.keys(key).forEach(function (k) {
        self.choices(k, key[k])
      })
    } else {
      options.choices[key] = (options.choices[key] || []).concat(values)
    }
    return self
  }

  self.normalize = function (strings) {
    options.normalize.push.apply(options.normalize, [].concat(strings))
    return self
  }

  self.config = function (key, msg) {
    self.describe(key, msg || usage.deferY18nLookup('Path to JSON config file'))
    options.config.push.apply(options.config, [].concat(key))
    return self
  }

  self.example = function (cmd, description) {
    usage.example(cmd, description)
    return self
  }

  self.command = function (cmd, description, fn) {
    if (description !== false) {
      usage.command(cmd, description)
    }
    if (fn) commandHandlers[cmd] = fn
    return self
  }

  var commandHandlers = {}
  self.getCommandHandlers = function () {
    return commandHandlers
  }

  self.string = function (strings) {
    options.string.push.apply(options.string, [].concat(strings))
    return self
  }

  self.default = function (key, value, defaultDescription) {
    if (typeof key === 'object') {
      Object.keys(key).forEach(function (k) {
        self.default(k, key[k])
      })
    } else {
      if (defaultDescription) options.defaultDescription[key] = defaultDescription
      if (typeof value === 'function') {
        if (!options.defaultDescription[key]) options.defaultDescription[key] = usage.functionDescription(value)
        value = value.call()
      }
      options.default[key] = value
    }
    return self
  }

  self.alias = function (x, y) {
    if (typeof x === 'object') {
      Object.keys(x).forEach(function (key) {
        self.alias(key, x[key])
      })
    } else {
      options.alias[x] = (options.alias[x] || []).concat(y)
    }
    return self
  }

  self.count = function (counts) {
    options.count.push.apply(options.count, [].concat(counts))
    return self
  }

  var demanded = {}
  self.demand = self.required = self.require = function (keys, max, msg) {
    // you can optionally provide a 'max' key,
    // which will raise an exception if too many '_'
    // options are provided.
    if (typeof max !== 'number') {
      msg = max
      max = Infinity
    }

    if (typeof keys === 'number') {
      if (!demanded._) demanded._ = { count: 0, msg: null, max: max }
      demanded._.count = keys
      demanded._.msg = msg
    } else if (Array.isArray(keys)) {
      keys.forEach(function (key) {
        self.demand(key, msg)
      })
    } else {
      if (typeof msg === 'string') {
        demanded[keys] = { msg: msg }
      } else if (msg === true || typeof msg === 'undefined') {
        demanded[keys] = { msg: undefined }
      }
    }

    return self
  }
  self.getDemanded = function () {
    return demanded
  }

  self.requiresArg = function (requiresArgs) {
    options.requiresArg.push.apply(options.requiresArg, [].concat(requiresArgs))
    return self
  }

  self.implies = function (key, value) {
    validation.implies(key, value)
    return self
  }

  self.usage = function (msg, opts) {
    if (!opts && typeof msg === 'object') {
      opts = msg
      msg = null
    }

    usage.usage(msg)

    if (opts) self.options(opts)

    return self
  }

  self.epilogue = self.epilog = function (msg) {
    usage.epilog(msg)
    return self
  }

  self.fail = function (f) {
    usage.failFn(f)
    return self
  }

  self.check = function (f) {
    validation.check(f)
    return self
  }

  self.defaults = self.default

  self.describe = function (key, desc) {
    options.key[key] = true
    usage.describe(key, desc)
    return self
  }

  self.parse = function (args) {
    return parseArgs(args)
  }

  self.option = self.options = function (key, opt) {
    if (typeof key === 'object') {
      Object.keys(key).forEach(function (k) {
        self.options(k, key[k])
      })
    } else {
      assert(typeof opt === 'object', 'second argument to option must be an object')

      options.key[key] = true // track manually set keys.

      if (opt.alias) self.alias(key, opt.alias)

      var demand = opt.demand || opt.required || opt.require

      if (demand) {
        self.demand(key, demand)
      } if ('config' in opt) {
        self.config(key)
      } if ('default' in opt) {
        self.default(key, opt.default)
      } if ('nargs' in opt) {
        self.nargs(key, opt.nargs)
      } if ('choices' in opt) {
        self.choices(key, opt.choices)
      } if (opt.boolean || opt.type === 'boolean') {
        self.boolean(key)
        if (opt.alias) self.boolean(opt.alias)
      } if (opt.array || opt.type === 'array') {
        self.array(key)
        if (opt.alias) self.array(opt.alias)
      } if (opt.string || opt.type === 'string') {
        self.string(key)
        if (opt.alias) self.string(opt.alias)
      } if (opt.count || opt.type === 'count') {
        self.count(key)
      } if (opt.defaultDescription) {
        options.defaultDescription[key] = opt.defaultDescription
      }

      var desc = opt.describe || opt.description || opt.desc
      if (desc) {
        self.describe(key, desc)
      }

      if (opt.requiresArg) {
        self.requiresArg(key)
      }
    }

    return self
  }
  self.getOptions = function () {
    return options
  }

  self.wrap = function (cols) {
    usage.wrap(cols)
    return self
  }

  var strict = false
  self.strict = function () {
    strict = true
    return self
  }
  self.getStrict = function () {
    return strict
  }

  self.showHelp = function (level) {
    if (!self.parsed) parseArgs(processArgs) // run parser, if it has not already been executed.
    usage.showHelp(level)
    return self
  }

  var versionOpt = null
  self.version = function (ver, opt, msg) {
    versionOpt = opt || 'version'
    usage.version(ver)
    self.boolean(versionOpt)
    self.describe(versionOpt, msg || usage.deferY18nLookup('Show version number'))
    return self
  }

  var helpOpt = null
  self.addHelpOpt = function (opt, msg) {
    helpOpt = opt
    self.boolean(opt)
    self.describe(opt, msg || usage.deferY18nLookup('Show help'))
    return self
  }

  self.showHelpOnFail = function (enabled, message) {
    usage.showHelpOnFail(enabled, message)
    return self
  }

  var exitProcess = true
  self.exitProcess = function (enabled) {
    if (typeof enabled !== 'boolean') {
      enabled = true
    }
    exitProcess = enabled
    return self
  }
  self.getExitProcess = function () {
    return exitProcess
  }

  self.help = function () {
    if (arguments.length > 0) return self.addHelpOpt.apply(self, arguments)

    if (!self.parsed) parseArgs(processArgs) // run parser, if it has not already been executed.

    return usage.help()
  }

  var completionCommand = null
  self.completion = function (cmd, desc, fn) {
    // a function to execute when generating
    // completions can be provided as the second
    // or third argument to completion.
    if (typeof desc === 'function') {
      fn = desc
      desc = null
    }

    // register the completion command.
    completionCommand = cmd || 'completion'
    if (!desc && desc !== false) {
      desc = 'generate bash completion script'
    }
    self.command(completionCommand, desc)

    // a function can be provided
    if (fn) completion.registerFunction(fn)

    return self
  }

  self.showCompletionScript = function ($0) {
    $0 = $0 || self.$0
    console.log(completion.generateCompletionScript($0))
    return self
  }

  self.locale = function (locale) {
    if (arguments.length === 0) {
      guessLocale()
      return y18n.getLocale()
    }
    detectLocale = false
    y18n.setLocale(locale)
    return self
  }

  self.updateStrings = self.updateLocale = function (obj) {
    detectLocale = false
    y18n.updateLocale(obj)
    return self
  }

  var detectLocale = true
  self.detectLocale = function (detect) {
    detectLocale = detect
    return self
  }
  self.getDetectLocale = function () {
    return detectLocale
  }

  self.getUsageInstance = function () {
    return usage
  }

  self.getValidationInstance = function () {
    return validation
  }

  self.terminalWidth = function () {
    return require('window-size').width
  }

  Object.defineProperty(self, 'argv', {
    get: function () {
      var args = null

      try {
        args = parseArgs(processArgs)
      } catch (err) {
        usage.fail(err.message)
      }

      return args
    },
    enumerable: true
  })

  function parseArgs (args) {
    var parsed = Parser(args, options, y18n)
    var argv = parsed.argv
    var aliases = parsed.aliases

    argv.$0 = self.$0

    self.parsed = parsed

    guessLocale() // guess locale lazily, so that it can be turned off in chain.

    // while building up the argv object, there
    // are two passes through the parser. If completion
    // is being performed short-circuit on the first pass.
    if (completionCommand &&
      (process.argv.join(' ')).indexOf(completion.completionKey) !== -1 &&
      !argv[completion.completionKey]) {
      return argv
    }

    // if there's a handler associated with a
    // command defer processing to it.
    var handlerKeys = Object.keys(self.getCommandHandlers())
    for (var i = 0, command; (command = handlerKeys[i]) !== undefined; i++) {
      if (~argv._.indexOf(command)) {
        self.getCommandHandlers()[command](self.reset())
        return self.argv
      }
    }

    // generate a completion script for adding to ~/.bashrc.
    if (completionCommand && ~argv._.indexOf(completionCommand) && !argv[completion.completionKey]) {
      self.showCompletionScript()
      if (exitProcess) {
        process.exit(0)
      }
    }

    // we must run completions first, a user might
    // want to complete the --help or --version option.
    if (completion.completionKey in argv) {
      // we allow for asynchronous completions,
      // e.g., loading in a list of commands from an API.
      completion.getCompletion(function (completions) {
        ;(completions || []).forEach(function (completion) {
          console.log(completion)
        })

        if (exitProcess) {
          process.exit(0)
        }
      })
      return
    }

    var helpOrVersion = false
    Object.keys(argv).forEach(function (key) {
      if (key === helpOpt && argv[key]) {
        helpOrVersion = true
        self.showHelp('log')
        if (exitProcess) {
          process.exit(0)
        }
      } else if (key === versionOpt && argv[key]) {
        helpOrVersion = true
        usage.showVersion()
        if (exitProcess) {
          process.exit(0)
        }
      }
    })

    // If the help or version options where used and exitProcess is false,
    // we won't run validations
    if (!helpOrVersion) {
      if (parsed.error) throw parsed.error

      // if we're executed via bash completion, don't
      // bother with validation.
      if (!argv[completion.completionKey]) {
        validation.nonOptionCount(argv)
        validation.missingArgumentValue(argv)
        validation.requiredArguments(argv)
        if (strict) validation.unknownArguments(argv, aliases)
        validation.customChecks(argv, aliases)
        validation.limitedChoices(argv)
        validation.implications(argv)
      }
    }

    setPlaceholderKeys(argv)

    return argv
  }

  function guessLocale () {
    if (!detectLocale) return

    try {
      var osLocale = require('os-locale')
      self.locale(osLocale.sync({ spawn: false }))
    } catch (err) {
      // if we explode looking up locale just noop
      // we'll keep using the default language 'en'.
    }
  }

  function setPlaceholderKeys (argv) {
    Object.keys(options.key).forEach(function (key) {
      if (typeof argv[key] === 'undefined') argv[key] = undefined
    })
  }

  sigletonify(self)
  return self
}

// rebase an absolute path to a relative one with respect to a base directory
// exported for tests
exports.rebase = rebase
function rebase (base, dir) {
  return path.relative(base, dir)
}

/*  Hack an instance of Argv with process.argv into Argv
    so people can do
    require('yargs')(['--beeble=1','-z','zizzle']).argv
    to parse a list of args and
    require('yargs').argv
    to get a parsed version of process.argv.
*/
function sigletonify (inst) {
  Object.keys(inst).forEach(function (key) {
    if (key === 'argv') {
      Argv.__defineGetter__(key, inst.__lookupGetter__(key))
    } else {
      Argv[key] = typeof inst[key] === 'function' ? inst[key].bind(inst) : inst[key]
    }
  })
}