|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import argparse |
| 3 | +import fnmatch |
| 4 | +import os |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | + |
| 8 | +def build_tree( |
| 9 | + path: Path, |
| 10 | + max_depth: int, |
| 11 | + ignore_patterns: list, |
| 12 | + whitelist_dirs: list, |
| 13 | + include_all: bool, |
| 14 | + root: Path, |
| 15 | + prefix: str = "", |
| 16 | +) -> str: |
| 17 | + """ |
| 18 | + Recursively build an ASCII tree up to max_depth, applying whitelist and |
| 19 | + ignore rules. |
| 20 | + """ |
| 21 | + if max_depth < 0: |
| 22 | + return "" |
| 23 | + entries = sorted( |
| 24 | + path.iterdir(), key=lambda p: (p.is_file(), p.name.lower()) |
| 25 | + ) |
| 26 | + lines = [] |
| 27 | + for i, entry in enumerate(entries): |
| 28 | + rel_path = entry.relative_to(root).as_posix() |
| 29 | + # Skip ignored patterns |
| 30 | + if any(fnmatch.fnmatch(rel_path, pat) for pat in ignore_patterns): |
| 31 | + continue |
| 32 | + # Enforce whitelist if not including all |
| 33 | + if not include_all and whitelist_dirs and not any( |
| 34 | + rel_path.startswith(w.rstrip("/")) for w in whitelist_dirs |
| 35 | + ): |
| 36 | + continue |
| 37 | + connector = "└── " if i == len(entries) - 1 else "├── " |
| 38 | + lines.append(f"{prefix}{connector}{entry.name}") |
| 39 | + # Recurse into directories |
| 40 | + if entry.is_dir(): |
| 41 | + extension = " " if i == len(entries) - 1 else "│ " |
| 42 | + subtree = build_tree( |
| 43 | + entry, |
| 44 | + max_depth - 1, |
| 45 | + ignore_patterns, |
| 46 | + whitelist_dirs, |
| 47 | + include_all, |
| 48 | + root, |
| 49 | + prefix + extension, |
| 50 | + ) |
| 51 | + if subtree: |
| 52 | + lines += subtree.splitlines() |
| 53 | + return "\n".join(lines) |
| 54 | + |
| 55 | + |
| 56 | +def detect_language(path: Path) -> str: |
| 57 | + """Map file suffix to Sphinx language.""" |
| 58 | + mapping = { |
| 59 | + ".py": "python", |
| 60 | + ".js": "javascript", |
| 61 | + ".java": "java", |
| 62 | + ".md": "markdown", |
| 63 | + ".yaml": "yaml", |
| 64 | + ".yml": "yaml", |
| 65 | + ".json": "json", |
| 66 | + ".sh": "bash", |
| 67 | + ".rst": "rst", |
| 68 | + } |
| 69 | + return mapping.get(path.suffix, "") |
| 70 | + |
| 71 | + |
| 72 | +def main(): |
| 73 | + p = argparse.ArgumentParser( |
| 74 | + description="Auto-generate a .rst with tree + literalinclude blocks" |
| 75 | + ) |
| 76 | + p.add_argument( |
| 77 | + "-p", |
| 78 | + "--project-root", |
| 79 | + type=Path, |
| 80 | + default=Path("."), |
| 81 | + help="Path to your project directory", |
| 82 | + ) |
| 83 | + p.add_argument( |
| 84 | + "-d", |
| 85 | + "--depth", |
| 86 | + type=int, |
| 87 | + default=10, |
| 88 | + help="How many levels deep to print in the tree", |
| 89 | + ) |
| 90 | + p.add_argument( |
| 91 | + "-o", |
| 92 | + "--output", |
| 93 | + type=Path, |
| 94 | + default=Path("docs/source_tree.rst"), |
| 95 | + help="Where to write the generated .rst", |
| 96 | + ) |
| 97 | + p.add_argument( |
| 98 | + "-e", |
| 99 | + "--ext", |
| 100 | + nargs="+", |
| 101 | + default=[".py", ".md", ".js", ".rst"], |
| 102 | + help="Which file extensions to include via literalinclude", |
| 103 | + ) |
| 104 | + p.add_argument( |
| 105 | + "-i", |
| 106 | + "--ignore", |
| 107 | + nargs="+", |
| 108 | + default=[ |
| 109 | + "__pycache__", |
| 110 | + "*.pyc", |
| 111 | + "*.py,cover", |
| 112 | + ".ipynb_checkpoints", |
| 113 | + "*.ipynb", |
| 114 | + "media", |
| 115 | + "static", |
| 116 | + "*.sqlite3", |
| 117 | + ], |
| 118 | + help="Ignore files or dirs matching these glob patterns (relative to " |
| 119 | + "project root)", |
| 120 | + ) |
| 121 | + p.add_argument( |
| 122 | + "-w", |
| 123 | + "--whitelist", |
| 124 | + nargs="+", |
| 125 | + default=["src", "docs", "examples", "scripts"], |
| 126 | + help="Directories (relative to project root) to include " |
| 127 | + "unless --include-all is given", |
| 128 | + ) |
| 129 | + p.add_argument( |
| 130 | + "--include-all", |
| 131 | + action="store_true", |
| 132 | + help="Include all files regardless of whitelist", |
| 133 | + ) |
| 134 | + args = p.parse_args() |
| 135 | + |
| 136 | + root = args.project_root.resolve() |
| 137 | + ignore_patterns = args.ignore |
| 138 | + whitelist_dirs = args.whitelist |
| 139 | + include_all = args.include_all |
| 140 | + output = args.output.resolve() |
| 141 | + output_dir = output.parent.resolve() |
| 142 | + |
| 143 | + # Header + tree |
| 144 | + header = f"""Project source-tree |
| 145 | +=================== |
| 146 | +
|
| 147 | +Below is the layout of our project (to {args.depth} levels), followed by |
| 148 | +the contents of each key file. |
| 149 | +
|
| 150 | +.. code-block:: bash |
| 151 | + :caption: Project directory layout |
| 152 | +
|
| 153 | + {root.name}/ |
| 154 | +""" |
| 155 | + tree = build_tree( |
| 156 | + root, |
| 157 | + args.depth, |
| 158 | + ignore_patterns, |
| 159 | + whitelist_dirs, |
| 160 | + include_all, |
| 161 | + root, |
| 162 | + prefix=" ", |
| 163 | + ) |
| 164 | + out = [header, tree, ""] |
| 165 | + |
| 166 | + # Walk and collect files |
| 167 | + for filepath in sorted(root.rglob("*")): |
| 168 | + if not filepath.is_file() or filepath.suffix not in args.ext: |
| 169 | + continue |
| 170 | + rel_path = filepath.relative_to(root).as_posix() |
| 171 | + # Skip ignored |
| 172 | + if any(fnmatch.fnmatch(rel_path, pat) for pat in ignore_patterns): |
| 173 | + continue |
| 174 | + # Enforce whitelist |
| 175 | + if ( |
| 176 | + not include_all |
| 177 | + and whitelist_dirs |
| 178 | + and not any( |
| 179 | + rel_path.startswith(w.rstrip("/")) for w in whitelist_dirs) |
| 180 | + ): |
| 181 | + continue |
| 182 | + |
| 183 | + # Compute include path relative to output_dir |
| 184 | + include_path = os.path.relpath(filepath, output_dir).replace( |
| 185 | + os.sep, "/" |
| 186 | + ) |
| 187 | + title = rel_path |
| 188 | + underline = "-" * len(title) |
| 189 | + lang = detect_language(filepath) |
| 190 | + out += [ |
| 191 | + title, |
| 192 | + underline, |
| 193 | + "", |
| 194 | + f".. literalinclude:: {include_path}", |
| 195 | + f" :language: {lang}" if lang else "", |
| 196 | + f" :caption: {rel_path}", |
| 197 | + # " :linenos:", |
| 198 | + "", |
| 199 | + ] |
| 200 | + |
| 201 | + # Write output |
| 202 | + args.output.write_text("\n".join(line for line in out if line is not None)) |
| 203 | + print(f"Wrote {args.output}") |
| 204 | + |
| 205 | + |
| 206 | +if __name__ == "__main__": |
| 207 | + main() |
0 commit comments