-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathext.py
322 lines (234 loc) · 9.03 KB
/
ext.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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
from docutils import nodes
from docutils.parsers import rst
from docutils.parsers.rst import directives
from docutils import statemachine
import click
def _indent(text, level=1):
prefix = ' ' * (4 * level)
def prefixed_lines():
for line in text.splitlines(True):
yield (prefix + line if line.strip() else line)
return ''.join(prefixed_lines())
def _get_usage(ctx):
"""Alternative, non-prefixed version of 'get_usage'."""
formatter = ctx.make_formatter()
pieces = ctx.command.collect_usage_pieces(ctx)
formatter.write_usage(ctx.command_path, ' '.join(pieces), prefix='')
return formatter.getvalue().rstrip('\n')
def _get_help_record(opt):
"""Re-implementation of click.Opt.get_help_record.
The variant of 'get_help_record' found in Click makes uses of slashes to
separate multiple opts, and formats option arguments using upper case. This
is not compatible with Sphinx's 'option' directive, which expects
comma-separated opts and option arguments surrounded by angle brackets [1].
[1] http://www.sphinx-doc.org/en/stable/domains.html#directive-option
"""
def _write_opts(opts):
rv, _ = click.formatting.join_options(opts)
if not opt.is_flag and not opt.count:
rv += ' <{}>'.format(opt.name)
return rv
rv = [_write_opts(opt.opts)]
if opt.secondary_opts:
rv.append(_write_opts(opt.secondary_opts))
help = opt.help or ''
extra = []
if opt.default is not None and opt.show_default:
extra.append('default: %s' % (
', '.join('%s' % d for d in opt.default)
if isinstance(opt.default, (list, tuple))
else opt.default, ))
if opt.required:
extra.append('required')
if extra:
help = '%s[%s]' % (help and help + ' ' or '', '; '.join(extra))
return ', '.join(rv), help
def _format_description(ctx):
"""Format the description for a given `click.Command`.
We parse this as reStructuredText, allowing users to embed rich
information in their help messages if they so choose.
"""
if not ctx.command.help:
return
for line in statemachine.string2lines(
ctx.command.help, tab_width=4, convert_whitespace=True):
yield line
yield ''
def _format_usage(ctx):
"""Format the usage for a `click.Command`."""
yield '.. code-block:: shell'
yield ''
for line in _get_usage(ctx).splitlines():
yield _indent(line)
yield ''
def _format_option(opt):
"""Format the output for a `click.Option`."""
opt = _get_help_record(opt)
yield '.. option:: {}'.format(opt[0])
if opt[1]:
yield ''
for line in statemachine.string2lines(
opt[1], tab_width=4, convert_whitespace=True):
yield _indent(line)
def _format_options(ctx):
"""Format all `click.Option` for a `click.Command`."""
# the hidden attribute is part of click 7.x only hence use of getattr
params = [x for x in ctx.command.params if isinstance(x, click.Option)
and not getattr(x, 'hidden', False)]
for param in params:
for line in _format_option(param):
yield line
yield ''
def _format_argument(arg):
"""Format the output of a `click.Argument`."""
yield '.. option:: {}'.format(arg.human_readable_name)
yield ''
yield _indent('{} argument{}'.format(
'Required' if arg.required else 'Optional',
'(s)' if arg.nargs != 1 else ''))
def _format_arguments(ctx):
"""Format all `click.Argument` for a `click.Command`."""
params = [x for x in ctx.command.params if isinstance(x, click.Argument)]
for param in params:
for line in _format_argument(param):
yield line
yield ''
def _format_envvar(param):
"""Format the envvars of a `click.Option` or `click.Argument`."""
yield '.. envvar:: {}'.format(param.envvar)
yield ''
if isinstance(param, click.Argument):
param_ref = param.human_readable_name
else:
# if a user has defined an opt with multiple "aliases", always use the
# first. For example, if '--foo' or '-f' are possible, use '--foo'.
param_ref = param.opts[0]
yield _indent('Provide a default for :option:`{}`'.format(param_ref))
def _format_envvars(ctx):
"""Format all envvars for a `click.Command`."""
params = [x for x in ctx.command.params if getattr(x, 'envvar')]
for param in params:
for line in _format_envvar(param):
yield line
yield ''
def _format_subcommand(command):
"""Format a sub-command of a `click.Command` or `click.Group`."""
yield '.. object:: {}'.format(command[0])
if command[1].short_help:
yield ''
for line in statemachine.string2lines(
command[1].short_help, tab_width=4, convert_whitespace=True):
yield _indent(line)
def _format_command(ctx, show_nested):
"""Format the output of `click.Command`."""
# description
for line in _format_description(ctx):
yield line
yield '.. program:: {}'.format(ctx.command_path)
# usage
for line in _format_usage(ctx):
yield line
# options
lines = list(_format_options(ctx))
if lines:
# we use rubric to provide some separation without exploding the table
# of contents
yield '.. rubric:: Options'
yield ''
for line in lines:
yield line
# arguments
lines = list(_format_arguments(ctx))
if lines:
yield '.. rubric:: Arguments'
yield ''
for line in lines:
yield line
# environment variables
lines = list(_format_envvars(ctx))
if lines:
yield '.. rubric:: Environment variables'
yield ''
for line in lines:
yield line
# if we're nesting commands, we need to do this slightly differently
if show_nested:
return
commands = sorted(getattr(ctx.command, 'commands', {}).items())
if commands:
yield '.. rubric:: Commands'
yield ''
for command in commands:
for line in _format_subcommand(command):
yield line
yield ''
class ClickDirective(rst.Directive):
has_content = False
required_arguments = 1
option_spec = {
'prog': directives.unchanged_required,
'show-nested': directives.flag,
}
def _load_module(self, module_path):
"""Load the module."""
# __import__ will fail on unicode,
# so we ensure module path is a string here.
module_path = str(module_path)
try:
module_name, attr_name = module_path.split(':', 1)
except ValueError: # noqa
raise self.error('"{}" is not of format "module.parser"'.format(
module_path))
try:
mod = __import__(module_name, globals(), locals(), [attr_name])
except: # noqa
raise self.error('Failed to import "{}" from "{}"'.format(
attr_name, module_name))
if not hasattr(mod, attr_name):
raise self.error('Module "{}" has no attribute "{}"'.format(
module_name, attr_name))
return getattr(mod, attr_name)
def _generate_nodes(self, name, command, parent=None, show_nested=False):
"""Generate the relevant Sphinx nodes.
Format a `click.Group` or `click.Command`.
:param name: Name of command, as used on the command line
:param command: Instance of `click.Group` or `click.Command`
:param parent: Instance of `click.Context`, or None
:param show_nested: Whether subcommands should be included in output
:returns: A list of nested docutil nodes
"""
ctx = click.Context(command, info_name=name, parent=parent)
# Title
section = nodes.section(
'',
nodes.title(text=name),
ids=[nodes.make_id(ctx.command_path)],
names=[nodes.fully_normalize_name(ctx.command_path)])
# Summary
source_name = ctx.command_path
result = statemachine.ViewList()
lines = _format_command(ctx, show_nested)
for line in lines:
result.append(line, source_name)
self.state.nested_parse(result, 0, section)
# Subcommands
if show_nested:
commands = getattr(ctx.command, 'commands', {})
for command_name, command_obj in sorted(commands.items()):
section.extend(self._generate_nodes(
command_name,
command_obj,
ctx,
show_nested))
return [section]
def run(self):
self.env = self.state.document.settings.env
command = self._load_module(self.arguments[0])
if 'prog' in self.options:
prog_name = self.options.get('prog')
else:
raise self.error(':prog: must be specified')
show_nested = 'show-nested' in self.options
return self._generate_nodes(prog_name, command, None, show_nested)
def setup(app):
app.add_directive('click', ClickDirective)