7
@Desc : Implement the same functionality as the `tree` command.
14
+-- mmdc_playwright.py
17
| +-- __init__.cpython-39.pyc
18
| +-- redis.cpython-39.pyc
19
| +-- singleton.cpython-39.pyc
20
| +-- embedding.cpython-39.pyc
21
| +-- make_sk_kernel.cpython-39.pyc
22
| +-- file_repository.cpython-39.pyc
28
from __future__ import annotations
31
from pathlib import Path
32
from typing import Callable, Dict, List
34
from gitignore_parser import parse_gitignore
37
def tree(root: str | Path, gitignore: str | Path = None, run_command: bool = False) -> str:
39
Recursively traverses the directory structure and prints it out in a tree-like format.
42
root (str or Path): The root directory from which to start traversing.
43
gitignore (str or Path): The filename of gitignore file.
44
run_command (bool): Whether to execute `tree` command. Execute the `tree` command and return the result if True,
45
otherwise execute python code instead.
48
str: A string representation of the directory tree.
56
+-- mmdc_playwright.py
58
| +-- __init__.cpython-39.pyc
59
| +-- redis.cpython-39.pyc
60
| +-- singleton.cpython-39.pyc
61
+-- parse_docstring.py
63
>>> tree(".", gitignore="../../.gitignore")
68
+-- mmdc_playwright.py
69
+-- parse_docstring.py
71
>>> tree(".", gitignore="../../.gitignore", run_command=True)
76
├── mmdc_playwright.py
77
└── parse_docstring.py
81
root = Path(root).resolve()
83
return _execute_tree(root, gitignore)
85
git_ignore_rules = parse_gitignore(gitignore) if gitignore else None
86
dir_ = {root.name: _list_children(root=root, git_ignore_rules=git_ignore_rules)}
91
def _list_children(root: Path, git_ignore_rules: Callable) -> Dict[str, Dict]:
93
for i in root.iterdir():
94
if git_ignore_rules and git_ignore_rules(str(i)):
100
dir_[i.name] = _list_children(root=i, git_ignore_rules=git_ignore_rules)
101
except (FileNotFoundError, PermissionError, OSError):
106
def _print_tree(dir_: Dict[str:Dict]) -> List[str]:
108
for name, children in dir_.items():
112
lines = _print_tree(children)
113
for j, v in enumerate(lines):
114
if v[0] not in ["+", " ", "|"]:
123
def _add_line(rows: List[str]) -> List[str]:
124
for i in range(len(rows) - 1, -1, -1):
128
rows[i] = "|" + v[1:]
132
def _execute_tree(root: Path, gitignore: str | Path) -> str:
133
args = ["--gitfile", str(gitignore)] if gitignore else []
135
result = subprocess.run(["tree"] + args + [str(root)], capture_output=True, text=True, check=True)
136
if result.returncode != 0:
137
raise ValueError(f"tree exits with code {result.returncode}")
139
except subprocess.CalledProcessError as e: