How to use the docopt.DocoptLanguageError 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
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 + ';')
                   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 + ';')
github lbryio / lbry-sdk / tests / unit / test_cli.py View on Github external
def test_can_parse_api_method_docs(self):
        failures = []
        for name, fn in Daemon.callable_methods.items():
            try:
                docopt.docopt(fn.__doc__, ())
            except docopt.DocoptLanguageError as err:
                failures.append(f"invalid docstring for {name}, {err.message}")
            except docopt.DocoptExit:
                pass
        if failures:
            self.fail("\n" + "\n".join(failures))
github lbryio / lbry-sdk / tests / unit / lbrynet_daemon / test_docs.py View on Github external
def test_can_parse_api_method_docs(self):
        failures = []
        for name, fn in Daemon.callable_methods.items():
            try:
                docopt.docopt(fn.__doc__, ())
            except docopt.DocoptLanguageError as err:
                failures.append(f"invalid docstring for {name}, {err.message}")
            except docopt.DocoptExit:
                pass
        if failures:
            self.fail("\n" + "\n".join(failures))
github omegaml / omegaml / omegaml / client / docoptparser.py View on Github external
def safe_docopt(doc, argv=None, help=True, version=None, options_first=False):
    """
    A docopt drop-in replacement to print meaning full error messages in case
    of a DocoptLanguageError exception

    Args:
        same as docopt

    Returns
        parsed args
    """
    try:
        args = docopt(doc, argv=argv, help=help, version=version, options_first=options_first)
    except DocoptLanguageError as e:
        print("*** ERROR {}, check below".format(e))
        print("arguments to doctopt were")
        print("   argv=", argv)
        print("   doc=", doc)
        print("**** ERROR {}, check above messages ***".format(e))
        exit(1)
    return args
github contains-io / rcli / rcli / usage.py View on Github external
def parse_commands(docstring):
    # type: (str) -> Generator[Tuple[List[str], List[str]], None, None]
    """Parse a docopt-style string for commands and subcommands.

    Args:
        docstring: A docopt-style string to parse. If the string is not a valid
            docopt-style string, it will not yield and values.

    Yields:
        All tuples of commands and subcommands found in the docopt docstring.
    """
    try:
        docopt.docopt(docstring, argv=())
    except (TypeError, docopt.DocoptLanguageError):
        return
    except docopt.DocoptExit:
        pass
    for command in _parse_section("usage", docstring):
        args = command.split()
        commands = []
        i = 0
        for i, arg in enumerate(args):
            if arg[0].isalpha() and not arg[0].isupper():
                commands.append(arg)
            else:
                break
        yield commands, args[i:]
github NicolasLM / sauna / sauna / main.py View on Github external
# Override the logging configuration with the one from the config file
        logging.config.dictConfig(config['logging'])

    sauna_instance = sauna.Sauna(config)

    # Generic commands implemented in sauna.commands package
    if args.get(''):
        argv = [args['']] + args['']
        try:
            func = commands.CommandRegister.all_commands[args['']]
        except KeyError:
            print('{} is not a valid command'.format(args['']))
            sys.exit(1)
        try:
            command_args = docopt(func.__doc__, argv=argv)
        except DocoptLanguageError:
            command_args = None
        func(sauna_instance, command_args)

    # Just run sauna
    else:
        sauna_instance.launch()

    logging.shutdown()
github docopt / docopt.c / docopt.py View on Github external
'': '80',
     'serial': False,
     'tcp': True}

    See also
    --------
    * For video introduction see http://docopt.org
    * Full documentation is available in README.rst as well as online
      at https://github.com/docopt/docopt#readme

    """
    argv = sys.argv[1:] if argv is None else argv

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

    options = parse_defaults(doc)
    pattern = parse_pattern(formal_usage(DocoptExit.usage), options)
    # [default] syntax for argument is disabled
    #for a in pattern.flat(Argument):
    #    same_name = [d for d in arguments if d.name == a.name]
    #    if same_name:
    #        a.value = same_name[0].value
    argv = parse_argv(Tokens(argv), list(options), options_first)
    pattern_options = set(pattern.flat(Option))
    for options_shortcut in pattern.flat(OptionsShortcut):
        doc_options = parse_defaults(doc)
        options_shortcut.children = list(set(doc_options) - pattern_options)
github sloria / konch / docopt.py View on Github external
'': '80',
     'serial': False,
     'tcp': True}

    See also
    --------
    * For video introduction see http://docopt.org
    * Full documentation is available in README.rst as well as online
      at https://github.com/docopt/docopt#readme

    """
    argv = sys.argv[1:] if argv is None else argv

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

    options = parse_defaults(doc)
    pattern = parse_pattern(formal_usage(DocoptExit.usage), options)
    # [default] syntax for argument is disabled
    #for a in pattern.flat(Argument):
    #    same_name = [d for d in arguments if d.name == a.name]
    #    if same_name:
    #        a.value = same_name[0].value
    argv = parse_argv(Tokens(argv), list(options), options_first)
    pattern_options = set(pattern.flat(Option))
    for options_shortcut in pattern.flat(OptionsShortcut):
        doc_options = parse_defaults(doc)
        options_shortcut.children = list(set(doc_options) - pattern_options)