]> git.ipfire.org Git - thirdparty/knot-resolver.git/commitdiff
manager: client: comment incomplete completion code
authorAleš Mrázek <ales.mrazek@nic.cz>
Tue, 10 Jan 2023 18:56:06 +0000 (19:56 +0100)
committerAleš Mrázek <ales.mrazek@nic.cz>
Tue, 10 Jan 2023 18:57:14 +0000 (19:57 +0100)
manager/knot_resolver_manager/cli/cmd/completion.py
manager/knot_resolver_manager/cli/cmd/config.py
manager/knot_resolver_manager/cli/cmd/schema.py
manager/knot_resolver_manager/cli/command.py

index a769ac350939475acd0634f9f1c9dc99fd4c891b..87a9183883ebec0e48355589914f33cc8b285890 100644 (file)
@@ -2,15 +2,7 @@ import argparse
 from enum import Enum
 from typing import List, Tuple, Type
 
-from knot_resolver_manager.cli.command import (
-    Command,
-    CommandArgs,
-    CompWords,
-    parser_words,
-    register_command,
-    subparser_by_name,
-    subparser_command,
-)
+from knot_resolver_manager.cli.command import Command, CommandArgs, CompWords, register_command
 
 
 class Shells(Enum):
@@ -58,44 +50,46 @@ class CompletionCommand(Command):
     @staticmethod
     def completion(args: List[str], parser: argparse.ArgumentParser) -> CompWords:
         words: CompWords = {}
-        for action in parser._actions:
-            for opt in action.option_strings:
-                words[opt] = action.help
+        # for action in parser._actions:
+        #     for opt in action.option_strings:
+        #         words[opt] = action.help
+        # return words
         return words
 
     def run(self, args: CommandArgs) -> None:
-        subparsers = args.parser._subparsers
-        words: CompWords = {}
+        pass
+        # subparsers = args.parser._subparsers
+        # words: CompWords = {}
 
-        if subparsers:
-            words = parser_words(subparsers._actions)
+        if subparsers:
+            words = parser_words(subparsers._actions)
 
-            uargs = iter(self.comp_args)
-            for uarg in uargs:
-                subparser = subparser_by_name(uarg, subparsers._actions)  # pylint: disable=W0212
+            uargs = iter(self.comp_args)
+            for uarg in uargs:
+                subparser = subparser_by_name(uarg, subparsers._actions)  # pylint: disable=W0212
 
-                if subparser:
-                    cmd: Command = subparser_command(subparser)
-                    subparser_args = self.comp_args[self.comp_args.index(uarg) + 1 :]
-                    if subparser_args:
-                        words = cmd.completion(subparser_args, subparser)
-                    break
-                elif uarg in ["-s", "--socket"]:
-                    # if arg is socket config, skip next arg
-                    next(uargs)
-                    continue
-                elif uarg in words:
-                    # uarg is walid arg, continue
-                    continue
-                else:
-                    raise ValueError(f"unknown argument: {uarg}")
+                if subparser:
+                    cmd: Command = subparser_command(subparser)
+                    subparser_args = self.comp_args[self.comp_args.index(uarg) + 1 :]
+                    if subparser_args:
+                        words = cmd.completion(subparser_args, subparser)
+                    break
+                elif uarg in ["-s", "--socket"]:
+                    # if arg is socket config, skip next arg
+                    next(uargs)
+                    continue
+                elif uarg in words:
+                    # uarg is walid arg, continue
+                    continue
+                else:
+                    raise ValueError(f"unknown argument: {uarg}")
 
-        # print completion words
-        # based on required bash/fish shell format
-        if self.shell == Shells.BASH:
-            print(" ".join(words))
-        elif self.shell == Shells.FISH:
-            # TODO: FISH completion implementation
-            pass
-        else:
-            raise ValueError(f"unexpected value of {Shells}: {self.shell}")
+        # print completion words
+        # based on required bash/fish shell format
+        if self.shell == Shells.BASH:
+            print(" ".join(words))
+        elif self.shell == Shells.FISH:
+            # TODO: FISH completion implementation
+            pass
+        else:
+            raise ValueError(f"unexpected value of {Shells}: {self.shell}")
index 8f2dce8a3e3fa230d808bc4973544c905bdebce9..050ad313e1966f00ad08d88c8de19835c6476f58 100644 (file)
@@ -2,13 +2,12 @@ import argparse
 import json
 import sys
 from enum import Enum
-from typing import Any, Dict, List, Optional, Tuple, Type
+from typing import List, Optional, Tuple, Type
 
 import yaml
 from typing_extensions import Literal
 
-from knot_resolver_manager.cli.command import Command, CommandArgs, CompWords, parser_words, register_command
-from knot_resolver_manager.datamodel.config_schema import KresConfig
+from knot_resolver_manager.cli.command import Command, CommandArgs, CompWords, register_command
 from knot_resolver_manager.utils.modeling import try_to_parse
 from knot_resolver_manager.utils.requests import request
 
@@ -40,54 +39,54 @@ def reformat(data: str, req_format: Formats) -> str:
     return json.dumps(dict, indent=4)
 
 
-def _properties_words(props: Dict[str, Any]) -> CompWords:
-    words: CompWords = {}
-    for name, prop in props.items():
-        words[name] = prop["description"] if "description" in prop else None
-    return words
-
-
-def _path_comp_words(node: str, nodes: List[str], props: Dict[str, Any]) -> CompWords:
-    i = nodes.index(node)
-    ln = len(nodes[i:])
-
-    # if node is last in path, return all possible words on thi level
-    if ln == 1:
-        return _properties_words(props)
-    # if node is valid
-    elif node in props:
-        node_schema = props[node]
-
-        if "anyOf" in node_schema:
-            for item in node_schema["anyOf"]:
-                print(item)
-
-        elif "type" not in node_schema:
-            pass
-
-        elif node_schema["type"] == "array":
-            if ln > 2:
-                # skip index for item in array
-                return _path_comp_words(nodes[i + 2], nodes, node_schema["items"]["properties"])
-            if "enum" in node_schema["items"]:
-                print(node_schema["items"]["enum"])
-            return {"0": "first array item", "-": "last array item"}
-        elif node_schema["type"] == "object":
-            if "additionalProperties" in node_schema:
-                print(node_schema)
-            return _path_comp_words(nodes[i + 1], nodes, node_schema["properties"])
-        return {}
-
-        # arrays/lists must be handled sparately
-        if node_schema["type"] == "array":
-            if ln > 2:
-                # skip index for item in array
-                return _path_comp_words(nodes[i + 2], nodes, node_schema["items"]["properties"])
-            return {"0": "first array item", "-": "last array item"}
-        return _path_comp_words(nodes[i + 1], nodes, node_schema["properties"])
-    else:
-        # if node is not last or valid, value error
-        raise ValueError(f"unknown config path node: {node}")
+def _properties_words(props: Dict[str, Any]) -> CompWords:
+    words: CompWords = {}
+    for name, prop in props.items():
+        words[name] = prop["description"] if "description" in prop else None
+    return words
+
+
+def _path_comp_words(node: str, nodes: List[str], props: Dict[str, Any]) -> CompWords:
+    i = nodes.index(node)
+    ln = len(nodes[i:])
+
+    # if node is last in path, return all possible words on thi level
+    if ln == 1:
+        return _properties_words(props)
+    # if node is valid
+    elif node in props:
+        node_schema = props[node]
+
+        if "anyOf" in node_schema:
+            for item in node_schema["anyOf"]:
+                print(item)
+
+        elif "type" not in node_schema:
+            pass
+
+        elif node_schema["type"] == "array":
+            if ln > 2:
+                # skip index for item in array
+                return _path_comp_words(nodes[i + 2], nodes, node_schema["items"]["properties"])
+            if "enum" in node_schema["items"]:
+                print(node_schema["items"]["enum"])
+            return {"0": "first array item", "-": "last array item"}
+        elif node_schema["type"] == "object":
+            if "additionalProperties" in node_schema:
+                print(node_schema)
+            return _path_comp_words(nodes[i + 1], nodes, node_schema["properties"])
+        return {}
+
+        # arrays/lists must be handled sparately
+        if node_schema["type"] == "array":
+            if ln > 2:
+                # skip index for item in array
+                return _path_comp_words(nodes[i + 2], nodes, node_schema["items"]["properties"])
+            return {"0": "first array item", "-": "last array item"}
+        return _path_comp_words(nodes[i + 1], nodes, node_schema["properties"])
+    else:
+        # if node is not last or valid, value error
+        raise ValueError(f"unknown config path node: {node}")
 
 
 @register_command
@@ -170,20 +169,20 @@ class ConfigCommand(Command):
         return config, ConfigCommand
 
     @staticmethod
-    def completion(args: List[str], parser: argparse.ArgumentParser) -> Dict[str, Optional[str]]:
-        words = parser_words(parser._actions)  # pylint: disable=W0212
-
-        for arg in args:
-            if arg in words:
-                continue
-            elif arg.startswith("-"):
-                return words
-            elif arg == args[-1]:
-                config_path = arg[1:].split("/") if arg.startswith("/") else arg.split("/")
-                schema_props: Dict[str, Any] = KresConfig.json_schema()["properties"]
-                return _path_comp_words(config_path[0], config_path, schema_props)
-            else:
-                break
+    def completion(args: List[str], parser: argparse.ArgumentParser) -> CompWords:
+        words = parser_words(parser._actions)  # pylint: disable=W0212
+
+        for arg in args:
+            if arg in words:
+                continue
+            elif arg.startswith("-"):
+                return words
+            elif arg == args[-1]:
+                config_path = arg[1:].split("/") if arg.startswith("/") else arg.split("/")
+                schema_props: Dict[str, Any] = KresConfig.json_schema()["properties"]
+                return _path_comp_words(config_path[0], config_path, schema_props)
+            else:
+                break
         return {}
 
     def run(self, args: CommandArgs) -> None:
index a60f225c80bdda7f718b51013638074b0c508deb..9b40e8f7b73dfc357ca3cbc9a7dd20b207f88075 100644 (file)
@@ -3,7 +3,7 @@ import json
 import sys
 from typing import List, Optional, Tuple, Type
 
-from knot_resolver_manager.cli.command import Command, CommandArgs, CompWords, parser_words, register_command
+from knot_resolver_manager.cli.command import Command, CommandArgs, CompWords, register_command
 from knot_resolver_manager.datamodel.config_schema import KresConfig
 from knot_resolver_manager.utils.requests import request
 
@@ -35,7 +35,8 @@ class SchemaCommand(Command):
 
     @staticmethod
     def completion(args: List[str], parser: argparse.ArgumentParser) -> CompWords:
-        return parser_words(parser._actions)  # pylint: disable=W0212
+        return {}
+        # return parser_words(parser._actions)  # pylint: disable=W0212
 
     def run(self, args: CommandArgs) -> None:
         if self.live:
index f2278d403d633b93a4eee7ffff4897d8ce433c5e..8fe3461df5c8f3509ff655a43b40acba8e7a6649 100644 (file)
@@ -58,26 +58,26 @@ class Command(ABC):
         raise NotImplementedError()
 
 
-def parser_words(actions: List[argparse.Action]) -> CompWords:
-    words: CompWords = {}
-    for action in actions:
-        if isinstance(action, argparse._SubParsersAction):  # pylint: disable=W0212
-            for sub in action._get_subactions():  # pylint: disable=W0212
-                words[sub.dest] = sub.help
-        elif isinstance(
-            action, (argparse._StoreConstAction, argparse._StoreAction, argparse._HelpAction)  # pylint: disable=W0212
-        ):  # pylint: disable=W0212
-            for s in action.option_strings:
-                words[s] = action.help
-    return words
-
-
-def subparser_by_name(subparser_name: str, actions: List[argparse.Action]) -> Optional[argparse.ArgumentParser]:
-    for action in actions:
-        if isinstance(action, argparse._SubParsersAction) and subparser_name in action.choices:  # pylint: disable=W0212
-            return action.choices[subparser_name]
-    return None
-
-
-def subparser_command(subparser: argparse.ArgumentParser) -> Command:
-    return subparser._defaults["command"]  # pylint: disable=W0212
+def parser_words(actions: List[argparse.Action]) -> CompWords:
+    words: CompWords = {}
+    for action in actions:
+        if isinstance(action, argparse._SubParsersAction):  # pylint: disable=W0212
+            for sub in action._get_subactions():  # pylint: disable=W0212
+                words[sub.dest] = sub.help
+        elif isinstance(
+            action, (argparse._StoreConstAction, argparse._StoreAction, argparse._HelpAction)  # pylint: disable=W0212
+        ):  # pylint: disable=W0212
+            for s in action.option_strings:
+                words[s] = action.help
+    return words
+
+
+def subparser_by_name(subparser_name: str, actions: List[argparse.Action]) -> Optional[argparse.ArgumentParser]:
+    for action in actions:
+        if isinstance(action, argparse._SubParsersAction) and subparser_name in action.choices:  # pylint: disable=W0212
+            return action.choices[subparser_name]
+    return None
+
+
+def subparser_command(subparser: argparse.ArgumentParser) -> Command:
+    return subparser._defaults["command"]  # pylint: disable=W0212