| 1 |
""" |
| 2 |
Demonstrates how to display a tree of files / directories with the Tree renderable. |
| 3 |
""" |
| 4 |
|
| 5 |
import os |
| 6 |
import pathlib |
| 7 |
import sys |
| 8 |
|
| 9 |
from rich import print |
| 10 |
from rich.filesize import decimal |
| 11 |
from rich.markup import escape |
| 12 |
from rich.text import Text |
| 13 |
from rich.tree import Tree |
| 14 |
|
| 15 |
|
| 16 |
def walk_directory(directory: pathlib.Path, tree: Tree) -> None: |
| 17 |
"""Recursively build a Tree with directory contents.""" |
| 18 |
# Sort dirs first then by filename |
| 19 |
paths = sorted( |
| 20 |
pathlib.Path(directory).iterdir(), |
| 21 |
key=lambda path: (path.is_file(), path.name.lower()), |
| 22 |
) |
| 23 |
for path in paths: |
| 24 |
# Remove hidden files |
| 25 |
if path.name.startswith("."): |
| 26 |
continue |
| 27 |
if path.is_dir(): |
| 28 |
style = "dim" if path.name.startswith("__") else "" |
| 29 |
branch = tree.add( |
| 30 |
f"[bold magenta]:open_file_folder: [link file://{path}]{escape(path.name)}", |
| 31 |
style=style, |
| 32 |
guide_style=style, |
| 33 |
) |
| 34 |
walk_directory(path, branch) |
| 35 |
else: |
| 36 |
text_filename = Text(path.name, "green") |
| 37 |
text_filename.highlight_regex(r"\..*$", "bold red") |
| 38 |
text_filename.stylize(f"link file://{path}") |
| 39 |
file_size = path.stat().st_size |
| 40 |
text_filename.append(f" ({decimal(file_size)})", "blue") |
| 41 |
icon = "🐍 " if path.suffix == ".py" else "📄 " |
| 42 |
tree.add(Text(icon) + text_filename) |
| 43 |
|
| 44 |
|
| 45 |
try: |
| 46 |
directory = os.path.abspath(sys.argv[1]) |
| 47 |
except IndexError: |
| 48 |
print("[b]Usage:[/] python tree.py <DIRECTORY>") |
| 49 |
else: |
| 50 |
tree = Tree( |
| 51 |
f":open_file_folder: [link file://{directory}]{directory}", |
| 52 |
guide_style="bold bright_blue", |
| 53 |
) |
| 54 |
walk_directory(pathlib.Path(directory), tree) |
| 55 |
print(tree) |