forked from docopt/docopt.c
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdocopt_c.py
executable file
·298 lines (250 loc) · 10.4 KB
/
docopt_c.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# Copyright (c) 2012 Vladimir Keleshev, <[email protected]>
# (see LICENSE-MIT file for copying)
"""Usage: docopt_c.py [options] [<docopt>]
Processes a docopt formatted string, from either stdin or a file, and
outputs the equivalent C code to parse a CLI, to either the stdout or a file.
Options:
-o, --output-name=<outname>
Filename used to write the produced C file.
If not present, the produced code is printed to stdout.
-t, --template=<template>
Filename used to read a C template.
-h,--help Show this help message and exit.
Arguments:
<docopt> Input file describing your CLI in docopt language.
"""
import sys
import os.path
import re
import docopt
from string import Template
import textwrap
import numbers
docopt_prefix = 'docopt_'
def to_c(s):
if type(s) is str:
if (s.startswith(docopt_prefix)):
return s;
return ('"%s"' % s.replace('\\', r'\\')\
.replace('"', r'\"')\
.replace('\n', '\\n"\n"'))
if s is True:
return '1'
if s is False:
return '0'
if isinstance(s, numbers.Number):
return str(s)
if s is None:
return 'NULL'
raise ValueError("can't convert to c type: %r" % s)
def c_command(o):
s = docopt_prefix + o.name
return '{%s}' % ', '.join(to_c(v) for v in (o.name, o.value, s))
def c_argument(o):
return '{%s}' % ', '.join(to_c(v) for v in (o.name, o.value, 0, None))
def c_option(o):
return '{%s}' % ', '.join(to_c(v) for v in (o.short, o.long, o.argcount,
False, None))
def c_name(s):
return ''.join(c if c.isalnum() else '_' for c in s).strip('_')
def c_if_command(cmd):
t = """if (!strcmp(command->name, %s)) {
args->%s = command->value;
}"""
return t % (to_c(cmd.name), c_name(cmd.name))
def c_if_argument(arg):
t = """if (!strcmp(argument->name, %s)) {
args->%s = argument->value;
}"""
return t % (to_c(arg.name), c_name(arg.name))
def c_if_flag(o):
t = """ else if (!strcmp(option->o%s, %s)) {
args->%s = option->value;
}"""
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_option(o):
t = """ else if (!strcmp(option->o%s, %s)) {
if (option->argument)
args->%s = option->argument;
}"""
return t % (('long' if o.long else 'short'),
to_c(o.long or o.short),
c_name(o.long or o.short))
def parse_leafs(pattern, all_options):
options_shortcut = False
leafs = []
queue = [(0, pattern)]
while queue:
level, node = queue.pop(-1) # depth-first search
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)
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]
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
def append_argument_set(positional_str, cmd_set, arg_set):
if len(cmd_set):
cmd_arg = ''
for cmd in cmd_set:
cmd_arg = "\nstatic Argument " + docopt_prefix + cmd.name + '[] = {'
for arg in arg_set:
cmd_arg += "\n " + c_argument(arg) + ","
cmd_arg += '\n {NULL, NULL, 0, NULL}\n};\n'
positional_str += cmd_arg
cmd_set = []
arg_set = []
return positional_str, cmd_set, arg_set
def parse_positionals(pattern):
c_positional = ''
cmd_set = []
arg_set = []
seen_set = []
options_shortcut = False
leafs = []
queue = [(0, pattern)]
while queue:
level, node = queue.pop(-1) # depth-first search
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)
# print("Node " + str(node))
if (type(node) == docopt.Command):
if (node) not in seen_set:
cmd_set.append(node)
seen_set.append(node)
elif (type(node) == docopt.Argument):
if len(cmd_set) != 0:
arg_set.append(node)
elif (type(node) == docopt.Required):
c_positional, cmd_set, arg_set = append_argument_set(c_positional, cmd_set, arg_set)
elif (type(node) == docopt.Either):
continue
elif (type(node) == docopt.OneOrMore):
continue
elif (type(node) == docopt.Optional):
continue
elif (type(node) == docopt.Option):
continue
else:
c_positional, cmd_set, arg_set = append_argument_set(c_positional, cmd_set, arg_set)
c_positional, cmd_set, arg_set = append_argument_set(c_positional, cmd_set, arg_set)
return c_positional
if __name__ == '__main__':
args = docopt.docopt(__doc__)
try:
if args['<docopt>'] is not None:
with open(args['<docopt>'], 'r') as f:
args['<docopt>'] = f.read()
elif args['<docopt>'] is None and sys.stdin.isatty():
print(__doc__.strip("\n"))
sys.exit("")
else:
args['<docopt>'] = 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['<docopt>']
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))
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_pattern = ''
t_pattern = ('#if 0\n /* docopt parsed pattern */\n' +
re.sub(r'([ \(])([A-Za-z]*\()', r'\n\1\2', str(pattern))
+ '\n#endif')
c_positional = parse_positionals(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)
for opt in options)
t_options = (('\n /* options with arguments */\n ' + t_options + ';')
if t_options != '' else '')
t_defaults = ', '.join(to_c(leaf.value) for leaf in leafs)
t_defaults = re.sub(r'"(.*?)"', r'(char*) "\1"', t_defaults)
t_defaults = '\n '.join(textwrap.wrap(t_defaults, 72))
t_defaults = ('\n ' + t_defaults + ',') if t_defaults != '' else ''
t_elems_cmds = ',\n '.join([c_command(cmd) for cmd in (commands)])
t_elems_cmds = ('\n ' + t_elems_cmds) if t_elems_cmds != '' else ''
t_elems_args = ',\n '.join([c_argument(arg) for arg in (arguments)])
t_elems_args = ('\n ' + t_elems_args + ',') if t_elems_args != '' else ''
t_elems_opts = ',\n '.join([c_option(o) for o in (flags + options)])
t_elems_opts = ('\n ' + t_elems_opts) if t_elems_opts != '' else ''
t_elems_n = ', '.join([str(len(l))
for l in [commands, arguments, (flags + options)]])
t_if_command = ' else '.join(c_if_command(command) for command in commands)
t_if_command = ('\n ' + t_if_command) if t_if_command != '' else ''
t_if_argument = ' else '.join(c_if_argument(arg) for arg in arguments)
t_if_argument = (('\n ' + t_if_argument)
if t_if_argument != '' else '')
t_if_flag = ''.join(c_if_flag(flag) for flag in flags)
t_if_option = ''.join(c_if_option(opt) for opt in options)
out = Template(args['--template']).safe_substitute(
parsed_pattern=t_pattern,
positional=c_positional,
commands=t_commands,
arguments=t_arguments,
flags=t_flags,
options=t_options,
help_message=to_c(doc),
usage_pattern=to_c(usage),
if_flag=t_if_flag,
if_option=t_if_option,
if_command=t_if_command,
if_argument=t_if_argument,
defaults=t_defaults,
elems_cmds=t_elems_cmds,
elems_args=t_elems_args,
elems_opts=t_elems_opts,
elems_n=t_elems_n)
if args['--output-name'] is None:
print(out.strip() + '\n')
else:
try:
with open(args['--output-name'], 'w') as f:
f.write(out.strip() + '\n')
except IOError as e:
sys.exit(str(e))