How to use the docopt.parse_defaults 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
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 + ';')
                   if t_arguments != '' else '')
    t_flags = ';\n    '.join('int %s' % c_name(flag.long or flag.short)
                             for flag in flags)
    t_flags = (('\n    /* options without arguments */\n    ' + t_flags + ';')
               if t_flags != '' else '')
    t_options = ';\n    '.join('char *%s' % c_name(opt.long or opt.short)
github boutiques / boutiques / tools / python / boutiques / importer.py View on Github external
def __init__(self, docopt_str, base_descriptor):
        with open(base_descriptor, "r") as base_desc:
            self.descriptor = collections.OrderedDict(json.load(base_desc))

        del self.descriptor['groups']
        del self.descriptor['inputs']
        del self.descriptor['output-files']
        self.docopt_str = docopt_str
        self.dependencies = collections.OrderedDict()
        self.all_desc_and_type = collections.OrderedDict()
        self.unique_ids = []

        try:
            # docopt code snippet to extract args tree (pattern)
            # should run if docopt script is valid
            options = parse_defaults(docopt_str)

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

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

            for options_shortcut in self.pattern.flat(AnyOptions):
                doc_options = parse_defaults(docopt_str)
                options_shortcut.children = list(
                    set(doc_options) - pattern_options)
            matched, left, collected = self.pattern.fix().match(argv)
        except Exception:
github boutiques / boutiques / tools / python / boutiques / util / docoptHelper.py View on Github external
def __init__(self, docopt_str, base_descriptor=None):
        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 SciCrunch / scibot / scibot / bookmarklet.py View on Github external
def main(local=False):
    from scibot.config import api_token, username, group, group2
    print(username, group, group2)  # sanity check
    from scibot.sync import __doc__ as sync__doc__, Locker, client
    from scibot.config import syncword
    if syncword is None:
        raise KeyError('Please set the SCIBOT_SYNC environment variable')

    from docopt import docopt, parse_defaults
    _sdefaults = {o.name:o.value if o.argcount else None for o in parse_defaults(sync__doc__)}
    _backup_sync_port = int(_sdefaults['--port'])

    app = Flask('scibot bookmarklet server')

    h = HypothesisUtils(username=username, token=api_token, group=group)
    h2 = HypothesisUtils(username=username, token=api_token, group=group2)

    if __name__ == '__main__':
        args = docopt(__doc__)
        _sync_port = args['--sync-port']

        if _sync_port:
            sync_port = int(_sync_port)
        else:
            sync_port = _backup_sync_port
    else:
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
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 docopt / docopt.c / docopt.c.py View on Github external
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('<<>>',
                      ';\n    '.join('char *%s' % c_name(o.long or o.short)
                                     for o in options if o.argcount == 1))
    out = out.replace('<<>>', to_c(doc))
    out = out.replace('<<>>', to_c(usage))
    
    defaults = ', '.join(to_c(o.value) for o in sorted(options, key=lambda o: o.argcount))
    defaults = re.sub(r'"(.*?)"', r'(char*) "\1"', defaults)
    out = out.replace('<<>>', defaults)
github Infinidat / infi.docopt_completion / src / infi / docopt_completion / common.py View on Github external
def parse_params(cmd):
    # This creates a parameter tree (CommandParams object) for the target docopt tool.
    # Also returns a second parameter, a dict of:
    #   option->option-help-string
    from docopt import parse_defaults, parse_pattern, formal_usage, printable_usage
    usage = get_usage(cmd)
    options = parse_defaults(usage)
    pattern = parse_pattern(formal_usage(printable_usage(usage)), options)
    param_tree = CommandParams()
    build_command_tree(pattern, param_tree)
    return param_tree, dict(list(get_options_descriptions(usage)))
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)