]> git.ipfire.org Git - thirdparty/knot-resolver.git/commitdiff
python: client: completion: use argparse.REMAINDER
authorAleš Mrázek <ales.mrazek@nic.cz>
Tue, 5 Nov 2024 09:27:49 +0000 (10:27 +0100)
committerAleš Mrázek <ales.mrazek@nic.cz>
Fri, 20 Dec 2024 21:24:22 +0000 (22:24 +0100)
Use argparse.REMAINDER to tell argparse to accept everything after argument as value for that argument.

python/knot_resolver/client/commands/completion.py

index ee46bc45727bf96d2aa815fd6eb15762964807a3..abb7b6128c8887d52d82bceba8367c8eb7622288 100644 (file)
@@ -24,10 +24,10 @@ class CompletionCommand(Command):
         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(
@@ -44,18 +44,14 @@ class CompletionCommand(Command):
             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
@@ -69,13 +65,13 @@ class CompletionCommand(Command):
         if subparsers:
             words = get_subparsers_words(subparsers._actions)  # noqa: SLF001
 
-            uargs = iter(self.comp_args)
+            uargs = iter(self.args)
             for uarg in uargs:
                 subparser = get_subparser_by_name(uarg, subparsers._actions)  # noqa: SLF001
 
                 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
@@ -86,8 +82,6 @@ class CompletionCommand(Command):
                 if uarg in words:
                     # uarg is valid (complete) arg, continue
                     continue
-                else:
-                    raise ValueError(f"unknown argument: {uarg}")
 
         # print completion words
         # based on required bash/fish shell format