Convenience function for initialising a Command CLI

    For parameter definitions see :class:`.Command`
760840
def cli(main, conf_dir=None, commands_dir=None):
    
    return Command(main, conf_dir=conf_dir, commands_dir=commands_dir)()
752453
def def_cmd(name=None, short=None, fn=None, usage=None, help=None):
    
    command = Command(name=name, short=short, fn=fn, usage=usage, help=help)
    Command.register(command)
78895
def init_command(self, action, flags=None):
    '''
    '''

    if not isinstance(action, list):
        action = [action]      
    cmd = ['singularity'] + action

    if self.quiet is True:
        cmd.insert(1, '--quiet')
    if self.debug is True:
        cmd.insert(1, '--debug')

    return cmd
605735
function Command(name, parent) {
  if (!(this instanceof Command)) {
    return new Command();
  }
  this.commands = [];
  this.options = [];
  this._args = [];
  this._aliases = [];
  this._name = name;
  this._relay = false;
  this._hidden = false;
  this._parent = parent;
  this._mode = false;
  this._catch = false;
  this._help = undefined;
  this._init = undefined;
  this._after = undefined;
  this._allowUnknownOptions = false;
}
236310
def init_argparser(self, argparser):
        

        super(PackageManagerRuntime, self).init_argparser(argparser)

        # Ideally, we could use more subparsers for each action (i.e.
        # init and install).  However, this is complicated by the fact
        # that setuptools has its own calling conventions through the
        # setup.py file, and to present a consistent cli to end-users
        # from both calmjs entry point and setuptools using effectively
        # the same codebase will require a bit of creative handling.

        # provide this for the setuptools command class.
        actions = argparser.add_argument_group('action arguments')
        count = 0

        for full, short, desc in self.pkg_manager_options:
            args = [
                dash + key
                for dash, key in zip(('-', '--'), (short, full))
                if key
            ]
            # default is singular, but for the argparsed version in our
            # runtime permits multiple packages.
            desc = desc.replace('Python package', 'Python package(s)')
            if not short:
                f = getattr(self.cli_driver, '%s_%s' % (
                    self.cli_driver.binary, full), None)
                if callable(f):
                    count += 1
                    actions.add_argument(
                        *args, help=desc, action=PackageManagerAction,
                        dest=self.action_key, const=(count, f)
                    )
                    if self.default_action is None:
                        self.default_action = f
                    continue  # pragma: no cover
            argparser.add_argument(*args, help=desc, action='store_true')

        argparser.add_argument(
            'package_names', metavar=metavar('package'), nargs='+',
            help="python packages to be used for the generation of '%s'" % (
                self.cli_driver.pkgdef_filename,
            ),
        )
624607
def cmd_func(self, command: str) -> Optional[Callable]:
        
        func_name = self.cmd_func_name(command)
        if func_name:
            return getattr(self, func_name)
58323
def _execute(self, func, command, **new_attributes):
        
        if self._cfg_factory:
            # if we have a cfg_factory
            try:
                # we try to load a config with the factory
                if self.cfg_file:
                    self.cfg = self._cfg_factory(self.cfg_file)
            except Exception as error:
                # raise se exception
                self._cfg_error(error)
        # let's get command(function) argspec
        arg_specs = inspect.getargspec(command)
        if arg_specs.defaults:
            # if we have defaults
            # count defaults arguments
            count = len(arg_specs.defaults)
            # get arguments names
            args_names = arg_specs.args[:count]
            # get keyword arguments names
            kwargs_name = arg_specs.args[count:]
        else:
            # else all names are the args only
            args_names = arg_specs.args
            # and keyword arguments is empty
            kwargs_name = []
        pargs = []
        kwargs = {}
        # for every argument in argument names
        for name in args_names:
            if name == 'args':
                # if argument name is *special name* **args**
                # we append a reference to self.args
                pargs.append(self.args)
            elif name == 'self':
                # else if argment name is *special name* **self**
                if ArgParseInated in inspect.getmro(func.__cls__):
                    # if the class that holds the function is subclass of
                    # ArgParseInated we'll instantiate it, passing some
                    # parameter
                    pargs.append(func.__cls__(self, **new_attributes))
                else:
                    # else we'll instatiate the class without parameters
                    pargs.append(func.__cls__())
            else:
                # else we'll append the argument getting it from the self.args
                pargs.append(getattr(self.args, name))
        # for every argument in keyword arguments
        for name in kwargs_name:
            if name == 'args':
                # if argument name is *special name* **args**
                # we set for the arg a reference to self.args
                kwargs[name] = self.args
            elif name in self.args:
                # else if name is in self.args we'll set the relative value.
                kwargs[name] = getattr(self.args, name)
        # set the **global** write function
        setattr(__builtin__, self._write_name, self.write)
        # set the **global** write line function
        setattr(__builtin__, self._write_line_name, self.writeln)
        # let's setup something.
        for setup_func in self.setup:
            setup_func(self)
        # call event before_execute
        self._self_event('before_execute', command, *pargs, **kwargs)
        # if events returns a non None value we use it as retrval.
        retval, pargs, kwargs = self._call_event(
            'before_execute', command, pargs, kwargs)
        # if before_execute event returns None go on with command
        if retval is None:
            # let's execute the command and assign the returned value to retval
            retval = command(*pargs, **kwargs)
            # call event after_execute
            self._call_event('after_execute', command, pargs, kwargs)
            self._self_event('after_execute', command, *pargs, **kwargs)
        if self.auto_exit:
            # if we have auto_exit is True
            if retval is None:
                self._self_event(
                    'before_exit_ok', command, retval=EXIT_OK, *pargs, **kwargs)
                # if retval is None we'll assume it's EXIT_OK
                self.exit(EXIT_OK)
            elif isinstance(retval, basestring):
                self._self_event('before_exit_ok', command, retval=retval, *pargs, **kwargs)
                # else if retval is a string we will exit with the message and
                # ERRORCODE is equal to 0
                self.exit(EXIT_OK, retval)
            elif isinstance(retval, int):
                if retval == EXIT_OK:
                    self._self_event('before_exit_ok', command, retval=retval, *pargs, **kwargs)
                else:
                    self._self_event('before_exit_error', command, retval=retval, *pargs, **kwargs)
                # else if retval is an integer we'll exits with it as ERRORCODE
                self.exit(retval)
            elif isinstance(retval, (tuple, list,)):
                self._self_event('before_exit_error', command, retval=retval, *pargs, **kwargs)
                # if retval is a tuple or a list we'll exist with ERRORCODE and
                # message
                self.exit(retval[0], retval[1])
            self._self_event('before_exit', command, retval=retval, *pargs, **kwargs)
            self.exit()
        else:
            # else if auto_exit is not True
            # we'll simply return  retval
            return retval
212888
function init() {
  // Retrieve any arguments passed in via the command line
  args = cliConfig.getArguments();

  // Supply usage info if help argument was passed
  if (args.help) {
    console.log(cliConfig.getUsage());
    process.exit(0);
  }

  getClientAuth(function(data) {
    parseClientAuth(data, function(err, data) {
      if (err) {
        console.error(err.message);
        process.exit(0);
      }
      writeEdgerc(data, function(err) {
        if (err) {
          if (err.errno == -13) {
            console.error("Unable to access " + err.path + ". Please make sure you " +
              "have permission to access this file or perhaps try running the " +
              "command as sudo.");
            process.exit(0);
          }
        }
        console.log("The section '" + args.section + "' has been succesfully added to " + args.path + "\n");
      });
    });
  });
}
994491
def _make_command_method(cls, command_name):
        
        def func(self, *args, **kwargs):
            return self._call_command(command_name, *args, **kwargs)
        return func
468654
def exec_cmd(self, command, **kwargs):
        

        if command == 'load':
            if kwargs:
                kwargs = dict(options=[kwargs])
        return self._exec_cmd(command, **kwargs)
325500
def parse_cmdline_args(args, classes):
    
    if args is None:
        raise ValueError("args must not be None")
    parsed_args = {}
    for kls in classes:
        prefix = kls.configuration_key_prefix()
        name = kls.configuration_key
        if getattr(args, "%s_%s" % (prefix, name), False):
            logging.debug(
                "Gathering initargs for '%s.%s'", prefix, name)
            initargs = {}
            for arg_name in kls.init_argnames():
                val = getattr(args, "%s_%s_%s" %
                              (prefix, name, arg_name))
                if val is not None:
                    initargs[arg_name] = val
            if prefix not in parsed_args:
                parsed_args[prefix] = []
            parsed_args[prefix].append((name, initargs))
    return parsed_args
847207
def cmd_func_name(self, command: str) -> str:
        
        target = COMMAND_FUNC_PREFIX + command
        return target if callable(getattr(self, target, None)) else ''
1312125
private void init(final String commandName, final String... arguments) {
        if (arguments != null) {
            if (arguments.length == 1) {
                init(commandName, arguments[0]);
                return;
            }

            String[] ary = new String[arguments.length];

            for (int i = 0; i < arguments.length; i++) {
                if (arguments[i].indexOf('!') == -1) {
                    ary[i] = arguments[i];
                } else {
                    ary[i] = "'" + arguments[i] + "'";
                }
            }
            // sCommandBytes = StringUtils.join(ary, '!');
            init(commandName, StringUtils.join(ary, '!'));
        } else {
            init(commandName, (String) null);
        }
    }
631981
def cmdline(self, **kwargs):
        

        args = [self.executable]
        indexed_args = []

        for key, value in kwargs.iteritems():
            parameter = self[key]
            if value != parameter.default:
                no_value = parameter.type == 'boolean'

                if parameter.longflag:  # use longflag where possible
                    args.append("--%s" % parameter.longflag)
                    if no_value:
                        args.append(str(value))
                elif parameter.flag:
                    args.append("-%s" % parameter.flag)
                    if no_value:
                        args.append(str(value))
                elif parameter.index:
                    indexed_args.insert(int(parameter.index), str(value))

        return args + indexed_args
129176
def init(argv):
    
    # Setting initial configuration values
    config.set_default({
        # driver section
        "driver": {},
        # fs section
        "fs": {},
        # MongoDB section
        "mongodb": {},
    })

    # Parse the command line
    init_parsecmdline(argv[1:])

    # Initiatize the output directory
    fs.init(dry_run=_opt["dry_run"], **config.get_entry('fs'))

    # This baby will handle UNIX signals
    signal.signal(signal.SIGINT,  _handle_signal)
    signal.signal(signal.SIGTERM, _handle_signal)
198361
def cli(ctx, pattern, arguments, safe):
    """"""

    matches = utils.grep_commands(pattern)
    if matches:
        selected = utils.select_command(matches)
        if selected >= 0:
            cmd, desc = matches[selected]
            pcmd = utils.create_pcmd(cmd)
            raw_params, params, defaults = utils.get_params_in_pcmd(pcmd)

            arguments = list(arguments)
            kargs = {}
            for r, p, d in zip(raw_params, params, defaults):
                if arguments:
                    val = arguments.pop(0)
                    click.echo("{}: {}".format(p, val))
                    kargs[r] = val
                elif safe:
                    if d:
                        kargs[r] = d
                else:
                    p_default = d if d else None
                    val = click.prompt("Enter value for '{}'".format(p), default=p_default)
                    kargs[r] = val
            click.echo("\n")

            final_cmd = utils.substitute_pcmd(pcmd, kargs, safe)

            command = "$ {} :: {}".format(final_cmd, desc)
            if click.confirm("Execute\n\t{}\n\n?".format(command), default=True):
                os.system(final_cmd)
    elif matches == []:
        click.echo('No saved commands matches the pattern {}'.format(pattern))
    else:
        click.echo("No commands to run, Add one by 'keep new'. ")
770804
def simple_cmd():
    
    parser = argparse.ArgumentParser(
        prog="Simple command-line function toolkit.",
        description="""Input function name and args and kwargs.
        python xxx.py main -a 1 2 3 -k a=1,b=2,c=3""",
    )
    parser.add_argument("-f", "--func_name", default="main")
    parser.add_argument("-a", "--args", dest="args", nargs="*")
    parser.add_argument("-k", "--kwargs", dest="kwargs")
    parser.add_argument(
        "-i",
        "-s",
        "--info",
        "--show",
        "--status",
        dest="show",
        action="store_true",
        help="show the args, kwargs and function's source code.",
    )
    params = parser.parse_args()
    func_name = params.func_name
    func = globals().get(func_name)
    if not (callable(func)):
        Config.utils_logger.warning("invalid func_name: %s" % func_name)
        return
    args = params.args or []
    kwargs = params.kwargs or {}
    if kwargs:
        items = [re.split("[:=]", i) for i in re.split("[,;]+", kwargs)]
        kwargs = dict(items)
    if params.show:
        from inspect import getsource

        Config.utils_logger.info("args: %s; kwargs: %s" % (args, kwargs))
        Config.utils_logger.info(getsource(func))
        return
    func(*args, **kwargs)