diff libervia/cli/cmd_pubsub.py @ 4394:e28cd3454c60

cli (pubsub): List support first draft + doc: Basic support for listing hierarchy of nodes with pubsub extended discovery. Nodes are displayed as a tree, depth can be specified. rel 463
author Goffi <goffi@goffi.org>
date Sun, 31 Aug 2025 12:34:37 +0200
parents 0d7bb4df2343
children
line wrap: on
line diff
--- a/libervia/cli/cmd_pubsub.py	Sun Aug 31 12:34:37 2025 +0200
+++ b/libervia/cli/cmd_pubsub.py	Sun Aug 31 12:34:37 2025 +0200
@@ -26,6 +26,7 @@
 import asyncio
 import json
 from . import base
+from rich.tree import Tree
 from libervia.backend.core.i18n import _
 from libervia.backend.core import exceptions
 from libervia.cli.constants import Const as C
@@ -1566,6 +1567,63 @@
             self.host.quit(C.EXIT_OK)
 
 
+class List(base.CommandBase):
+
+    def __init__(self, host):
+        extra_outputs = {"default": self.default_output}
+        base.CommandBase.__init__(
+            self,
+            host,
+            "list",
+            use_pubsub=True,
+            use_output=C.OUTPUT_COMPLEX,
+            extra_outputs=extra_outputs,
+            pubsub_flags={},
+            help=_("list nodes and items"),
+        )
+
+    def add_parser_options(self):
+        self.parser.add_argument(
+            "-d",
+            "--depth",
+            type=int,
+            default=0,
+            help=_("recursion depth level (DEFAULT: 0)"),
+        )
+
+    async def start(self):
+        options = {
+            "depth": self.args.depth
+        }
+        try:
+            result_s = await self.host.bridge.ps_disco_get(
+                self.args.service,
+                self.args.node,
+                data_format.serialise(options),
+                self.profile,
+            )
+        except Exception as e:
+            self.disp(f"Can't list: {e}.", error=True)
+            self.host.quit(C.EXIT_BRIDGE_ERRBACK)
+        else:
+            result = data_format.deserialise(result_s, type_check=list)
+            await self.output(result)
+            self.host.quit(C.EXIT_OK)
+
+    def recursive_tree(self, item_data: dict) -> Tree:
+        node_tree = Tree(item_data["name"])
+        children = item_data.get("children", [])
+        for child in children:
+            node_tree.add(self.recursive_tree(child))
+        return node_tree
+
+
+    def default_output(self, data: list) -> None:
+        """Output the node as a tree view."""
+        for item in data:
+            self.console.print(self.recursive_tree(item))
+
+
 class Subscribe(base.CommandBase):
     def __init__(self, host):
         base.CommandBase.__init__(
@@ -3064,6 +3122,7 @@
         Delete,
         Edit,
         Rename,
+        List,
         Subscribe,
         Unsubscribe,
         Subscriptions,