dox-foundation-demo node_modules/express/node_modules/commander/index.js

EventEmitter

declaration
EventEmitter

    Description

    Module dependencies.

    Source

    var EventEmitter = require('events').EventEmitter
      , spawn = require('child_process').spawn
      , keypress = require('keypress')
      , fs = require('fs')
      , exists = fs.existsSync
      , path = require('path')
      , tty = require('tty')
      , dirname = path.dirname
      , basename = path.basename;

    Command

    property
    exports.Command

      Description

      Expose Command.

      Source

      exports.Command = Command;

      Option

      function
      Option()
      • @param: {String}flags
      • @param: {String}description

      Description

      Initialize a new Option with the given flags and description.

      Source

      function Option(flags, description) {
        this.flags = flags;
        this.required = ~flags.indexOf('<');
        this.optional = ~flags.indexOf('[');
        this.bool = !~flags.indexOf('-no-');
        flags = flags.split(/[ ,|]+/);
        if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift();
        this.long = flags.shift();
        this.description = description || '';
      }

      Command

      function
      Command()
      • @param: {String}name

      Description

      Initialize a new Command.

      Source

      function Command(name) {
        this.commands = [];
        this.options = [];
        this._args = [];
        this._name = name;
      }

      __proto__

      property
      Command.prototype.__proto__

        Description

        Inherit from EventEmitter.prototype.

        Source

        Command.prototype.__proto__ = EventEmitter.prototype;

        command

        method
        Command.prototype.command()
        • @param: {String}name
        • @param: {String}[desc]
        • @return: {Command}the new command

        Description

        Add command name.

        The .action() callback is invoked when the
        command name is specified via ARGV,
        and the remaining arguments are applied to the
        function for access.

        When the name is "*" an un-matched command
        will be passed as the first arg, followed by
        the rest of ARGV remaining.

        Examples:

         program
           .version('0.0.1')
           .option('-C, --chdir <path>', 'change the working directory')
           .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')
           .option('-T, --no-tests', 'ignore test hook')
        
         program
           .command('setup')
           .description('run remote setup commands')
           .action(function(){
             console.log('setup');
           });
        
         program
           .command('exec <cmd>')
           .description('run the given remote command')
           .action(function(cmd){
             console.log('exec "%s"', cmd);
           });
        
         program
           .command('*')
           .description('deploy the given env')
           .action(function(env){
             console.log('deploying "%s"', env);
           });
        
         program.parse(process.argv);
        

        Source

        Command.prototype.command = function(name, desc){
          var args = name.split(/ +/);
          var cmd = new Command(args.shift());
          if (desc) cmd.description(desc);
          if (desc) this.executables = true;
          this.commands.push(cmd);
          cmd.parseExpectedArgs(args);
          cmd.parent = this;
          if (desc) return this;
          return cmd;
        };

        parseExpectedArgs

        method
        Command.prototype.parseExpectedArgs()
        • @param: {Array}args
        • @return: {Command}for chaining

        Description

        Parse expected args.

        For example ["[type]"] becomes [{ required: false, name: 'type' }].

        Source

        Command.prototype.parseExpectedArgs = function(args){
          if (!args.length) return;
          var self = this;
          args.forEach(function(arg){
            switch (arg[0]) {
              case '<':
                self._args.push({ required: true, name: arg.slice(1, -1) });
                break;
              case '[':
                self._args.push({ required: false, name: arg.slice(1, -1) });
                break;
            }
          });
          return this;
        };

        action

        method
        Command.prototype.action()
        • @param: {Function}fn
        • @return: {Command}for chaining

        Description

        Register callback fn for the command.

        Examples:

         program
           .command('help')
           .description('display verbose help')
           .action(function(){
              // output help here
           });
        

        Source

        Command.prototype.action = function(fn){
          var self = this;
          this.parent.on(this._name, function(args, unknown){    
            // Parse any so-far unknown options
            unknown = unknown || [];
            var parsed = self.parseOptions(unknown);
            
            // Output help if necessary
            outputHelpIfNecessary(self, parsed.unknown);
            
            // If there are still any unknown options, then we simply 
            // die, unless someone asked for help, in which case we give it
            // to them, and then we die.
            if (parsed.unknown.length > 0) {      
              self.unknownOption(parsed.unknown[0]);
            }
            
            // Leftover arguments need to be pushed back. Fixes issue #56
            if (parsed.args.length) args = parsed.args.concat(args);
            
            self._args.forEach(function(arg, i){
              if (arg.required && null == args[i]) {
                self.missingArgument(arg.name);
              }
            });
            
            // Always append ourselves to the end of the arguments,
            // to make sure we match the number of arguments the user
            // expects
            if (self._args.length) {
              args[self._args.length] = self;
            } else {
              args.push(self);
            }
            
            fn.apply(this, args);
          });
          return this;
        };

        option

        method
        Command.prototype.option()
        • @param: {String}flags
        • @param: {String}description
        • @param: {Function,Mixed}fnor default
        • @param: {Mixed}defaultValue
        • @return: {Command}for chaining

        Description

        Define option with flags, description and optional
        coercion fn.

        The flags string should contain both the short and long flags,
        separated by comma, a pipe or space. The following are all valid
        all will output this way when --help is used.

        "-p, --pepper"
        "-p|--pepper"
        "-p --pepper"

        Examples:

        // simple boolean defaulting to false
        program.option('-p, --pepper', 'add pepper');
        
        --pepper
        program.pepper
        // => Boolean
        
        // simple boolean defaulting to false
        program.option('-C, --no-cheese', 'remove cheese');
        
        program.cheese
        // => true
        
        --no-cheese
        program.cheese
        // => true
        
        // required argument
        program.option('-C, --chdir <path>', 'change the working directory');
        
        --chdir /tmp
        program.chdir
        // => "/tmp"
        
        // optional argument
        program.option('-c, --cheese [type]', 'add cheese [marble]');
        

        Source

        Command.prototype.option = function(flags, description, fn, defaultValue){
          var self = this
            , option = new Option(flags, description)
            , oname = option.name()
            , name = camelcase(oname);
        
          // default as 3rd arg
          if ('function' != typeof fn) defaultValue = fn, fn = null;
        
          // preassign default value only for --no-*, [optional], or <required>
          if (false == option.bool || option.optional || option.required) {
            // when --no-* we make sure default is true
            if (false == option.bool) defaultValue = true;
            // preassign only if we have a default
            if (undefined !== defaultValue) self[name] = defaultValue;
          }
        
          // register the option
          this.options.push(option);
        
          // when it's passed assign the value
          // and conditionally invoke the callback
          this.on(oname, function(val){
            // coercion
            if (null != val && fn) val = fn(val);
        
            // unassigned or bool
            if ('boolean' == typeof self[name] || 'undefined' == typeof self[name]) {
              // if no value, bool true, and we have a default, then use it!
              if (null == val) {
                self[name] = option.bool
                  ? defaultValue || true
                  : false;
              } else {
                self[name] = val;
              }
            } else if (null !== val) {
              // reassign
              self[name] = val;
            }
          });
        
          return this;
        };

        parse

        method
        Command.prototype.parse()
        • @param: {Array}argv
        • @return: {Command}for chaining

        Description

        Parse argv, settings options and invoking commands when defined.

        Source

        Command.prototype.parse = function(argv){
          // implicit help
          if (this.executables) this.addImplicitHelpCommand();
        
          // store raw args
          this.rawArgs = argv;
        
          // guess name
          this._name = this._name || basename(argv[1]);
        
          // process argv
          var parsed = this.parseOptions(this.normalize(argv.slice(2)));
          var args = this.args = parsed.args;
         
          // executable sub-commands, skip .parseArgs()
          if (this.executables) return this.executeSubCommand(argv, args, parsed.unknown);
        
          return this.parseArgs(this.args, parsed.unknown);
        };

        parseOptions

        method
        Command.prototype.parseOptions()
        • @param: {Array}argv
        • @return: {Array}

        Description

        Parse options from argv returning argv
        void of these options.

        Source

        Command.prototype.parseOptions = function(argv){
          var args = []
            , len = argv.length
            , literal
            , option
            , arg;
        
          var unknownOptions = [];
        
          // parse options
          for (var i = 0; i < len; ++i) {
            arg = argv[i];
        
            // literal args after --
            if ('--' == arg) {
              literal = true;
              continue;
            }
        
            if (literal) {
              args.push(arg);
              continue;
            }
        
            // find matching Option
            option = this.optionFor(arg);
        
            // option is defined
            if (option) {
              // requires arg
              if (option.required) {
                arg = argv[++i];
                if (null == arg) return this.optionMissingArgument(option);
                if ('-' == arg[0] && '-' != arg) return this.optionMissingArgument(option, arg);
                this.emit(option.name(), arg);
              // optional arg
              } else if (option.optional) {
                arg = argv[i+1];
                if (null == arg || ('-' == arg[0] && '-' != arg)) {
                  arg = null;
                } else {
                  ++i;
                }
                this.emit(option.name(), arg);
              // bool
              } else {
                this.emit(option.name());
              }
              continue;
            }
            
            // looks like an option
            if (arg.length > 1 && '-' == arg[0]) {
              unknownOptions.push(arg);
              
              // If the next argument looks like it might be
              // an argument for this option, we pass it on.
              // If it isn't, then it'll simply be ignored
              if (argv[i+1] && '-' != argv[i+1][0]) {
                unknownOptions.push(argv[++i]);
              }
              continue;
            }
            
            // arg
            args.push(arg);
          }
          
          return { args: args, unknown: unknownOptions };
        };

        version

        method
        Command.prototype.version()
        • @param: {String}str
        • @param: {String}flags
        • @return: {Command}for chaining

        Description

        Set the program version to str.

        This method auto-registers the "-V, --version" flag
        which will print the version number when passed.

        Source

        Command.prototype.version = function(str, flags){
          if (0 == arguments.length) return this._version;
          this._version = str;
          flags = flags || '-V, --version';
          this.option(flags, 'output the version number');
          this.on('version', function(){
            console.log(str);
            process.exit(0);
          });
          return this;
        };

        description

        method
        Command.prototype.description()
        • @param: {String}str
        • @return: {String,Command}

        Description

        Set the description str.

        Source

        Command.prototype.description = function(str){
          if (0 == arguments.length) return this._description;
          this._description = str;
          return this;
        };

        usage

        method
        Command.prototype.usage()
        • @param: {String}str
        • @return: {String,Command}

        Description

        Set / get the command usage str.

        Source

        Command.prototype.usage = function(str){
          var args = this._args.map(function(arg){
            return arg.required
              ? '<' + arg.name + '>'
              : '[' + arg.name + ']';
          });
        
          var usage = '[options'
            + (this.commands.length ? '] [command' : '')
            + ']'
            + (this._args.length ? ' ' + args : '');
        
          if (0 == arguments.length) return this._usage || usage;
          this._usage = str;
        
          return this;
        };

        prompt

        method
        Command.prototype.prompt()
        • @param: {String,Object}str
        • @param: {Function}fn

        Description

        Prompt str and callback fn(val)

        Commander supports single-line and multi-line prompts.
        To issue a single-line prompt simply add white-space
        to the end of str, something like "name: ", whereas
        for a multi-line prompt omit this "description:".

        Examples:

        program.prompt('Username: ', function(name){
          console.log('hi %s', name);
        });
        
        program.prompt('Description:', function(desc){
          console.log('description was "%s"', desc.trim());
        });
        

        Source

        Command.prototype.prompt = function(str, fn){
          var self = this;
          if ('string' == typeof str) {
            if (/ $/.test(str)) return this.promptSingleLine.apply(this, arguments);
            this.promptMultiLine(str, fn);
          } else {
            var keys = Object.keys(str)
              , obj = {};
        
            function next() {
              var key = keys.shift()
                , label = str[key];
        
              if (!key) return fn(obj);
              self.prompt(label, function(val){
                obj[key] = val;
                next();
              });
            }
        
            next();
          }
        };

        password

        method
        Command.prototype.password()
        • @param: {String}str
        • @param: {String}mask
        • @param: {Function}fn

        Description

        Prompt for password with str, mask char and callback fn(val).

        The mask string defaults to '', aka no output is
        written while typing, you may want to use "*" etc.

        Examples:

        program.password('Password: ', function(pass){
          console.log('got "%s"', pass);
          process.stdin.destroy();
        });
        
        program.password('Password: ', '*', function(pass){
          console.log('got "%s"', pass);
          process.stdin.destroy();
        });
        

        Source

        Command.prototype.password = function(str, mask, fn){
          var self = this
            , buf = '';
        
          // default mask
          if ('function' == typeof mask) {
            fn = mask;
            mask = '';
          }
        
          keypress(process.stdin);
        
          function setRawMode(mode) {
            if (process.stdin.setRawMode) {
              process.stdin.setRawMode(mode);
            } else {
              tty.setRawMode(mode);
            }
          };
          setRawMode(true);
          process.stdout.write(str);
        
          // keypress
          process.stdin.on('keypress', function(c, key){
            if (key && 'enter' == key.name) {
              console.log();
              process.stdin.pause();
              process.stdin.removeAllListeners('keypress');
              setRawMode(false);
              if (!buf.trim().length) return self.password(str, mask, fn);
              fn(buf);
              return;
            }
        
            if (key && key.ctrl && 'c' == key.name) {
              console.log('%s', buf);
              process.exit();
            }
        
            process.stdout.write(mask);
            buf += c;
          }).resume();
        };

        confirm

        method
        Command.prototype.confirm()
        • @param: {String}str
        • @param: {Function}fn

        Description

        Confirmation prompt with str and callback fn(bool)

        Examples:

         program.confirm('continue? ', function(ok){
           console.log(' got %j', ok);
           process.stdin.destroy();
         });
        

        Source

        Command.prototype.confirm = function(str, fn, verbose){
          var self = this;
          this.prompt(str, function(ok){
            if (!ok.trim()) {
              if (!verbose) str += '(yes or no) ';
              return self.confirm(str, fn, true);
            }
            fn(parseBool(ok));
          });
        };

        choose

        method
        Command.prototype.choose()
        • @param: {Array}list
        • @param: {Number,Function}indexor fn
        • @param: {Function}fn

        Description

        Choice prompt with list of items and callback fn(index, item)

        Examples:

         var list = ['tobi', 'loki', 'jane', 'manny', 'luna'];
        
         console.log('Choose the coolest pet:');
         program.choose(list, function(i){
           console.log('you chose %d "%s"', i, list[i]);
           process.stdin.destroy();
         });
        

        Source

        Command.prototype.choose = function(list, index, fn){
          var self = this
            , hasDefault = 'number' == typeof index;
        
          if (!hasDefault) {
            fn = index;
            index = null;
          }
        
          list.forEach(function(item, i){
            if (hasDefault && i == index) {
              console.log('* %d) %s', i + 1, item);
            } else {
              console.log('  %d) %s', i + 1, item);
            }
          });
        
          function again() {
            self.prompt('  : ', function(val){
              val = parseInt(val, 10) - 1;
              if (hasDefault && isNaN(val)) val = index;
        
              if (null == list[val]) {
                again();
              } else {
                fn(val, list[val]);
              }
            });
          }
        
          again();
        };

        outputHelp

        method
        Command.prototype.outputHelp()

          Description

          Output help information for this command

          Source

          Command.prototype.outputHelp = function(){
            process.stdout.write(this.helpInformation());
            this.emit('--help');
          };

          help

          method
          Command.prototype.help()

            Description

            Output help information and exit.

            Source

            Command.prototype.help = function(){
              this.outputHelp();
              process.exit();
            };