forked from google/python-fire
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelptext.py
More file actions
473 lines (388 loc) · 14.5 KB
/
Copy pathhelptext.py
File metadata and controls
473 lines (388 loc) · 14.5 KB
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
# Copyright (C) 2018 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""helptext is the new, work in progress, help text module for Fire.
This is a fork of, and is intended to replace, helputils.
Utility for producing help strings for use in Fire CLIs.
Can produce help strings suitable for display in Fire CLIs for any type of
Python object, module, class, or function.
There are two types of informative strings: Usage and Help screens.
Usage screens are shown when the user accesses a group or accesses a command
without calling it. A Usage screen shows information about how to use that group
or command. Usage screens are typically short and show the minimal information
necessary for the user to determine how to proceed.
Help screens are shown when the user requests help with the help flag (--help).
Help screens are shown in a less-style console view, and contain detailed help
information.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import inspect
from fire import completion
from fire import docstrings
from fire import inspectutils
from fire import value_types
def Text(component, trace=None, verbose=False):
"""Returns the text to show for a supplied component.
The component can be any Python class, object, function, module, etc.
Args:
component: The component to determine the help string for.
trace: The Fire trace leading to this component.
verbose: Whether to include private members in the help string.
Returns:
String suitable for display giving information about the component.
"""
info = inspectutils.Info(component)
info['docstring_info'] = docstrings.parse(info['docstring'])
is_error_screen = False
if trace:
is_error_screen = trace.HasError()
if is_error_screen:
return UsageText(info, trace, verbose=verbose)
else:
return HelpText(info, trace, verbose=verbose)
def GetArgsAngFlags(component):
"""Returns all types of arguments and flags of a component."""
spec = inspectutils.GetFullArgSpec(component)
args = spec.args
if spec.defaults is None:
num_defaults = 0
else:
num_defaults = len(spec.defaults)
args_with_no_defaults = args[:len(args) - num_defaults]
args_with_defaults = args[len(args) - num_defaults:]
flags = args_with_defaults + spec.kwonlyargs
return args_with_no_defaults, args_with_defaults, flags
def GetSummaryAndDescription(docstring_info):
"""Retrieves summary and description for help text generation."""
# To handle both empty string and None
summary = docstring_info.summary if docstring_info.summary else None
description = (
docstring_info.description if docstring_info.description else None)
return summary, description
def GetCurrentCommand(trace=None):
"""Returns current command for the purpose of generating help text."""
if trace:
current_command = trace.GetCommand()
else:
current_command = ''
return current_command
def HelpText(component, info, trace=None, verbose=False):
if inspect.isroutine(component) or inspect.isclass(component):
return HelpTextForFunction(component, info, trace)
else:
return HelpTextForObject(component, info, trace, verbose)
def HelpTextForFunction(component, info, trace=None, verbose=False):
"""Returns detail help text for a function component.
Args:
component: Current component to generate help text for.
info: Info containing metadata of component.
trace: FireTrace object that leads to current component.
verbose: Whether to display help text in verbose mode.
Returns:
Formatted help text for display.
"""
# TODO(joejoevictor): Implement verbose related output
del verbose
current_command = GetCurrentCommand(trace)
summary, description = GetSummaryAndDescription(info['docstring_info'])
spec = inspectutils.GetFullArgSpec(component)
args = spec.args
args_with_no_defaults, args_with_defaults, flags = GetArgsAngFlags(component)
del args_with_defaults
output_template = """NAME
{name_section}
SYNOPSIS
{synopsis_section}
DESCRIPTION
{description_section}
{args_and_flags_section}
NOTES
You could also use flags syntax for POSITIONAL ARGUMENTS
"""
# Name section
name_section_template = '{current_command}{command_summary}'
command_summary_str = ' - ' + summary if summary else ''
name_section = name_section_template.format(
current_command=current_command, command_summary=command_summary_str)
args_and_flags = ''
if args_with_no_defaults:
items = [arg.upper() for arg in args_with_no_defaults]
args_and_flags = ' '.join(items)
synopsis_flag_template = '[--{flag_name}={flag_name_upper}]'
if flags:
items = [
synopsis_flag_template.format(
flag_name=flag, flag_name_upper=flag.upper()) for flag in flags
]
args_and_flags = args_and_flags + ' '.join(items)
# Synopsis section
synopsis_section_template = '{current_command} {args_and_flags}'
positional_arguments = '|'.join(args)
if positional_arguments:
positional_arguments = ' ' + positional_arguments
synopsis_section = synopsis_section_template.format(
current_command=current_command, args_and_flags=args_and_flags)
# Description section
description_section = description if description else summary
args_and_flags_section = ''
# Positional arguments and flags section
pos_arg_template = """
POSITIONAL ARGUMENTS
{items}
"""
pos_arg_items = []
for arg in args_with_no_defaults:
item_template = ' {arg_name}\n {arg_description}\n'
arg_description = None
for arg_in_docstring in info['docstring_info'].args:
if arg_in_docstring.name == arg:
arg_description = arg_in_docstring.description
item = item_template.format(
arg_name=arg.upper(), arg_description=arg_description)
pos_arg_items.append(item)
if pos_arg_items:
args_and_flags_section += pos_arg_template.format(
items='\n'.join(pos_arg_items).rstrip('\n'))
flags_template = """
FLAGS
{items}
"""
flag_items = []
for flag in flags:
item_template = ' --{flag_name}\n {flag_description}\n'
flag_description = None
for arg_in_docstring in info['docstring_info'].args:
if arg_in_docstring.name == flag:
flag_description = arg_in_docstring.description
item = item_template.format(
flag_name=flag, flag_description=flag_description)
flag_items.append(item)
if flag_items:
args_and_flags_section += flags_template.format(
items='\n'.join(flag_items).rstrip('\n'))
return output_template.format(
name_section=name_section,
synopsis_section=synopsis_section,
description_section=description_section,
args_and_flags_section=args_and_flags_section)
def HelpTextForObject(component, info, trace=None, verbose=False):
"""Generates help text for python objects.
Args:
component: Current component to generate help text for.
info: Info containing metadata of component.
trace: FireTrace object that leads to current component.
verbose: Whether to display help text in verbose mode.
Returns:
Formatted help text for display.
"""
output_template = """NAME
{current_command} - {command_summary}
SYNOPSIS
{synopsis}
DESCRIPTION
{command_description}
{detail_section}
"""
current_command = GetCurrentCommand(trace)
docstring_info = info['docstring_info']
command_summary = docstring_info.summary if docstring_info.summary else ''
if docstring_info.description:
command_description = docstring_info.description
else:
command_description = ''
groups = []
commands = []
values = []
members = completion._Members(component, verbose) # pylint: disable=protected-access
for member_name, member in members:
if value_types.IsGroup(member):
groups.append((member_name, member))
if value_types.IsCommand(member):
commands.append((member_name, member))
if value_types.IsValue(member):
values.append((member_name, member))
possible_actions = []
# TODO(joejoevictor): Add global flags to here. Also, if it's a callable,
# there will be additional flags.
possible_flags = ''
detail_section_string = ''
item_template = """
{name}
{command_summary}
"""
if groups:
# TODO(joejoevictor): Add missing GROUPS section handling
possible_actions.append('GROUP')
if commands:
possible_actions.append('COMMAND')
commands_str_template = """
COMMANDS
COMMAND is one of the followings:
{items}
"""
command_item_strings = []
for command_name, command in commands:
command_docstring_info = docstrings.parse(
inspectutils.Info(command)['docstring'])
command_item_strings.append(
item_template.format(
name=command_name,
command_summary=command_docstring_info.summary))
detail_section_string += commands_str_template.format(
items=('\n'.join(command_item_strings)).rstrip('\n'))
if values:
possible_actions.append('VALUES')
values_str_template = """
VALUES
VALUE is one of the followings:
{items}
"""
value_item_strings = []
for value_name, value in values:
del value
init_docstring_info = docstrings.parse(
inspectutils.Info(component.__class__.__init__)['docstring'])
for arg_info in init_docstring_info.args:
if arg_info.name == value_name:
value_item_strings.append(
item_template.format(
name=value_name, command_summary=arg_info.description))
detail_section_string += values_str_template.format(
items=('\n'.join(value_item_strings)).rstrip('\n'))
possible_actions_string = ' ' + (' | '.join(possible_actions))
synopsis_template = '{current_command}{possible_actions}{possible_flags}'
synopsis_string = synopsis_template.format(
current_command=current_command,
possible_actions=possible_actions_string,
possible_flags=possible_flags)
return output_template.format(
current_command=current_command,
command_summary=command_summary,
synopsis=synopsis_string,
command_description=command_description,
detail_section=detail_section_string)
def UsageText(component, trace=None, verbose=False):
if inspect.isroutine(component) or inspect.isclass(component):
return UsageTextForFunction(component, trace)
else:
return UsageTextForObject(component, trace, verbose)
def UsageTextForFunction(component, trace=None):
"""Returns usage text for function objects.
Args:
component: The component to determine the usage text for.
trace: The Fire trace object containing all metadata of current execution.
Returns:
String suitable for display in error screen.
"""
output_template = """Usage: {current_command} {args_and_flags}
{availability_lines}
For detailed information on this command, run:
{current_command}{hyphen_hyphen} --help
"""
if trace:
command = trace.GetCommand()
is_help_an_arg = trace.NeedsSeparatingHyphenHyphen()
else:
command = None
is_help_an_arg = False
if not command:
command = ''
spec = inspectutils.GetFullArgSpec(component)
args = spec.args
if spec.defaults is None:
num_defaults = 0
else:
num_defaults = len(spec.defaults)
args_with_no_defaults = args[:len(args) - num_defaults]
args_with_defaults = args[len(args) - num_defaults:]
flags = args_with_defaults + spec.kwonlyargs
items = [arg.upper() for arg in args_with_no_defaults]
if flags:
items.append('<flags>')
availability_lines = (
'\nAvailable flags: '
+ ' | '.join('--' + flag for flag in flags) + '\n')
else:
availability_lines = ''
args_and_flags = ' '.join(items)
hyphen_hyphen = ' --' if is_help_an_arg else ''
return output_template.format(
current_command=command,
args_and_flags=args_and_flags,
availability_lines=availability_lines,
hyphen_hyphen=hyphen_hyphen)
def UsageTextForObject(component, trace=None, verbose=False):
"""Returns help text for usage screen for objects.
Construct help text for usage screen to inform the user about error occurred
and correct syntax for invoking the object.
Args:
component: The component to determine the usage text for.
trace: The Fire trace object containing all metadata of current execution.
verbose: Whether to include private members in the usage text.
Returns:
String suitable for display in error screen.
"""
output_template = """Usage: {current_command} <{possible_actions}>
{availability_lines}
For detailed information on this command, run:
{current_command} --help
"""
if trace:
command = trace.GetCommand()
else:
command = None
if not command:
command = ''
groups = []
commands = []
values = []
members = completion._Members(component, verbose) # pylint: disable=protected-access
for member_name, member in members:
if value_types.IsGroup(member):
groups.append(member_name)
if value_types.IsCommand(member):
commands.append(member_name)
if value_types.IsValue(member):
values.append(member_name)
possible_actions = []
availability_lines = []
availability_lint_format = '{header:20s}{choices}'
if groups:
possible_actions.append('groups')
groups_string = ' | '.join(groups)
groups_text = availability_lint_format.format(
header='available groups:',
choices=groups_string)
availability_lines.append(groups_text)
if commands:
possible_actions.append('commands')
commands_string = ' | '.join(commands)
commands_text = availability_lint_format.format(
header='available commands:',
choices=commands_string)
availability_lines.append(commands_text)
if values:
possible_actions.append('values')
values_string = ' | '.join(values)
values_text = availability_lint_format.format(
header='available values:',
choices=values_string)
availability_lines.append(values_text)
possible_actions_string = '|'.join(possible_actions)
availability_lines_string = '\n'.join(availability_lines)
return output_template.format(
current_command=command,
possible_actions=possible_actions_string,
availability_lines=availability_lines_string)