Recursively build a Tree with directory contents.
(directory: pathlib.Path, tree: 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: |