diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-05-14 20:18:28 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-05-14 20:18:28 +0000 |
commit | f8363b456f1ab31ee56abad579b215af195093d5 (patch) | |
tree | b1500c675c2e0a55fb75721a854e1510acf7c862 /examples/tree.py | |
parent | Initial commit. (diff) | |
download | rich-upstream.tar.xz rich-upstream.zip |
Adding upstream version 9.11.0.upstream/9.11.0upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to '')
-rw-r--r-- | examples/tree.py | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/examples/tree.py b/examples/tree.py new file mode 100644 index 0000000..9927719 --- /dev/null +++ b/examples/tree.py @@ -0,0 +1,55 @@ +""" +Demonstrates how to display a tree of files / directories with the Tree renderable. +""" + +import os +import pathlib +import sys + +from rich import print +from rich.filesize import decimal +from rich.markup import escape +from rich.text import Text +from rich.tree import Tree + + +def walk_directory(directory: pathlib.Path, tree: Tree) -> None: + """Recursively build a Tree with directory contents.""" + # Sort dirs first then by filename + paths = sorted( + pathlib.Path(directory).iterdir(), + key=lambda path: (path.is_file(), path.name.lower()), + ) + for path in paths: + # Remove hidden files + if path.name.startswith("."): + continue + if path.is_dir(): + style = "dim" if path.name.startswith("__") else "" + branch = tree.add( + f"[bold magenta]:open_file_folder: [link file://{path}]{escape(path.name)}", + style=style, + guide_style=style, + ) + walk_directory(path, branch) + else: + text_filename = Text(path.name, "green") + text_filename.highlight_regex(r"\..*$", "bold red") + text_filename.stylize(f"link file://{path}") + file_size = path.stat().st_size + text_filename.append(f" ({decimal(file_size)})", "blue") + icon = "🐍 " if path.suffix == ".py" else "📄 " + tree.add(Text(icon) + text_filename) + + +try: + directory = os.path.abspath(sys.argv[1]) +except IndexError: + print("[b]Usage:[/] python tree.py <DIRECTORY>") +else: + tree = Tree( + f":open_file_folder: [link file://{directory}]{directory}", + guide_style="bold bright_blue", + ) + walk_directory(pathlib.Path(directory), tree) + print(tree) |