Skip to content

Commit 1d925db

Browse files
committed
Add support for docopt's [options] shortcut (closes issue docopt#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.
1 parent 08c5236 commit 1d925db

File tree

1 file changed

+17
-10
lines changed

1 file changed

+17
-10
lines changed

docopt_c.py

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -98,25 +98,32 @@ def c_if_option(o):
9898
c_name(o.long or o.short))
9999

100100

101-
def parse_leafs(pattern):
101+
def parse_leafs(pattern, all_options):
102+
options_shortcut = False
102103
leafs = []
103104
queue = [(0, pattern)]
104105
while queue:
105106
level, node = queue.pop(-1) # depth-first search
106-
if hasattr(node, 'children'):
107+
if not options_shortcut and type(node) == docopt.OptionsShortcut:
108+
options_shortcut = True
109+
elif hasattr(node, 'children'):
107110
children = [((level + 1), child) for child in node.children]
108111
children.reverse()
109112
queue.extend(children)
110113
else:
111114
if node not in leafs:
112115
leafs.append(node)
113-
leafs.sort(key=lambda e: e.name)
116+
sort_by_name = lambda e: e.name
117+
leafs.sort(key=sort_by_name)
114118
commands = [leaf for leaf in leafs if type(leaf) == docopt.Command]
115119
arguments = [leaf for leaf in leafs if type(leaf) == docopt.Argument]
116-
flags = [leaf for leaf in leafs
117-
if type(leaf) == docopt.Option and leaf.argcount == 0]
118-
options = [leaf for leaf in leafs
119-
if type(leaf) == docopt.Option and leaf.argcount > 0]
120+
if options_shortcut:
121+
option_leafs = all_options
122+
option_leafs.sort(key=sort_by_name)
123+
else:
124+
option_leafs = [leaf for leaf in leafs if type(leaf) == docopt.Option]
125+
flags = [leaf for leaf in option_leafs if leaf.argcount == 0]
126+
options = [leaf for leaf in option_leafs if leaf.argcount > 0]
120127
leafs = [i for sl in [commands, arguments, flags, options] for i in sl]
121128
return leafs, commands, arguments, flags, options
122129

@@ -148,9 +155,9 @@ def parse_leafs(pattern):
148155
if isinstance(usage, list):
149156
raise docopt.DocoptLanguageError(''.join(usage))
150157

151-
options = docopt.parse_defaults(doc)
152-
pattern = docopt.parse_pattern(docopt.formal_usage(usage), options)
153-
leafs, commands, arguments, flags, options = parse_leafs(pattern)
158+
all_options = docopt.parse_defaults(doc)
159+
pattern = docopt.parse_pattern(docopt.formal_usage(usage), all_options)
160+
leafs, commands, arguments, flags, options = parse_leafs(pattern, all_options)
154161

155162
t_commands = ';\n '.join('int %s' % c_name(cmd.name)
156163
for cmd in commands)

0 commit comments

Comments
 (0)