////////////////////////////////////////////////////////////////////////////////
// 'installed' subcommand.
347889
func cmdInstalled(params Parameters) *subcommands.Command {
	return &subcommands.Command{
		Advanced:  true,
		UsageLine: "installed [options]",
		ShortDesc: "lists packages installed in the site root",
		LongDesc:  "Lists packages installed in the site root.",
		CommandRun: func() subcommands.CommandRun {
			c := &installedRun{defaultServiceURL: params.ServiceURL}
			c.registerBaseFlags()
			c.siteRootOptions.registerFlags(&c.Flags)
			return c
		},
	}
}
1174009
func (c *Command) Subcommand(name string) *Command {
	for _, sub := range c.Subcommands {
		if sub.Name == name {
			return sub
		}
		for _, a := range sub.Aliases {
			if a == name {
				return sub
			}
		}
	}
	return nil
}
800195
public void addCommand(Command command) {
        if(command == null)
            throw new IllegalArgumentException();

        if(_frozen)
            throw new IllegalStateException();

        Command[] results = new Command[_commands.length + 1];
        System.arraycopy(_commands, 0, results, 0, _commands.length);
        results[_commands.length] = command;
        _commands = results;
    }
1305541
func (cmd *CLI) SubCommandsUsageString(title string) string {
	tbl := NewSharedShellTable(&sep, &columnWidth)
	cmd.subCommands.Each(func(name string, command *SubCommand) {
		row := tbl.Row()
		row.Column(" ", command.Name())
		aliases := decorateNameAliases(command.NameAliases())
		desArray := []string{command.Description(), aliases}
		description := strings.Join(desArray, "  ")
		row.Column(description)
	})
	return fmt.Sprintf("\n\n%s:\n%s", title, tbl.String())
}
1315406
func (c *CLI) Subcommand() string {
	c.once.Do(c.init)
	return c.subcommand
}
1135991
func (s *Service) InstallCommands() ([]string, error) {
	cmd := fmt.Sprintf(serviceCreateCommandTemplate[1:],
		renderer.Quote(s.Service.Name),
		renderer.Quote(s.Service.Conf.Desc),
		renderer.Quote(s.Service.Conf.ExecStart),
		renderer.Quote(s.Service.Name),
		renderer.Quote(s.Service.Conf.Desc),
		renderer.Quote(s.Service.Conf.ExecStart),
		renderer.Quote(s.Service.Name),
		renderer.Quote(s.Service.Name),
	)
	return strings.Split(cmd, "\n"), nil
}
191874
function _postCommand(args, commandsConfig, globalOptsConfig) {

  function _validate(value, name, desc) {
    return function (rule) {
      if (iz.hasOwnProperty(rule)) {
        var isValid = iz[rule](value);
        if (isValid === null || isValid === false) {
          exit(new Error(util.format('Invalid %s: <%s> must be %s', desc, name, rule)));
        }
      } else {
        exit(new Error(util.format('Invalid %s rule: %s', desc, rule)));
      }
    };
  }

  if (!args) {
    return;

  } else if (args.length === 0) {
    // 2 -> 'node' and 'somecommand'
    // which means that the command is executed without args, hence display help menu
    // NOTE: this check is needed because for some reason commander.args
    // also returns empty array when one of the args is an opt (-- prefixed)
    if (process.argv.length === 2) {
      commander.help();
    }

  } else {
    var lastArg = args[args.length - 1],
      commandName = lastArg._name,
      commandArgs = (commandsConfig[commandName]) ? commandsConfig[commandName].args : undefined,
      commandOpts = (commandsConfig[commandName]) ? commandsConfig[commandName].options : undefined;

    // non-object last arg means command is not configured in setup
    if (typeof lastArg !== 'object') {
      exit(new Error(util.format('Unknown command: %s, use --help for more info', lastArg)));

    } else if (commandArgs && commandArgs.length > 0) {
      var programName = lastArg.parent._name;

      // display usage info when expected arguments don't exist
      if (args.length === 1) {
        exit(new Error(util.format('Usage: %s %s %s', programName, commandName, commandArgs.map(function (arg) {
          return util.format((arg.optional) ? '[%s]' : '<%s>', arg.name);
        }).join(' '))));
      } else {
        // validate arguments as configured in commands setup
        for (var i = 0, ln = commandArgs.length; i < ln; i += 1) {
          if (!commandArgs[i].optional) {
            commandArgs[i].rules.forEach(_validate(args[i], commandArgs[i].name, 'argument'));
          }
        }
      }
    }

    // validate command opts as configured in commands setup
    if (commandOpts) {
      commandOpts.forEach(function (commandOpt) {
        if (commandOpt.rules) {
          var name = commandOpt.arg,
            value = lastArg[name.match(/<.*>/)[0].replace(/[<>]/g, '')];
          commandOpt.rules.forEach(_validate(value, name, 'option'));
        }
      });
    }

    // validate global opts as configured in commands setup
    if (globalOptsConfig) {
      globalOptsConfig.forEach(function (globalOptConfig) {
        if (globalOptConfig.rules) {
          var name = globalOptConfig.arg,
            value = lastArg.parent[name.match(/<.*>/)[0].replace(/[<>]/g, '')];
          globalOptConfig.rules.forEach(_validate(value, name, 'option'));
        }
      });
    }
  }
}
1238990
function parseGruntCommandLine() {
        var cmdline = _cmdline.match(/--[\S]+\b/ig);

        if (null != cmdline) {
            for (var i = 0, n = cmdline.length; i < n; i++) {
                // if cmdline does not have "=", set "true" as default value.
                if (!cmdline[i].match(/=/i)) {
                    cmdline[i] += '=true';
                }
            }
        } else {
            cmdline = [];
        }

        return cmdline;
    }
527470
function(program) {
  this.cli = program;
  this.cmd = this.cli;
  if(process.env.CLI_TOOLKIT_HELP_CMD) {
    var alias = this.cli.finder.getCommandByName;
    var cmd = alias(process.env.CLI_TOOLKIT_HELP_CMD, this.cli.commands());
    if(cmd) {
      this.cmd = cmd;
    }
  }
  this.eol = eol;
  this.format = fmt.TEXT_FORMAT;
  this.help2man = !!process.env.help2man;
  this.conf = this.cli.configure().help;
  this.vanilla = this.conf.vanilla;
  if(this.colon === undefined) {
    this.colon = typeof(this.conf.colon) === 'boolean' ? this.conf.colon : true;
  }
  this.messages = this.conf.messages;
  this.limit = this.conf.maximum ? this.conf.maximum : 80;
  this.usage = this.cli.usage();
  this.delimiter = this.conf.delimiter ? this.conf.delimiter : ', ';
  this.assignment = this.conf.assignment ? this.conf.assignment : '=';
  this.align = this.conf.align || columns.COLUMN_ALIGN;
  this.collapse = this.conf.collapse;
  if(!~columns.align.indexOf(this.align)) {
    this.align = columns.COLUMN_ALIGN;
  }
  this.sections = sections.slice(0);

  var i, k;

  // custom unknown sections in help conf
  if(this.cmd.sections()) {
    var ckeys = Object.keys(this.cmd.sections());
    // custom sections come after options
    var ind = this.sections.indexOf(manual.OPTIONS) + 1;
    for(i = 0;i < ckeys.length;i++) {
      k = ckeys[i].toLowerCase();
      if(!~this.sections.indexOf(k)) {
        // inject into section list
        this.sections.splice(ind, 0, k);
        ind++;
      }
    }
  }

  this.padding = this.conf.indent;
  this.space = this.conf.space || repeat(this.padding);
  this.wraps = true;
  this.width = this.conf.width;
  // whether to use columns
  this.use = this.format === fmt.TEXT_FORMAT;
  this.headers = {};
  for(k in headers) {
    this.headers[k] = headers[k];
  }
  this.metrics = {};
  this.getMetrics();
  this.titles();
}
689268
function _Overlay_resolveCommands(commands) {
                    // First make sure they're all DOM elements.
                    commands = _resolveElements(commands);

                    // Now make sure they're all in this container
                    var result = {};
                    result.commands = [];
                    result.others = [];
                    var allCommands = this.element.querySelectorAll(".win-command");
                    var countAll, countIn;
                    for (countAll = 0; countAll < allCommands.length; countAll++) {
                        var found = false;
                        for (countIn = 0; countIn < commands.length; countIn++) {
                            if (commands[countIn] === allCommands[countAll]) {
                                result.commands.push(allCommands[countAll]);
                                commands.splice(countIn, 1);
                                found = true;
                                break;
                            }
                        }
                        if (!found) {
                            result.others.push(allCommands[countAll]);
                        }
                    }
                    return result;
                }
528333
function PostInstall() {

    var self = this;

    //Initialize post installation scripts.
    var init = function() {
        self.isWin32 = ( os.platform() == 'win32' ) ? true : false;
        self.path = _( __dirname.substring(0, (__dirname.length - "script".length)-1 ) );
        self.root = process.cwd().toString();


        createVersionFile();
        //console.log('[ debug ] createVersionFile()');
        createGinaFileForPlatform();
        //console.log('[ debug ] createGinaFileForPlatform()');
    }

    var createVersionFile = function(callback) {
        var version = require( _(self.path + '/package.json') ).version;
        var target = _(self.path + '/VERSION');
        try {
            if ( fs.existsSync(target) ) {
                fs.unlinkSync(target);
                setTimeout(function(){
                    if (callback) {



                            fs.writeFileSync(target, version);
                            callback()

                    } else {
                        fs.writeFileSync(target, version);
                    }
                }, 1000)

            } else {
                fs.writeFileSync(target, version);
            }

        } catch(err) {
            throw err;
            process.exit(0)
        }
    }

    //Creating framework command line file for nix.
    var createGinaFile = function(win32Name, callback) {
        var name = require( _(self.path + '/package.json') ).name;
        var appPath = _( self.path.substring(0, (self.path.length - ("node_modules/" + name + '/').length)) );
        var source = _(self.path + '/core/template/command/gina.tpl');
        var target = _(appPath +'/'+ name);
        if ( typeof(win32Name) != 'undefined') {
            target = _(appPath +'/'+ win32Name)
        }

        //Will override.
        if ( typeof(callback) != 'undefined') {

            try {
                utils.generator.createFileFromTemplateSync(source, target);
                setTimeout(function () {
                    callback(false)
                }, 1000)
            } catch (err) {
                callback(err)
            }
        } else {
            utils.generator.createFileFromTemplateSync(source, target)
        }
    }

    var createGinaFileForPlatform = function() {
        console.log('creating platform file');
        //console.log('[ debug ] about to open ' + _(self.path + '/package.json'));
        var name = require( _(self.path + '/package.json') ).name;

        var filename = ( (self.isWin32) ? '.' : '' ) + name;

        var keepGoing = function(filename) {



            createGinaFile(filename, function onGinaFileCreated(err){

                if (err) {
                    throw err;
                    return false
                }
                // this is done to allow multiple calls of post_install.js
                var filename = _(self.path + '/SUCCESS');
                var installed = fs.existsSync( filename );
                if (!installed /**&& /node_modules\/gina/.test( new _(process.cwd()).toUnixStyle() ) */ ) {
                    fs.writeFileSync(filename, true )
                }

                // old NPM : < 3 & compatible 3+
                console.log('> now installing dependencies, please wait ...\n\r');
                var dependencies = require( _(self.path + '/package.json') ).ginaDependencies;

                // starting from NodeJS v5.x, it is done automatically
                npmInstall(dependencies);

            });
        }

        if (self.isWin32) {
            var appPath = _( self.path.substring(0, (self.path.length - ("node_modules/" + name + '/').length)) );
            var source = _(self.path + '/core/template/command/gina.bat.tpl');
            var target = _(appPath +'/'+ name + '.bat');
            if ( fs.existsSync(target) ) {
                fs.unlinkSync(target);
                // have to wait for windows to complete this
                setTimeout( function(){
                    utils.generator.createFileFromTemplateSync(source, target);
                    keepGoing(filename)
                }, 1000)
            } else {
                utils.generator.createFileFromTemplateSync(source, target);
                keepGoing(filename)
            }
        } else {
            filename += '.sh';// patch for latest npm release
            keepGoing(filename)
        }
    }


    var npmInstall = function(modules) {
        if ( modules.count() == 0 ) {
            console.log("\nGina's command line tool has been installed !\n");
            process.exit(0)
        }

        var cmd = ( isWin32() ) ? 'npm.cmd install' : 'npm install';
        var key = null;
        for (var m in modules) {
            key = m;
            if ( modules[m] != '') {
                cmd += ' '+ m +'@'+ modules[m];
                console.log('installing [ '+ m +'@'+ modules[m] +' ]');
            } else {
                cmd += ' '+ m + '@latest';
                console.log('installing [ '+ m + '@latest ]');
            }

            break
        }

        delete modules[key];

        if ( !fs.existsSync(self.path) ) {
            fs.mkdirSync(self.path)
        }

        if ( !fs.existsSync(self.path +'/node_modules') ) {
            fs.mkdirSync(self.path +'/node_modules')
        }

        if ( !fs.existsSync(self.path +'/tmp') ) {
            fs.mkdirSync(self.path +'/tmp')
        }

        //console.debug('cwd: ' + _(self.path));
        //console.debug('tmp: ' +  _(self.root +'/tmp'));

        run(cmd, { cwd: _(self.path), tmp: _(self.root +'/tmp')  })
            .onData(function(data){
                //console.info(data)
            })
            .onComplete( function done(err, data){
                if (err && err != 'false') {
                    console.error(err);
                    //console.debug('\nCommand was: \n'+ cmd)
                } //else {
                    //console.info(data);
                    //end()
                //}

                npmInstall(modules)
            })
    }

    var end = function() {
        // Update middleware file
        var filename = _(self.path) + '/MIDDLEWARE';
        var msg = "Gina's command line tool has been installed.\n\r";

        var deps = require(_(self.path) + '/package.json').dependecies;


        for (var d in deps) {
            if (d === 'express' && deps[d] != '') {
                var middleware = d +'@'+ deps[d]
            }
        }

        var expressPackage = _(self.path + '/node_modules/express/package.json');
        if ( typeof(middleware) == 'undefined' && fs.existsSync(expressPackage) ) {
            var middleware = require(expressPackage).version;
            middleware = 'express@' + middleware;
        } else if (typeof(middleware) == 'undefined') {
            throw new Error('No middleware found !!');
            process.exit(0)
        }

        if ( fs.existsSync(filename) ) { // update
            var def = fs.readFileSync(filename).toString;
            // TODO - uninstall old if installed ??
            if (def !== middleware) {

                try {

                    fs.writeFileSync(filename, middleware);
                    console.log(msg)
                } catch (err) {
                    throw new Error(err.stack||err.message||err);
                    process.exit(0)
                }

                // fs.writeFile(filename, middleware, function onWrote(err){
                //     if (err) {
                //         throw new Error(err.stack||err.message||err);
                //         process.exit(1)
                //     } else {
                //         console.log(msg)
                //     }
                // })
            } // else, nothing to do
        } else { // create

            try {

                fs.writeFileSync(filename, middleware);
                console.log(msg)
            } catch (err) {
                throw new Error(err.stack||err.message||err);
                process.exit(0)
            }

            // fs.writeFile(filename, middleware, function onWrote(err){
            //     if (err) {
            //         throw new Error(err.stack||err.message||err);
            //         process.exit(1)
            //     } else {
            //         console.log(msg)
            //     }
            // })
        }
    }

    //var createGinaHome = function() { };


    init()
}
1363099
function findPluginPath(command) {
  if (command && /^\w+$/.test(command)) {
    try {
      return resolve.sync('nowa-' + command, {
        paths: moduleDirs
      });
    } catch (e) {
      console.log('');
      console.log('  ' + chalk.green.bold(command) + ' command is not installed.');
      console.log('  You can try to install it by ' + chalk.blue.bold('nowa install ' + command) + '.');
      console.log('');
    }
  }
}
182065
def parse_subcommands(parser, subcommands, argv):
    

    subparsers = parser.add_subparsers(dest='subparser_name')

    # add help sub-command
    parser_help = subparsers.add_parser(
        'help', help='Detailed help for actions using `help <action>`')
    parser_help.add_argument('action', nargs=1)

    # add all other subcommands
    modules = [
        name for _, name, _ in pkgutil.iter_modules(subcommands.__path__)]
    commands = [m for m in modules if m in argv]

    actions = {}

    # `commands` will contain the module corresponding to a single
    # subcommand if provided; otherwise, generate top-level help
    # message from all submodules in `modules`.
    for name in commands or modules:
        # set up subcommand help text. The first line of the dosctring
        # in the module is displayed as the help text in the
        # script-level help message (`script -h`). The entire
        # docstring is displayed in the help message for the
        # individual subcommand ((`script action -h`))
        # if no individual subcommand is specified (run_action[False]),
        # a full list of docstrings is displayed
        try:
            imp = '{}.{}'.format(subcommands.__name__, name)
            mod = importlib.import_module(imp)
        except Exception as e:
            log.error(e)
            continue

        subparser = subparsers.add_parser(
            name,
            help=mod.__doc__.lstrip().split('\n', 1)[0],
            description=mod.__doc__,
            formatter_class=argparse.RawDescriptionHelpFormatter)

        mod.build_parser(subparser)

        # see global subcommands/__init__.py
        subcommands.build_parser(subparser)

        actions[name] = mod.action

    return parser, actions
269760
def install(cmd, packages):
    
    check_cmd(cmd)

    all_pkgs_str = " ".join(all_pkgs)
    print("INSTALLING: " + cmd + " install " + all_pkgs_str)
    subprocess.check_call([cmd, 'install'] + packages)
1358400
function executeCommand(parts, callback) {
    var name,
        shouldLoad = true,
        command,
        usage;

    if (typeof parts === 'undefined' || typeof parts === 'function') {
      throw(new Error('parts is a required argument of type Array'));
    }

    name = parts.shift();

    if (app.cli.source || app.commands[name]) {
      if (app.commands[name]) {
        shouldLoad = false;
        if (typeof app.commands[name] != 'function' && !app.commands[name][parts[0]]) {
          shouldLoad = true;
        }
      }

      if (shouldLoad && !loadCommand(name, parts[0])) {
        return callback();
      }

      command = app.commands[name];
      while (command) {
        usage = command.usage;

        if (!app.argv.h && !app.argv.help && typeof command === 'function') {
          while (parts.length + 1 < command.length) {
            parts.push(null);
          }

          if (command.destructive) {
            return ensureDestroy(function (err) {
              return err ? callback() : command.apply(app, parts.concat(callback));
            })
          }

          command.apply(app, parts.concat(callback));
          return;
        }

        command = command[parts.shift()];
      }

      //
      // Since we have not resolved a needle, try and print out a usage message
      //
      if (usage || app.cli.usage) {
        showUsage(usage || app.cli.usage);
        callback(false);
      }
    }
    else if (app.usage) {
      //
      // If there's no directory we're supposed to search for modules, simply
      // print out usage notice if it's provided.
      //
      showUsage(app.cli.usage);
      callback(true);
    }
  }
248942
def register_textx_subcommands():
    
    # Register direct sub-commands
    global textx
    for subcommand in pkg_resources.iter_entry_points(group='textx_commands'):
        textx.command()(subcommand.load())

    # Register sub-command groups
    for subgroup in pkg_resources.iter_entry_points(
            group='textx_command_groups'):
        subgroup.load()(textx)
519291
function parseCommandLine() {
	var commands = process.argv.slice(2);
	var args = {};

	for (var i = 0; i < commands.length; i++) {
		var match = commands[i].match(/^--(.+)=(.+)$/);
		if (match)
			args[match[1]] = match[2];
		else if (i < commands.length - 1 && commands[i].substr(0, 1) === "-") {
			args[commands[i].substr(1)] = commands[i + 1];
			i++;
		}
		else if (i === 0) args[commandKey] = commands[i];
		else if (i === 1) args[commandHost] = commands[i];
	}

	return args;
}