Create command subparsers.

    Parameters
    ----------
    parent : `argparse.ArgumentParser`
        Command parser.
167650
def create_arg_parser(parent):
    

    arg1 = parent.add_subparsers(dest='command')

    arg2 = arg1.add_parser('create')
    arg2.add_argument('-P', '--progress',
                      action='store_true',
                      help='show progress bar')
    arg2.add_argument('-s', '--settings',
                      type=FileType('r'), default=None,
                      help='settings json file')
    arg2.add_argument('-o', '--output',
                      default=None,
                      help='output file (default: stdout)')
    arg2.add_argument('input', nargs='*',
                      help='input file (default: stdin)')

    arg2 = arg1.add_parser('update')
    arg2.add_argument('-P', '--progress',
                      action='store_true',
                      help='show progress bar')
    arg2.add_argument('-s', '--settings',
                      type=FileType('r'), default=None,
                      help='settings json file')
    arg2.add_argument('-o', '--output',
                      default=None,
                      help='output file (default: rewrite state file)')
    arg2.add_argument('state',
                      help='state file')
    arg2.add_argument('input', nargs='*',
                      help='input file (default: stdin)')

    arg2 = arg1.add_parser('settings')
    arg2.add_argument('state',
                      help='state file')

    arg2 = arg1.add_parser('generate')
    arg2.add_argument('-P', '--progress',
                      action='store_true',
                      help='show progress bar')
    arg2.add_argument('-nf', '--no-format',
                      dest='format',
                      action='store_false',
                      help='do not format text')
    arg2.add_argument('-s', '--settings',
                      type=FileType('r'), default=None,
                      help='settings json file')
    arg2.add_argument('-ss', '--state-size',
                      type=int, default=None,
                      help='generator state size')
    arg2.add_argument('-S', '--start',
                      default=None,
                      help='text start')
    arg2.add_argument('-E', '--end',
                      default=None,
                      help='text end')
    arg2.add_argument('-R', '--reply',
                      default=None,
                      help='reply to text')
    arg2.add_argument('-w', '--words',
                      type=int, default=256,
                      help='max text size (default: %(default)s)')
    arg2.add_argument('-c', '--count',
                      type=int, default=1,
                      help='number of generated texts (default: %(default)s)')
    arg2.add_argument('-o', '--output',
                      type=FileType('w'), default=None,
                      help='output file (default: stdout)')
    arg2.add_argument('state',
                      help='state file')

    arg2.set_defaults(format=True)
213181
def _apply2parser(arguments, options, parser):
    
    for args, kwargs in options:
        parser.option(*args, **kwargs)
    for args, kwargs in arguments:
        parser.argument(*args, **kwargs)
    return parser
305045
def add_peer_parser(subparsers, parent_parser):
    
    parser = subparsers.add_parser(
        'peer',
        help='Displays information about validator peers',
        description="Provides a subcommand to list a validator's peers")

    grand_parsers = parser.add_subparsers(title='subcommands',
                                          dest='subcommand')
    grand_parsers.required = True
    add_peer_list_parser(grand_parsers, parent_parser)
139584
def add_batch_parser(subparsers, parent_parser):
    
    parser = subparsers.add_parser(
        'batch',
        help='Displays information about batches and submit new batches',
        description='Provides subcommands to display Batch information and '
        'submit Batches to the validator via the REST API.')

    grand_parsers = parser.add_subparsers(title='subcommands',
                                          dest='subcommand')
    grand_parsers.required = True
    add_batch_list_parser(grand_parsers, parent_parser)
    add_batch_show_parser(grand_parsers, parent_parser)
    add_batch_status_parser(grand_parsers, parent_parser)
    add_batch_submit_parser(grand_parsers, parent_parser)
1241392
def init(parser = None):
    

    global p,subparsers
    if parser is None:
        p = argparse.ArgumentParser()
    else:
        p = parser

    arg = p.add_argument

    subparsers = p.add_subparsers()
931010
def init_argparser(self, argparser):
        

        def prepare_argparser():
            if argparser in self.argparser_details:
                return False
            result = self.argparser_details[argparser] = ArgumentParserDetails(
                {}, {}, {})
            return result

        def to_module_attr(ep):
            return '%s:%s' % (ep.module_name, '.'.join(ep.attrs))

        def register(name, runtime, entry_point):
            subparser = commands.add_parser(
                name, help=inst.description,
            )
            # Have to specify this separately because otherwise the
            # subparser will not have a proper description when it is
            # invoked as the root.
            subparser.description = inst.description

            # Assign values for version reporting system
            setattr(subparser, ATTR_ROOT_PKG, getattr(
                argparser, ATTR_ROOT_PKG, self.package_name))
            subp_info = []
            subp_info.extend(getattr(argparser, ATTR_INFO, []))
            subp_info.append((subparser.prog, entry_point.dist))
            setattr(subparser, ATTR_INFO, subp_info)

            try:
                try:
                    runtime.init_argparser(subparser)
                except RuntimeError as e:
                    # first attempt to filter out recursion errors; also if
                    # the stack frame isn't available the complaint about
                    # bad validation doesn't apply anyway.
                    frame = currentframe()
                    if (not frame or 'maximum recursion depth' not in str(
                            e.args)):
                        raise

                    if (not isinstance(runtime, Runtime) or (type(
                            runtime).entry_point_load_validated.__code__ is
                            Runtime.entry_point_load_validated.__code__)):
                        # welp, guess some other thing blew up then, or
                        # that the problem is definitely not caused by
                        # this runtime implementation.
                        # TODO figure out how to log this nicer via the
                        # self.log_debug_error without exploding the
                        # console like Megumin would have done.
                        raise

                    # assume the overridden method didn't do everything
                    # correctly then; would be great if there is a way
                    # to ensure that our thing would have been called.
                    cls = type(runtime)
                    logger.critical(
                        "Runtime subclass at entry_point '%s' has override "
                        "'entry_point_load_validated' without filtering out "
                        "its parent classes; this can be addressed by calling "
                        "super(%s.%s, self).entry_point_load_validated("
                        "entry_point) in its implementation, or simply don't "
                        "override that method to avoid infinite recursion.",
                        entry_point, cls.__module__, cls.__name__,
                    )
                    exc = RuntimeError(
                        "%r has an invalid 'entry_point_load_validated' "
                        "implementation: insufficient protection against "
                        "infinite recursion into self not provided" % runtime
                    )
                    # for Python 3 to not blow it up.
                    exc.__suppress_context__ = True
                    raise exc
            except Exception as e:
                self.log_debug_error(
                    "cannot register entry_point '%s' from '%s' as a "
                    "subcommand to '%s': %s: %s",
                    entry_point, entry_point.dist, argparser.prog,
                    e.__class__.__name__, e
                )
                # this is where naughty things happen: will be poking at
                # the parser internals to undo the damage that was done
                # first, pop the choices_actions as a help was provided
                commands._choices_actions.pop()
                # then pop the name that was mapped.
                commands._name_parser_map.pop(name)
            else:
                # finally record the completely initialized subparser
                # into the structure here if successful.
                subparsers[name] = subparser
                runtimes[name] = runtime
                entry_points[name] = entry_point

        details = prepare_argparser()
        if not details:
            logger.debug(
                'argparser %r has already been initialized against runner %r',
                argparser, self,
            )
            return
        subparsers, runtimes, entry_points = details

        super(Runtime, self).init_argparser(argparser)

        commands = argparser.add_subparsers(
            dest=self.action_key, metavar='<command>')
        # Python 3.7 has required set to True, which is correct in most
        # cases but this disables the manual handling for cases where a
        # command was not provided; also this generates a useless error
        # message that simply states "<command> is required" and forces
        # the program to exit.  As the goal of this suite of classes is
        # to act as a helpful CLI front end, force required to be False
        # to keep our manual handling and management of subcommands.
        # Setting this as a property for compatibility with Python<3.7,
        # as only in Python>=3.7 the add_subparsers can accept required
        # as an argument.
        commands.required = False

        for entry_point in self.iter_entry_points():
            inst = self.entry_point_load_validated(entry_point)
            if not inst:
                continue

            if entry_point.name in runtimes:
                reg_ep = entry_points[entry_point.name]
                reg_rt = runtimes[entry_point.name]

                if reg_rt is inst:
                    # this is fine, multiple packages declared the same
                    # thing with the same name.
                    logger.debug(
                        "duplicated registration of command '%s' via entry "
                        "point '%s' ignored; registered '%s', confict '%s'",
                        entry_point.name, entry_point, reg_ep.dist,
                        entry_point.dist,
                    )
                    continue

                logger.error(
                    "a calmjs runtime command named '%s' already registered.",
                    entry_point.name
                )
                logger.info("conflicting entry points are:")
                logger.info(
                    "'%s' from '%s' (registered)", reg_ep, reg_ep.dist)
                logger.info(
                    "'%s' from '%s' (conflict)", entry_point, entry_point.dist)
                # Fall back name should work if the class/instances are
                # stable.
                name = to_module_attr(entry_point)

                if name in runtimes:
                    # Maybe this is the third time this module is
                    # registered.  Test for its identity.
                    if runtimes[name] is not inst:
                        # Okay someone is having a fun time here mucking
                        # with data structures internal to here, likely
                        # (read hopefully) due to testing or random
                        # monkey patching (or module level reload).
                        logger.critical(
                            "'%s' is already registered but points to a "
                            "completely different instance; please try again "
                            "with verbose logging and note which packages are "
                            "reported as conflicted; alternatively this is a "
                            "forced situation where this Runtime instance has "
                            "been used or initialized improperly.",
                            name
                        )
                    else:
                        logger.debug(
                            "fallback command '%s' is already registered.",
                            name
                        )
                    continue

                logger.error(
                    "falling back to using full instance path '%s' as command "
                    "name, also registering alias for registered command", name
                )
                register(to_module_attr(reg_ep), reg_rt, reg_ep)
            else:
                name = entry_point.name

            register(name, inst, entry_point)
720459
def MakeSubparser(subparsers, parents, method, arguments=None):
    """"""
    name = ('-'.join(re.split(r'([A-Z][a-z]+)', method.__name__)[1:-1:2])).lower()
    help = method.__doc__.splitlines()[0]
    subparser = subparsers.add_parser(
        name=name, description=help, help=help.rstrip('.'), parents=parents)
    subparser.set_defaults(method=method, positional=[])
    argspec = inspect.getargspec(method)

    # Figure out positionals and default argument, if any. Explicitly includes
    # arguments that default to '' but excludes arguments that default to None.
    offset = len(argspec.args) - len(argspec.defaults or []) - 1
    positional = []
    for i in range(1, len(argspec.args)):
        if i > offset and argspec.defaults[i - offset - 1] is None:
            break
        positional.append(argspec.args[i])
    defaults = [None] * offset + list(argspec.defaults or [])

    # Add all arguments so they append to args.positional.
    args_help = _DocToArgs(method.__doc__)
    for name, default in zip(positional, defaults):
        if not isinstance(default, (None.__class__, str)):
            continue
        subparser.add_argument(
            name, help=(arguments or {}).get(name, args_help.get(name)),
            default=default, nargs='?' if default is not None else None,
            action=PositionalArg)
    if argspec.varargs:
        subparser.add_argument(
            argspec.varargs, nargs=argparse.REMAINDER,
            help=(arguments or {}).get(argspec.varargs, args_help.get(argspec.varargs)))
    return subparser
563766
def command(self, *args, **kwargs):
        
        def decorator(func):
            kwargs.setdefault('parent', self)
            result = command(*args, **kwargs)(func)
            self.add_command(result)
            return result

        return decorator
1176101
def setup_manage_parser(self, parser):
        
        parser.set_defaults(func=self.manage)
        parser.add_argument("args", nargs=argparse.REMAINDER,
                            help="arguments for django manage command")
641169
def parser(subparsers):
    ""

    # create the parser for the version subcommand.
    parser_version = subparsers.add_parser(
        'version',
        help="Output the version of %(prog)s to the console.")
    parser_version.set_defaults(func=command_version)

    return parser_version
1090847
def get_subparser(self, name, dest="subcommand", **kwargs):
        """"""
        if name not in self.children:
            # Create the subparser.
            subparsers = self._get_subparsers(dest)
            parser = subparsers.add_parser(name, **kwargs)
            self.children[name] = NamedParser(name, parser)
        return self.children[name]
1116723
def setup_parser(sub_parsers):
    
    parser = sub_parsers.add_parser("run", prog="law run", description="Run a task with"
        " configurable parameters. See http://luigi.rtfd.io/en/stable/running_luigi.html for more"
        " info.")

    parser.add_argument("task_family", help="a task family registered in the task database file or"
        " a module and task class in the format <module>.<class>")
    parser.add_argument("parameter", nargs="*", help="task parameters")
1096963
def add_list_blocks_parser(subparsers, parent_parser):
    
    parser = subparsers.add_parser(
        'list-blocks',
        help='List blocks from different nodes.',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog='',
        parents=[parent_parser, base_multinode_parser()])

    parser.add_argument(
        '-n',
        '--count',
        default=10,
        type=int,
        help='the number of blocks to list')
72643
def _make_argparser(self):
        """"""
        self.argparser = ShellArgumentParser(prog='')
        subparsers = self.argparser.add_subparsers()

        for name in self.get_names():
            if name.startswith('parser_'):
                parser = subparsers.add_parser(name[7:])
                parser.set_defaults(func=getattr(self, 'arg_' + name[7:]))
                getattr(self, name)(parser)

        self.argparser_completer = None

        try:
            import argcomplete
        except ImportError:
            pass
        else:
            os.environ.setdefault("_ARGCOMPLETE_COMP_WORDBREAKS", " \t\"'")
            self.argparser_completer = argcomplete.CompletionFinder(self.argparser)
554790
def _get_subparsers(self, dest):
        """"""
        if not self._subparsers:
            self._subparsers = self.parser.add_subparsers(dest=dest)
        elif self._subparsers.dest != dest:
            raise KeyError(
                "Subparser names mismatch. You can only create one subcommand.")
        return self._subparsers
413418
def subcommand(self, command_name=None):
        
        def wrapper(decorated):
            cmd_name = command_name or decorated.__name__
            subparser = self.subparsers.add_parser(cmd_name,
                                                   description=decorated.__doc__)
            for args, kwargs in describe_arguments(decorated):
                subparser.add_argument(*args, **kwargs)
            subparser.set_defaults(func=decorated)
            return decorated
        return wrapper
821719
def create_parser(self, prog_name, subcommand):
        
        parser = argparse.ArgumentParser(prog='%s %s' % (prog_name, subcommand), description=self.help)

        parser.add_argument('-v', '--verbosity', action='store', default=1, type=int, choices=range(4),
            help='Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output'),
        parser.add_argument('--settings',
            help='The Python path to a settings module, e.g. "myproject.settings.main". '
            'If this isn\'t provided, the DJANGO_SETTINGS_MODULE environment variable will be used.'),
        parser.add_argument('--pythonpath',
            help='A directory to add to the Python path, e.g. "/home/djangoprojects/myproject".'),
        parser.add_argument('--traceback', action='store_true', help='Print traceback on exception'),

        subparsers = parser.add_subparsers(description='JavaScript command to execute')

        for subparser in self.subparsers:
            subparser(self, subparsers)

        return parser