2021-02-12 21:59:35 +00:00
|
|
|
"""
|
|
|
|
Demonstrates how to display a tree of files / directories with the Tree renderable.
|
|
|
|
"""
|
|
|
|
|
2021-01-03 17:14:59 +00:00
|
|
|
import os
|
2021-01-05 16:31:23 +00:00
|
|
|
import pathlib
|
2021-01-03 17:14:59 +00:00
|
|
|
import sys
|
|
|
|
|
|
|
|
from rich import print
|
2021-01-05 16:31:23 +00:00
|
|
|
from rich.filesize import decimal
|
|
|
|
from rich.markup import escape
|
2021-01-03 17:14:59 +00:00
|
|
|
from rich.text import Text
|
|
|
|
from rich.tree import Tree
|
|
|
|
|
|
|
|
|
2021-01-08 21:13:10 +00:00
|
|
|
def walk_directory(directory: pathlib.Path, tree: Tree) -> None:
|
|
|
|
"""Recursively build a Tree with directory contents."""
|
|
|
|
# Sort dirs first then by filename
|
2021-01-05 16:31:23 +00:00
|
|
|
paths = sorted(
|
|
|
|
pathlib.Path(directory).iterdir(),
|
2021-01-07 21:38:57 +00:00
|
|
|
key=lambda path: (path.is_file(), path.name.lower()),
|
2021-01-05 16:31:23 +00:00
|
|
|
)
|
|
|
|
for path in paths:
|
2021-01-08 21:13:10 +00:00
|
|
|
# Remove hidden files
|
2021-01-05 16:31:23 +00:00
|
|
|
if path.name.startswith("."):
|
|
|
|
continue
|
|
|
|
if path.is_dir():
|
2021-01-07 16:56:57 +00:00
|
|
|
style = "dim" if path.name.startswith("__") else ""
|
2021-01-05 16:31:23 +00:00
|
|
|
branch = tree.add(
|
2021-01-07 16:56:57 +00:00
|
|
|
f"[bold magenta]:open_file_folder: [link file://{path}]{escape(path.name)}",
|
2021-01-05 16:31:23 +00:00
|
|
|
style=style,
|
|
|
|
guide_style=style,
|
|
|
|
)
|
2021-01-03 17:14:59 +00:00
|
|
|
walk_directory(path, branch)
|
|
|
|
else:
|
2021-01-05 16:31:23 +00:00
|
|
|
text_filename = Text(path.name, "green")
|
|
|
|
text_filename.highlight_regex(r"\..*$", "bold red")
|
2021-01-08 21:13:10 +00:00
|
|
|
text_filename.stylize(f"link file://{path}")
|
2021-01-05 16:31:23 +00:00
|
|
|
file_size = path.stat().st_size
|
|
|
|
text_filename.append(f" ({decimal(file_size)})", "blue")
|
2021-01-08 21:13:10 +00:00
|
|
|
icon = "🐍 " if path.suffix == ".py" else "📄 "
|
|
|
|
tree.add(Text(icon) + text_filename)
|
2021-01-03 17:14:59 +00:00
|
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
directory = os.path.abspath(sys.argv[1])
|
|
|
|
except IndexError:
|
|
|
|
print("[b]Usage:[/] python tree.py <DIRECTORY>")
|
|
|
|
else:
|
2021-01-07 16:56:57 +00:00
|
|
|
tree = Tree(
|
|
|
|
f":open_file_folder: [link file://{directory}]{directory}",
|
|
|
|
guide_style="bold bright_blue",
|
|
|
|
)
|
2021-01-08 21:14:58 +00:00
|
|
|
walk_directory(pathlib.Path(directory), tree)
|
2021-01-07 16:56:57 +00:00
|
|
|
print(tree)
|