Coverage for src / file_tree / app.py: 91%
112 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-02-27 12:12 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-02-27 12:12 +0000
1"""
2Set up and runs the textual app for some FileTree.
4It is not recommended to run any of the functions in this module.
5Instead load a :class:`FileTree <file_tree.file_tree.FileTree>` and
6then run :meth:`FileTree.run_app <file_tree.file_tree.FileTree.run_app>` and
7"""
9import itertools
10from argparse import ArgumentParser
11from functools import lru_cache
13try:
14 from rich.style import Style
15 from rich.text import Text
16 from textual.app import App, ComposeResult
17 from textual.binding import Binding
18 from textual.containers import Horizontal, Vertical
19 from textual.message import Message
20 from textual.widgets import DataTable, Footer, Header, Static, Tree
21 from textual.widgets.tree import TreeNode
22except ImportError:
23 raise ImportError(
24 "Running the file-tree app requires rich and textual to be installed. Please install these using `pip/conda install textual`."
25 )
27from .file_tree import FileTree, Template, is_missing
30class TemplateSelect(Message, bubble=True):
31 """Message sent when a template in the sidebar gets selected."""
33 def __init__(self, sender, template: Template):
34 """Create template selector."""
35 self.template = template
36 super().__init__(sender)
39class TemplateTreeControl(Tree):
40 """Sidebar containing all template definitions in FileTree."""
42 current_node = None
43 BINDINGS = [
44 Binding("space", "toggle_node", "Collapse/Expand Node", show=True),
45 Binding("up", "cursor_up", "Move Up", show=True),
46 Binding("down", "cursor_down", "Move Down", show=True),
47 ]
49 def __init__(self, file_tree: FileTree, parent_app, name: str = None):
50 """
51 Create a new template sidebar based on given FileTree.
53 Args:
54 file_tree: FileTree to interact with
55 parent_app: parent app to send message to update the template
56 name: name of the sidebar within textual
57 """
58 self.file_tree = file_tree
59 super().__init__("-", name=name)
60 self.show_root = False
61 self.find_children(self.root, self.file_tree.get_template(""))
62 self.root.expand_all()
63 self.parent_app = parent_app
64 self.select_node(self.get_node_at_line(0))
66 def on_mount(
67 self,
68 ):
69 """Focus on tree when app is loaded."""
70 self.focus()
72 def find_children(self, parent_node: TreeNode, template: Template):
73 """
74 Find all the children of a template and add them to the node.
76 Calls itself recursively.
77 """
78 all_children = template.children(self.file_tree._templates.values())
79 if len(all_children) == 0:
80 parent_node.add_leaf(template.unique_part, template)
81 else:
82 this_node = parent_node.add(template.unique_part, template)
83 children = set()
84 for child in all_children:
85 if child not in children:
86 self.find_children(this_node, child)
87 children.add(child)
89 def render_label(self, node: TreeNode[Template], base_style, style):
90 """Render the label for a template node in the tree."""
91 if node.data is None:
92 return node.label
93 label = _render_node_helper(self.file_tree, node).copy()
94 if node is self.cursor_node:
95 label.stylize("reverse")
96 if not node.is_expanded and len(node.children) > 0:
97 label = Text("📁 ") + label
98 return label
100 def on_tree_node_highlighted(self):
101 """Update tempalte in parent app when a node is highlighted."""
102 if self.current_node is not self.cursor_node:
103 self.current_node = self.cursor_node
104 self.parent_app.update_template(self.current_node.data)
107@lru_cache(None)
108def _render_node_helper(tree: FileTree, node: TreeNode[Template]):
109 meta = {
110 "@click": f"click_label({node.id})",
111 "tree_node": node.id,
112 }
113 paths = node.data.format_mult(
114 tree.placeholders, filter=True, glob=True
115 ).data.flatten()
116 existing = [p for p in paths if p != ""]
117 color = "blue" if len(existing) == len(paths) else "yellow"
118 if len(existing) == 0:
119 color = "red"
120 res = node.data.rich_line(tree._iter_templates)
121 res.append(" ")
122 res.append(f"[{len(existing)}/{len(paths)}]", style=color)
123 res.apply_meta(meta)
124 return res
127class FileTreeViewer(App):
128 """FileTree viewer app."""
130 TITLE = "FileTree viewer"
131 CSS_PATH = "css/app.css"
133 def __init__(self, file_tree: FileTree):
134 """Create a new FileTree viewer app."""
135 self.file_tree = file_tree.fill().update_glob(
136 file_tree.template_keys(only_leaves=True)
137 )
138 super().__init__()
140 def compose(self) -> ComposeResult:
141 """Compose the app layout."""
142 self.table = TemplateTable(self.file_tree)
143 controller = TemplateTreeControl(self.file_tree, self)
144 self.template_keys = Static()
145 yield Header()
146 yield Horizontal(
147 controller,
148 Vertical(
149 self.template_keys,
150 self.table,
151 ),
152 )
153 yield Footer()
155 async def handle_template_select(self, message: TemplateSelect):
156 """User has selected a template."""
157 self.update_template(message.template)
159 def update_template(self, template: Template):
160 """Update the template keys and table based on the selected template."""
161 self.app.sub_title = template.as_string
162 keys = sorted(
163 [
164 key
165 for (key, value) in self.file_tree._templates.items()
166 if value == template
167 ]
168 )
169 if len(keys) == 0:
170 self.template_keys.update("No keys found for this template.")
171 elif keys == [""]:
172 self.template_keys.update(
173 "Please select a template to see its possible values.",
174 )
175 else:
176 self.template_keys.update(f"Keys: {', '.join(keys)}")
177 self.table.update_template(template)
180class TemplateTable(DataTable):
181 """
182 Table showing all possible placeholder values for a template.
184 Any rows that do not exist in the file system are shaded red.
185 """
187 def __init__(self, file_tree: FileTree):
188 """Create new renderer for template."""
189 self.file_tree = file_tree
190 super().__init__(fixed_rows=1, zebra_stripes=True, cursor_type="none")
192 def update_template(self, template: Template):
193 """Update the table to show the values for a new template."""
194 self.clear(columns=True)
195 xr = template.format_mult(self.file_tree.placeholders, filter=True, glob=True)
196 coords = sorted(xr.coords.keys())
197 self.add_columns(*coords)
198 for values in itertools.product(*[xr.coords[c].data for c in coords]):
199 path = xr.sel(**{c: v for c, v in zip(coords, values)}).item()
200 style = Style(bgcolor=None if path != "" else "red")
201 cleaned_values = ["<MISSING>" if is_missing(v) else v for v in values]
202 self.add_row(*[Text(v, style) for v in cleaned_values])
205def run():
206 """Start CLI interface to app."""
207 parser = ArgumentParser(
208 description="Interactive terminal-based interface with file-trees"
209 )
210 parser.add_argument("file_tree", help="Which file-tree to visualise")
211 parser.add_argument("-d", "--directory", default=".", help="top-level directory")
212 args = parser.parse_args()
213 FileTree.read(args.file_tree, args.directory).run_app()