Code coverage report for command-router/index.js

Statements: 98.41% (62 / 63)      Branches: 91.18% (31 / 34)      Functions: 100% (6 / 6)      Lines: 100% (55 / 55)      Ignored: none     

All files » command-router/ » index.js
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 951 1 1 1 1 1   1   1 23   12   12 12 12 12   12     1   1 12 12   12   12     1 13   13   13 8 8     13     13     13     1 13 13 13 13   13 2 1 1     11   11   11     1 3 3   3   3 3   3   3   3 3 1   2       3    
var extend = require('xtend')
var inherits = require('util').inherits
var EE = require('events').EventEmitter
var Router = require('routes')
var nopt = require('nopt')
var path = require('path')
 
module.exports = CommandRouter
 
function CommandRouter(options) {
  if (!(this instanceof CommandRouter)) return new CommandRouter(options)
 
  var cli = this
 
  cli.router = new Router()
  cli.knownOptions = {}
  cli.shortHands = {}
  cli.defaults = {}
 
  EE.call(cli)
}
 
inherits(CommandRouter, EE)
 
CommandRouter.prototype.command = function(route, callback) {
  var cli = this
  var route = route || '/'
 
  cli.router.addRoute(route, callback)
 
  return cli
}
 
CommandRouter.prototype.parse = function(argv) {
  var cli = this
 
  cli.options = nopt(cli.knownOptions, cli.shortHands, argv, 2)
 
  Object.keys(cli.defaults).forEach(function(name){
    Iif (cli.options[name] === false) return
    if (! cli.options[name]) cli.options[name] = cli.defaults[name]
  });
 
  console.log('cli.options.argv', cli.options.argv)
 
 
  cli.path = cli.options.argv.remain.join(' ')
 
 
  cli.dispatch(cli.path)
}
 
CommandRouter.prototype.dispatch = function(path) {
  var cli = this
  var path = path || '/'
  var action = (path === '/') ? '' : path
  var route = cli.router.match(path)
 
  if (! route) {
    if (cli.listeners('notfound').length === 0) {
      throw new Error('No CLI action defined for: "' + action + '"')
    } else return cli.emit('notfound', action)
  }
 
  cli.params = route.params
 
  if (route.splats.length) cli.params.splats = route.splats
 
  route.fn.call(cli, cli.params, cli.options)
}
 
CommandRouter.prototype.option = function(name, opts) {
  var cli = this
  var opts = typeof(name) === 'object' ? name : opts || {}
 
  if (!opts.name) opts.name = name
 
  if (! opts.type) opts.type = Boolean
  if (! opts.default) opts.default = false
 
  cli.knownOptions[opts.name] = opts.type
 
  if (opts.alias) cli.shortHands[opts.alias] = '--' + opts.name
 
  Eif (typeof opts.default !== undefined) {
    if (opts.type === path) {
      cli.defaults[opts.name] = path.resolve(opts.default)
    } else {
      cli.defaults[opts.name] = opts.default
    }
  }
 
  return cli
}