Skip to content

Commit

Permalink
python: client: completion: use argparse.REMAINDER
Browse files Browse the repository at this point in the history
Use argparse.REMAINDER to tell argparse to accept everything after argument as value for that argument.
  • Loading branch information
alesmrazek committed Nov 5, 2024
1 parent 81adcc7 commit d62d310
Showing 1 changed file with 11 additions and 12 deletions.
23 changes: 11 additions & 12 deletions python/knot_resolver/client/commands/completion.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ def __init__(self, namespace: argparse.Namespace) -> None:
super().__init__(namespace)
self.shell: Shells = namespace.shell
self.space = namespace.space
self.comp_args: List[str] = namespace.comp_args
self.args: List[str] = namespace.args

if self.space:
self.comp_args.append("")
self.args.append("")

@staticmethod
def register_args_subparser(
Expand All @@ -44,18 +44,19 @@ def register_args_subparser(
action="store_true",
default=False,
)
completion.add_argument(
"comp_args",
type=str,
help="arguments to complete",
nargs="*",
)

shells_dest = "shell"
shells = completion.add_mutually_exclusive_group()
shells.add_argument("--bash", action="store_const", dest=shells_dest, const=Shells.BASH, default=Shells.BASH)
shells.add_argument("--fish", action="store_const", dest=shells_dest, const=Shells.FISH)

completion.add_argument(
"--args",
help="arguments to complete",
nargs=argparse.REMAINDER,
default=[]
)

return completion, CompletionCommand

@staticmethod
Expand All @@ -69,13 +70,13 @@ def run(self, args: CommandArgs) -> None:
if subparsers:
words = get_subparsers_words(subparsers._actions)

uargs = iter(self.comp_args)
uargs = iter(self.args)
for uarg in uargs:
subparser = get_subparser_by_name(uarg, subparsers._actions) # pylint: disable=W0212

if subparser:
cmd: Command = get_subparser_command(subparser)
subparser_args = self.comp_args[self.comp_args.index(uarg) + 1 :]
subparser_args = self.args[self.args.index(uarg) + 1 :]
if subparser_args or self.space:
words = cmd.completion(subparser_args, subparser)
break
Expand All @@ -86,8 +87,6 @@ def run(self, args: CommandArgs) -> None:
elif uarg in words:
# uarg is valid arg, continue
continue
else:
raise ValueError(f"unknown argument: {uarg}")

# print completion words
# based on required bash/fish shell format
Expand Down

0 comments on commit d62d310

Please sign in to comment.