How to use the docopt.parse_section function in docopt

To help you get started, we’ve selected a few docopt examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github docopt / docopt.c / docopt_c.py View on Github external
args[''] = f.read()
        elif args[''] is None and sys.stdin.isatty():
            print(__doc__.strip("\n"))
            sys.exit("")
        else:
            args[''] = sys.stdin.read()
        if args['--template'] is None:
            args['--template'] = os.path.join(
                    os.path.dirname(os.path.realpath(__file__)), "template.c")
        with open(args['--template'], 'r') as f:
                args['--template'] = f.read()
    except IOError as e:
        sys.exit(e)

    doc = args['']
    usage = docopt.parse_section('usage:', doc)
    s = ['More than one ', '"usage:" (case-insensitive)', ' not found.']
    usage = {0: s[1:], 1: usage[0] if usage else None}.get(len(usage), s[:2])
    if isinstance(usage, list):
        raise docopt.DocoptLanguageError(''.join(usage))

    options = docopt.parse_defaults(doc)
    pattern = docopt.parse_pattern(docopt.formal_usage(usage), options)
    leafs, commands, arguments, flags, options = parse_leafs(pattern)

    t_commands = ';\n    '.join('int %s' % c_name(cmd.name)
                                for cmd in commands)
    t_commands = (('\n    /* commands */\n    ' + t_commands + ';')
                  if t_commands != '' else '')
    t_arguments = ';\n    '.join('char *%s' % c_name(arg.name)
                                 for arg in arguments)
    t_arguments = (('\n    /* arguments */\n    ' + t_arguments + ';')
github boutiques / boutiques / tools / python / boutiques / util / docoptHelper.py View on Github external
def loadDescriptionAndType(self):
        # using docopt code to extract description and type from args
        for line in (dcpt.parse_section('arguments:', self.docopt_str) +
                     dcpt.parse_section('options:', self.docopt_str)):
            _, _, s = line.partition(':')  # get rid of "options:"
            split = re.split('\n[ \t]*(-\S+?)', '\n' + s)[1:] if\
                line in dcpt.parse_section('options:', self.docopt_str) else\
                re.split('\n[ \t]*(<\S+?)', '\n' + s)[1:]
            split = [s1 + s2 for s1, s2 in zip(split[::2], split[1::2])]
            # parse each line of Arguments and Options
            for arg_str in [s for s in split if (s.startswith('-') or
                            s.startswith('<'))]:
                arg = dcpt.Option.parse(arg_str) if arg_str.startswith('-')\
                    else dcpt.Argument.parse(arg_str)
                arg_segs = arg_str.partition('  ')
                self.all_desc_and_type[arg.name] = {
                    "desc": arg_segs[-1].replace('\n', ' ')
                                        .replace("  ", '').strip()}
                if hasattr(arg, "value") and arg.value is not None and\
github boutiques / boutiques / tools / python / boutiques / util / docoptHelper.py View on Github external
def generateInputsAndCommandLine(self, node):
        child_node_type = type(node.children[0]).__name__
        if hasattr(node, 'children') and (child_node_type == "Either" or
                                          child_node_type == "Required"):
            for child in node.children:
                self.generateInputsAndCommandLine(child)
        # Traversing reached usage level
        else:
            self.descriptor['command-line'] = dcpt.parse_section(
                'usage:', self.docopt_str)[0].split("\n")[1:][0].split()[0]
            self._loadInputsFromUsage(node)
github boutiques / boutiques / tools / python / boutiques / util / docoptHelper.py View on Github external
if base_descriptor is not None:
            with open(base_descriptor, "r") as base_desc:
                self.descriptor = json.load(base_desc)
        else:
            self.descriptor = {
                "inputs": []
            }

        self.docopt_str = docopt_str
        self.dependencies = {}
        self.all_desc_and_type = {}
        self.unique_ids = {}
        options = dcpt.parse_defaults(docopt_str)

        self.pattern = dcpt.parse_pattern(
            dcpt.formal_usage(dcpt.parse_section('usage:', docopt_str)[0]),
            options)

        argv = dcpt.parse_argv(dcpt.Tokens(sys.argv[1:]), list(options), False)
        pattern_options = set(self.pattern.flat(dcpt.Option))

        for options_shortcut in self.pattern.flat(dcpt.OptionsShortcut):
            doc_options = dcpt.parse_defaults(docopt_str)
            options_shortcut.children = list(set(doc_options) - pattern_options)
        matched, left, collected = self.pattern.fix().match(argv)
github boutiques / boutiques / tools / python / boutiques / util / docoptHelper.py View on Github external
def loadDocoptDescription(self):
        self.descriptor["description"] = self.docopt_str\
            .replace("".join(dcpt.parse_section(
                'usage:', self.docopt_str)), "")\
            .replace("".join(dcpt.parse_section(
                'arguments:', self.docopt_str)), "")\
            .replace("".join(dcpt.parse_section(
                'options:', self.docopt_str)), "")\
            .replace("\n\n", "\n").strip()
github boutiques / boutiques / tools / python / boutiques / util / parserHelper.py View on Github external
def docoptToArgumentParser(self, docopt_str):
        # initial doc validation
        extc_dict = dcpt.docopt(docopt_str)

        usage_sections = dcpt.parse_section('usage:', docopt_str)

        options = dcpt.parse_defaults(docopt_str)
        pattern = dcpt.parse_pattern(
            dcpt.formal_usage(usage_sections[0]), options)
        argv = dcpt.parse_argv(dcpt.Tokens(sys.argv[1:]), list(options), False)
        pattern_options = set(pattern.flat(dcpt.Option))
        for options_shortcut in pattern.flat(dcpt.OptionsShortcut):
            doc_options = dcpt.parse_defaults(docopt_str)
            options_shortcut.children = list(set(doc_options) - pattern_options)
        matched, left, collected = pattern.fix().match(argv)

        # can loop through to compare extracted params with extc_dict
        # and add param to argparser for each prm
        for prm in pattern.flat() + collected:
            print(prm)
github boutiques / boutiques / tools / python / boutiques / util / docoptHelper.py View on Github external
def loadDocoptDescription(self):
        self.descriptor["description"] = self.docopt_str\
            .replace("".join(dcpt.parse_section(
                'usage:', self.docopt_str)), "")\
            .replace("".join(dcpt.parse_section(
                'arguments:', self.docopt_str)), "")\
            .replace("".join(dcpt.parse_section(
                'options:', self.docopt_str)), "")\
            .replace("\n\n", "\n").strip()
github boutiques / boutiques / tools / python / boutiques / util / docoptHelper.py View on Github external
def loadDocoptDescription(self):
        self.descriptor["description"] = self.docopt_str\
            .replace("".join(dcpt.parse_section(
                'usage:', self.docopt_str)), "")\
            .replace("".join(dcpt.parse_section(
                'arguments:', self.docopt_str)), "")\
            .replace("".join(dcpt.parse_section(
                'options:', self.docopt_str)), "")\
            .replace("\n\n", "\n").strip()
github docopt / docopt.c / docopt.c.py View on Github external
return t % (('long' if o.long else 'short'),
                to_c(o.long or o.short),
                c_name(o.long or o.short))


def c_if_not_flag(o):
    t = """ else if (o->option.argument && strcmp(o->option.o%s, %s) == 0) {
            args.%s = o->option.argument;\n        }"""
    return t % (('long' if o.long else 'short'),
                to_c(o.long or o.short),
                c_name(o.long or o.short))


if __name__ == '__main__':
    doc = sys.stdin.read()
    usage_sections = docopt.parse_section('usage:', doc)

    if len(usage_sections) == 0:
        raise docopt.DocoptLanguageError('"usage:" (case-insensitive) not found.')
    if len(usage_sections) > 1:
        raise docopt.DocoptLanguageError('More than one "usage:" (case-insensitive).')
    docopt.DocoptExit.usage = usage_sections[0]
    usage = docopt.DocoptExit.usage

    options = docopt.parse_defaults(doc)
    pattern = docopt.parse_pattern(docopt.formal_usage(usage), options)

    out = __doc__
    out = out.replace('<<>>',
                      ';\n    '.join('int %s' % c_name(o.long or o.short)
                                     for o in options if o.argcount == 0))
    out = out.replace('<<>>',