Skip to content

Commit 030ec20

Browse files
author
Sourcery AI
committed
'Refactored by Sourcery'
1 parent 38e334b commit 030ec20

File tree

1 file changed

+88
-58
lines changed

1 file changed

+88
-58
lines changed

shtab/__init__.py

Lines changed: 88 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,6 @@ def get_option_strings(parser):
161161
def recurse(parser, prefix):
162162
"""recurse through subparsers, appending to the return lists"""
163163
subparsers = []
164-
option_strings = []
165164
compgens = []
166165
choices = []
167166
nargs = []
@@ -181,21 +180,22 @@ def recurse(parser, prefix):
181180

182181
if hasattr(positional, "complete"):
183182
# shtab `.complete = ...` functions
184-
compgens.append(u"{}_pos_{}_COMPGEN={}".format(
185-
prefix, i, complete2pattern(positional.complete, "bash", choice_type2fn)))
183+
compgens.append(
184+
f'{prefix}_pos_{i}_COMPGEN={complete2pattern(positional.complete, "bash", choice_type2fn)}'
185+
)
186+
186187

187188
if positional.choices:
188189
# choices (including subparsers & shtab `.complete` functions)
189-
log.debug("choices:{}:{}".format(prefix, sorted(positional.choices)))
190+
log.debug(f"choices:{prefix}:{sorted(positional.choices)}")
190191

191192
this_positional_choices = []
192193
for choice in positional.choices:
193194
if isinstance(choice, Choice):
194195
# append special completion type to `compgens`
195196
# NOTE: overrides `.complete` attribute
196-
log.debug("Choice.{}:{}:{}".format(choice.type, prefix, positional.dest))
197-
compgens.append(u"{}_pos_{}_COMPGEN={}".format(
198-
prefix, i, choice_type2fn[choice.type]))
197+
log.debug(f"Choice.{choice.type}:{prefix}:{positional.dest}")
198+
compgens.append(f"{prefix}_pos_{i}_COMPGEN={choice_type2fn[choice.type]}")
199199
elif isinstance(positional.choices, dict):
200200
# subparser, so append to list of subparsers & recurse
201201
log.debug("subcommand:%s", choice)
@@ -211,8 +211,9 @@ def recurse(parser, prefix):
211211
new_nargs,
212212
) = recurse(
213213
positional.choices[choice],
214-
prefix + "_" + wordify(choice),
214+
f"{prefix}_{wordify(choice)}",
215215
)
216+
216217
sub_subparsers.extend(new_subparsers)
217218
sub_option_strings.extend(new_option_strings)
218219
sub_compgens.extend(new_compgens)
@@ -225,31 +226,37 @@ def recurse(parser, prefix):
225226
this_positional_choices.append(str(choice))
226227

227228
if this_positional_choices:
228-
choices.append(u"{}_pos_{}_choices='{}'".format(
229-
prefix, i, " ".join(this_positional_choices)))
229+
choices.append(
230+
f"""{prefix}_pos_{i}_choices='{" ".join(this_positional_choices)}'"""
231+
)
232+
230233

231234
# skip default `nargs` values
232235
if positional.nargs not in (None, "1", "?"):
233-
nargs.append(u"{}_pos_{}_nargs={}".format(prefix, i, positional.nargs))
236+
nargs.append(f"{prefix}_pos_{i}_nargs={positional.nargs}")
234237

235238
if discovered_subparsers:
236239
subparsers.append(u"{}_subparsers=('{}')".format(prefix,
237240
"' '".join(discovered_subparsers)))
238-
log.debug("subcommands:{}:{}".format(prefix, discovered_subparsers))
241+
log.debug(f"subcommands:{prefix}:{discovered_subparsers}")
242+
243+
option_strings = [
244+
u"{}_option_strings=('{}')".format(
245+
prefix, "' '".join(get_option_strings(parser))
246+
)
247+
]
239248

240-
# optional arguments
241-
option_strings.append(u"{}_option_strings=('{}')".format(
242-
prefix, "' '".join(get_option_strings(parser))))
243249
for optional in parser._get_optional_actions():
244250
if optional == SUPPRESS:
245251
continue
246252

247253
for option_string in optional.option_strings:
248254
if hasattr(optional, "complete"):
249255
# shtab `.complete = ...` functions
250-
compgens.append(u"{}_{}_COMPGEN={}".format(
251-
prefix, wordify(option_string),
252-
complete2pattern(optional.complete, "bash", choice_type2fn)))
256+
compgens.append(
257+
f'{prefix}_{wordify(option_string)}_COMPGEN={complete2pattern(optional.complete, "bash", choice_type2fn)}'
258+
)
259+
253260

254261
if optional.choices:
255262
# choices (including shtab `.complete` functions)
@@ -258,21 +265,24 @@ def recurse(parser, prefix):
258265
# append special completion type to `compgens`
259266
# NOTE: overrides `.complete` attribute
260267
if isinstance(choice, Choice):
261-
log.debug("Choice.{}:{}:{}".format(choice.type, prefix, optional.dest))
262-
compgens.append(u"{}_{}_COMPGEN={}".format(
263-
prefix, wordify(option_string), choice_type2fn[choice.type]))
268+
log.debug(f"Choice.{choice.type}:{prefix}:{optional.dest}")
269+
compgens.append(
270+
f"{prefix}_{wordify(option_string)}_COMPGEN={choice_type2fn[choice.type]}"
271+
)
272+
264273
else:
265274
# simple choice
266275
this_optional_choices.append(str(choice))
267276

268277
if this_optional_choices:
269-
choices.append(u"{}_{}_choices='{}'".format(
270-
prefix, wordify(option_string), " ".join(this_optional_choices)))
278+
choices.append(
279+
f"""{prefix}_{wordify(option_string)}_choices='{" ".join(this_optional_choices)}'"""
280+
)
281+
271282

272283
# Check for nargs.
273284
if optional.nargs is not None and optional.nargs != 1:
274-
nargs.append(u"{}_{}_nargs={}".format(prefix, wordify(option_string),
275-
optional.nargs))
285+
nargs.append(f"{prefix}_{wordify(option_string)}_nargs={optional.nargs}")
276286

277287
# append recursion results
278288
subparsers.extend(sub_subparsers)
@@ -466,29 +476,53 @@ def complete_zsh(parser, root_prefix=None, preamble="", choice_functions=None):
466476
choice_type2fn.update(choice_functions)
467477

468478
def format_optional(opt):
469-
return (('{nargs}{options}"[{help}]"' if isinstance(
470-
opt, FLAG_OPTION) else '{nargs}{options}"[{help}]:{dest}:{pattern}"').format(
471-
nargs=('"(- :)"' if isinstance(opt, OPTION_END) else
472-
'"*"' if isinstance(opt, OPTION_MULTI) else ""),
473-
options=("{{{}}}".format(",".join(opt.option_strings))
474-
if len(opt.option_strings) > 1 else '"{}"'.format("".join(
475-
opt.option_strings))),
479+
return (
480+
(
481+
'{nargs}{options}"[{help}]"'
482+
if isinstance(opt, FLAG_OPTION)
483+
else '{nargs}{options}"[{help}]:{dest}:{pattern}"'
484+
)
485+
.format(
486+
nargs=(
487+
'"(- :)"'
488+
if isinstance(opt, OPTION_END)
489+
else '"*"'
490+
if isinstance(opt, OPTION_MULTI)
491+
else ""
492+
),
493+
options=(
494+
"{{{}}}".format(",".join(opt.option_strings))
495+
if len(opt.option_strings) > 1
496+
else '"{}"'.format("".join(opt.option_strings))
497+
),
476498
help=escape_zsh(opt.help or ""),
477499
dest=opt.dest,
478-
pattern=complete2pattern(opt.complete, "zsh", choice_type2fn) if hasattr(
479-
opt, "complete") else
480-
(choice_type2fn[opt.choices[0].type] if isinstance(opt.choices[0], Choice) else
481-
"({})".format(" ".join(map(str, opt.choices)))) if opt.choices else "",
482-
).replace('""', ""))
500+
pattern=complete2pattern(opt.complete, "zsh", choice_type2fn)
501+
if hasattr(opt, "complete")
502+
else (
503+
choice_type2fn[opt.choices[0].type]
504+
if isinstance(opt.choices[0], Choice)
505+
else f'({" ".join(map(str, opt.choices))})'
506+
)
507+
if opt.choices
508+
else "",
509+
)
510+
.replace('""', "")
511+
)
483512

484513
def format_positional(opt):
485514
return '"{nargs}:{help}:{pattern}"'.format(
486515
nargs={"+": "(*)", "*": "(*):"}.get(opt.nargs, ""),
487516
help=escape_zsh((opt.help or opt.dest).strip().split("\n")[0]),
488-
pattern=complete2pattern(opt.complete, "zsh", choice_type2fn) if hasattr(
489-
opt, "complete") else
490-
(choice_type2fn[opt.choices[0].type] if isinstance(opt.choices[0], Choice) else
491-
"({})".format(" ".join(map(str, opt.choices)))) if opt.choices else "",
517+
pattern=complete2pattern(opt.complete, "zsh", choice_type2fn)
518+
if hasattr(opt, "complete")
519+
else (
520+
choice_type2fn[opt.choices[0].type]
521+
if isinstance(opt.choices[0], Choice)
522+
else f'({" ".join(map(str, opt.choices))})'
523+
)
524+
if opt.choices
525+
else "",
492526
)
493527

494528
# {cmd: {"help": help, "arguments": [arguments]}}
@@ -506,11 +540,11 @@ def recurse(parser, prefix, paths=None):
506540
for sub in parser._get_positional_actions():
507541
if sub.help == SUPPRESS or not sub.choices:
508542
continue
509-
if not sub.choices or not isinstance(sub.choices, dict):
543+
if not isinstance(sub.choices, dict):
510544
# positional argument
511545
all_commands[prefix]["arguments"].append(format_positional(sub))
512546
else: # subparser
513-
log.debug("choices:{}:{}".format(prefix, sorted(sub.choices)))
547+
log.debug(f"choices:{prefix}:{sorted(sub.choices)}")
514548
public_cmds = get_public_subcommands(sub)
515549
for cmd, subparser in sub.choices.items():
516550
if cmd not in public_cmds:
@@ -528,7 +562,7 @@ def recurse(parser, prefix, paths=None):
528562
format_positional(opt) for opt in subparser._get_positional_actions()
529563
if not isinstance(opt.choices, dict) if opt.help != SUPPRESS)
530564

531-
new_pref = prefix + "_" + wordify(cmd)
565+
new_pref = f"{prefix}_{wordify(cmd)}"
532566
options = all_commands[new_pref] = {
533567
"cmd": cmd, "help": (subparser.description or "").strip().split("\n")[0],
534568
"arguments": arguments, "paths": [*paths, cmd]}
@@ -592,8 +626,11 @@ def command_option(prefix, options):
592626

593627
def command_list(prefix, options):
594628
name = " ".join([prog, *options["paths"]])
595-
commands = "\n ".join('"{}:{}"'.format(cmd, escape_zsh(opt["help"]))
596-
for cmd, opt in sorted(options["commands"].items()))
629+
commands = "\n ".join(
630+
f'"{cmd}:{escape_zsh(opt["help"])}"'
631+
for cmd, opt in sorted(options["commands"].items())
632+
)
633+
597634
return """
598635
{prefix}_commands() {{
599636
local _commands=(
@@ -656,19 +693,12 @@ def complete_tcsh(parser, root_prefix=None, preamble="", choice_functions=None):
656693
def get_specials(arg, arg_type, arg_sel):
657694
if arg.choices:
658695
choice_strs = ' '.join(map(str, arg.choices))
659-
yield "'{}/{}/({})/'".format(
660-
arg_type,
661-
arg_sel,
662-
choice_strs,
663-
)
696+
yield f"'{arg_type}/{arg_sel}/({choice_strs})/'"
664697
elif hasattr(arg, "complete"):
665-
complete_fn = complete2pattern(arg.complete, 'tcsh', choice_type2fn)
666-
if complete_fn:
667-
yield "'{}/{}/{}/'".format(
668-
arg_type,
669-
arg_sel,
670-
complete_fn,
671-
)
698+
if complete_fn := complete2pattern(
699+
arg.complete, 'tcsh', choice_type2fn
700+
):
701+
yield f"'{arg_type}/{arg_sel}/{complete_fn}/'"
672702

673703
def recurse_parser(cparser, positional_idx, requirements=None):
674704
log_prefix = '| ' * positional_idx

0 commit comments

Comments
 (0)