| 1 |
import json |
| 2 |
import argparse |
| 3 |
|
| 4 |
REPEATABLE_ACTIONS = ["extend", "append", "append_const", "count"] |
| 5 |
|
| 6 |
|
| 7 |
def get_arg_list(arg): |
| 8 |
if arg.nargs is None or arg.nargs == 1: |
| 9 |
return [{}] |
| 10 |
elif arg.nargs == argparse.OPTIONAL: |
| 11 |
return [{"isOptional": True}] |
| 12 |
elif arg.nargs == argparse.ZERO_OR_MORE: |
| 13 |
return [{"isOptional": True, "isVariadic": True}] |
| 14 |
elif arg.nargs == argparse.ONE_OR_MORE: |
| 15 |
return [{}, {"isOptional": True, "isVariadic": True}] |
| 16 |
elif isinstance(arg.nargs, int): |
| 17 |
return [{} for i in range(arg.nargs)] |
| 18 |
else: |
| 19 |
return [{"isOptional": True, "isVariadic": True}] |
| 20 |
|
| 21 |
|
| 22 |
def get_arg_names(arg, n=None): |
| 23 |
if n is None: |
| 24 |
n = len(get_arg_list(arg)) |
| 25 |
if isinstance(arg.metavar, tuple): |
| 26 |
return arg.metavar |
| 27 |
elif arg.metavar is not None: |
| 28 |
return (arg.metavar,) * n |
| 29 |
elif arg.dest != argparse.SUPPRESS: |
| 30 |
return (arg.dest,) * n |
| 31 |
return None |
| 32 |
|
| 33 |
|
| 34 |
def get_base_suggestion(arg): |
| 35 |
"""Compute properties shared amongst Fig spec options and args.""" |
| 36 |
result = {} |
| 37 |
if arg.help is not None: |
| 38 |
if arg.help == argparse.SUPPRESS: |
| 39 |
result["hidden"] = True |
| 40 |
else: |
| 41 |
result["description"] = str(arg.help) |
| 42 |
elif arg.dest != argparse.SUPPRESS: |
| 43 |
result["description"] = str(arg.dest) |
| 44 |
return result |
| 45 |
|
| 46 |
|
| 47 |
def construct_args(arg, hooks, parser, add_descriptions = True): |
| 48 |
"""Construct Fig arg array given an argparse argument.""" |
| 49 |
arg_hook = hooks.get("arg") |
| 50 |
|
| 51 |
|
| 52 |
base_arg = get_base_suggestion(arg) |
| 53 |
|
| 54 |
if not add_descriptions and "description" in base_arg: |
| 55 |
del base_arg["description"] |
| 56 |
|
| 57 |
if hasattr(arg.choices, '__iter__'): |
| 58 |
base_arg["suggestions"] = [str(a) for a in arg.choices] |
| 59 |
|
| 60 |
args = get_arg_list(arg) |
| 61 |
|
| 62 |
|
| 63 |
names = get_arg_names(arg, len(args)) |
| 64 |
if names is not None: |
| 65 |
for name, arg in zip(names, args): |
| 66 |
arg["name"] = str(name) |
| 67 |
|
| 68 |
|
| 69 |
for arg in args: |
| 70 |
if arg.get("isVariadic", False): |
| 71 |
arg["optionsCanBreakVariadicArg"] = True |
| 72 |
arg.update(base_arg) |
| 73 |
if arg_hook: |
| 74 |
arg_hook(arg, parser) |
| 75 |
|
| 76 |
return args |
| 77 |
|
| 78 |
|
| 79 |
def construct_option(arg, hooks, parser): |
| 80 |
"""Construct Fig option given an argparse argument.""" |
| 81 |
option_args = construct_args(arg, hooks, parser, add_descriptions=False) |
| 82 |
if len(arg.option_strings) > 1: |
| 83 |
name = [str(name) for name in arg.option_strings] |
| 84 |
else: |
| 85 |
name = arg.option_strings[0] |
| 86 |
|
| 87 |
option = { |
| 88 |
"name": name, |
| 89 |
**get_base_suggestion(arg) |
| 90 |
} |
| 91 |
|
| 92 |
if hasattr(arg, "action") and arg.action in REPEATABLE_ACTIONS: |
| 93 |
option["isRepeatable"] = True |
| 94 |
if option_args: |
| 95 |
option["args"] = option_args |
| 96 |
if arg.required: |
| 97 |
option["isRequired"] = True |
| 98 |
|
| 99 |
option_hook = hooks.get("option") |
| 100 |
if option_hook: |
| 101 |
option_hook(option, parser) |
| 102 |
|
| 103 |
return option |
| 104 |
|
| 105 |
|
| 106 |
def construct_subcommand( |
| 107 |
parser, |
| 108 |
hooks=None, |
| 109 |
arg_filter=None, |
| 110 |
is_root=True |
| 111 |
): |
| 112 |
"""Construct Fig subcommand given an argparse parser.""" |
| 113 |
subcommands = [] |
| 114 |
options = [] |
| 115 |
args = [] |
| 116 |
subcommand = {} |
| 117 |
hooks = {} if hooks is None else hooks |
| 118 |
subcommand_hook = hooks.get("subcommand") |
| 119 |
|
| 120 |
if is_root: |
| 121 |
subcommand["name"] = parser.prog |
| 122 |
|
| 123 |
for arg in parser._actions: |
| 124 |
if arg_filter is not None and arg_filter(arg): |
| 125 |
continue |
| 126 |
if arg.nargs == argparse.PARSER: |
| 127 |
subcommand.update(get_base_suggestion(arg)) |
| 128 |
help_map = {a.dest: a.help for a in arg._choices_actions} |
| 129 |
|
| 130 |
nested_subcommands = {} |
| 131 |
for name, nested_parser in arg.choices.items(): |
| 132 |
if nested_parser in nested_subcommands: |
| 133 |
nested_subcommands[nested_parser]["name"].append(name) |
| 134 |
else: |
| 135 |
nested_subcommands[nested_parser] = { |
| 136 |
"name": [name], |
| 137 |
**construct_subcommand( |
| 138 |
nested_parser, |
| 139 |
hooks=hooks, |
| 140 |
arg_filter=arg_filter, |
| 141 |
is_root=False |
| 142 |
), |
| 143 |
} |
| 144 |
if name in help_map and help_map[name] != argparse.SUPPRESS: |
| 145 |
nested_subcommands[nested_parser]["description"] = str(help_map[name]) |
| 146 |
for p, nested_subcommand in nested_subcommands.items(): |
| 147 |
if len(nested_subcommand["name"]) == 1: |
| 148 |
nested_subcommand["name"] = nested_subcommand["name"][0] |
| 149 |
if subcommand_hook: |
| 150 |
subcommand_hook(nested_subcommand, p) |
| 151 |
subcommands.append(nested_subcommand) |
| 152 |
elif arg.option_strings: |
| 153 |
options.append(construct_option(arg, hooks, parser)) |
| 154 |
else: |
| 155 |
args.extend(construct_args(arg, hooks, parser)) |
| 156 |
|
| 157 |
if subcommands: |
| 158 |
subcommand["subcommands"] = subcommands |
| 159 |
if options: |
| 160 |
subcommand["options"] = options |
| 161 |
if args: |
| 162 |
subcommand["args"] = args |
| 163 |
|
| 164 |
if is_root and subcommand_hook: |
| 165 |
subcommand_hook(subcommand, parser) |
| 166 |
|
| 167 |
return subcommand |
| 168 |
|
| 169 |
|
| 170 |
def generate_completion_spec( |
| 171 |
parser, |
| 172 |
hooks=None, |
| 173 |
arg_filter=None, |
| 174 |
tool="argparse_complete_fig" |
| 175 |
): |
| 176 |
"""Generate Fig spec file given a root ArgumentParser object.""" |
| 177 |
spec = construct_subcommand(parser, hooks, arg_filter) |
| 178 |
return f"""// Autogenerated by {tool} |
| 179 |
const completionSpec: Fig.Spec = {json.dumps(spec, indent=2)} |
| 180 |
export default completionSpec;""" |
| 181 |
|
| 182 |
|
| 183 |
class GenerateFigSpecAction(argparse.Action): |
| 184 |
def __init__( |
| 185 |
self, |
| 186 |
option_strings, |
| 187 |
help="Generate fig completion spec for this parser", |
| 188 |
*args, |
| 189 |
**kwargs, |
| 190 |
): |
| 191 |
super(GenerateFigSpecAction, self).__init__( |
| 192 |
option_strings=option_strings, |
| 193 |
dest=argparse.SUPPRESS, |
| 194 |
default=argparse.SUPPRESS, |
| 195 |
help=help, |
| 196 |
nargs=0, |
| 197 |
) |
| 198 |
|
| 199 |
def __call__(self, parser, namespace, values, option_string=None): |
| 200 |
def option_hook(option, _parser): |
| 201 |
if option["name"] == "--generate-fig-spec": |
| 202 |
option["priority"] = 0 |
| 203 |
|
| 204 |
hooks = {"option": option_hook} |
| 205 |
spec = generate_completion_spec(parser, hooks) |
| 206 |
print(spec) |
| 207 |
parser.exit() |
| 208 |
|
| 209 |
|
| 210 |
def add_completion_spec_command(parser): |
| 211 |
parser.add_argument("--generate-fig-spec", action=GenerateFigSpecAction) |