From 1d925db469c3293700b80458ee052f5b8bd72565 Mon Sep 17 00:00:00 2001 From: Angel Ezquerra Date: Fri, 14 Feb 2014 16:32:23 +0100 Subject: [PATCH] Add support for docopt's [options] shortcut (closes issue #22) When the [options] shortcut is detected on the usage section, we use the contents of the options section to get the full list of options, rather than just getting those options that are explicitly mentioned on the usage section. --- docopt_c.py | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/docopt_c.py b/docopt_c.py index 0e288ee..453d1ff 100644 --- a/docopt_c.py +++ b/docopt_c.py @@ -98,25 +98,32 @@ def c_if_option(o): c_name(o.long or o.short)) -def parse_leafs(pattern): +def parse_leafs(pattern, all_options): + options_shortcut = False leafs = [] queue = [(0, pattern)] while queue: level, node = queue.pop(-1) # depth-first search - if hasattr(node, 'children'): + if not options_shortcut and type(node) == docopt.OptionsShortcut: + options_shortcut = True + elif hasattr(node, 'children'): children = [((level + 1), child) for child in node.children] children.reverse() queue.extend(children) else: if node not in leafs: leafs.append(node) - leafs.sort(key=lambda e: e.name) + sort_by_name = lambda e: e.name + leafs.sort(key=sort_by_name) commands = [leaf for leaf in leafs if type(leaf) == docopt.Command] arguments = [leaf for leaf in leafs if type(leaf) == docopt.Argument] - flags = [leaf for leaf in leafs - if type(leaf) == docopt.Option and leaf.argcount == 0] - options = [leaf for leaf in leafs - if type(leaf) == docopt.Option and leaf.argcount > 0] + if options_shortcut: + option_leafs = all_options + option_leafs.sort(key=sort_by_name) + else: + option_leafs = [leaf for leaf in leafs if type(leaf) == docopt.Option] + flags = [leaf for leaf in option_leafs if leaf.argcount == 0] + options = [leaf for leaf in option_leafs if leaf.argcount > 0] leafs = [i for sl in [commands, arguments, flags, options] for i in sl] return leafs, commands, arguments, flags, options @@ -148,9 +155,9 @@ def parse_leafs(pattern): 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) + all_options = docopt.parse_defaults(doc) + pattern = docopt.parse_pattern(docopt.formal_usage(usage), all_options) + leafs, commands, arguments, flags, options = parse_leafs(pattern, all_options) t_commands = ';\n '.join('int %s' % c_name(cmd.name) for cmd in commands)