#!/usr/bin/env python3 """ Codebase Visualizer - 生成交互式代码库目录树 HTML 用法: python visualize.py [目标目录] [--max-depth N] [--exclude pattern1,pattern2] 示例: python visualize.py . python visualize.py /path/to/project --max-depth 4 python visualize.py . --exclude __pycache__,dist,.git 生成 codebase-map.html 并在浏览器中打开。 """ import os import sys import json import webbrowser from pathlib import Path from collections import defaultdict # 默认忽略的目录和文件 DEFAULT_EXCLUDES = { ".git", ".svn", ".hg", "node_modules", "__pycache__", ".pytest_cache", ".venv", "venv", "env", "dist", "build", ".next", ".nuxt", ".DS_Store", "Thumbs.db", ".claude", } # 文件类型 → 颜色映射 FILE_COLORS = { ".py": "#3572A5", ".js": "#F7DF1E", ".ts": "#3178C6", ".tsx": "#3178C6", ".jsx": "#F7DF1E", ".html": "#E34F26", ".css": "#1572B6", ".json": "#292929", ".md": "#083FA1", ".yaml": "#CB171E", ".yml": "#CB171E", ".sh": "#89E051", ".go": "#00ADD8", ".rs": "#DEA584", ".java": "#B07219", ".rb": "#CC342D", ".php": "#4F5D95", ".sql": "#E38C00", ".toml": "#9C4121", } def scan_directory(root_path, max_depth=6, excludes=None): """扫描目录,构建树形结构数据。""" if excludes is None: excludes = DEFAULT_EXCLUDES root = Path(root_path).resolve() tree = {"name": root.name, "type": "directory", "children": [], "path": "."} stats = defaultdict(int) def _scan(current_path, node, depth): if depth > max_depth: return try: entries = sorted(current_path.iterdir(), key=lambda e: (not e.is_dir(), e.name.lower())) except PermissionError: return for entry in entries: if entry.name in excludes: continue rel_path = str(entry.relative_to(root)) if entry.is_dir(): child = {"name": entry.name, "type": "directory", "children": [], "path": rel_path} _scan(entry, child, depth + 1) if child["children"]: # 只保留非空目录 node["children"].append(child) elif entry.is_file(): ext = entry.suffix.lower() size = entry.stat().st_size stats[ext] += 1 child = { "name": entry.name, "type": "file", "ext": ext, "size": size, "path": rel_path, } node["children"].append(child) _scan(root, tree, 0) return tree, dict(stats) def generate_html(tree_data, stats, project_name): """生成交互式 HTML 可视化页面。""" stats_json = json.dumps(dict(sorted(stats.items(), key=lambda x: -x[1])[:15]), ensure_ascii=False) tree_json = json.dumps(tree_data, ensure_ascii=False, indent=None) colors_json = json.dumps(FILE_COLORS, ensure_ascii=False) total_files = sum(stats.values()) total_types = len(stats) html = f""" {project_name} - Codebase Map

{project_name}

{total_files} files {total_types} types
""" return html def main(): target = "." max_depth = 6 excludes = set(DEFAULT_EXCLUDES) args = sys.argv[1:] i = 0 while i < len(args): if args[i] == "--max-depth" and i + 1 < len(args): max_depth = int(args[i + 1]) i += 2 elif args[i] == "--exclude" and i + 1 < len(args): for pat in args[i + 1].split(","): excludes.add(pat.strip()) i += 2 elif not args[i].startswith("-"): target = args[i] i += 1 else: i += 1 target_path = Path(target).resolve() if not target_path.is_dir(): print(f"Error: '{target}' is not a directory") sys.exit(1) project_name = target_path.name print(f"Scanning {project_name}...") tree_data, stats = scan_directory(target_path, max_depth, excludes) total = sum(stats.values()) print(f"Found {total} files across {len(stats)} types") output_file = "codebase-map.html" html = generate_html(tree_data, stats, project_name) with open(output_file, "w", encoding="utf-8") as f: f.write(html) abs_path = Path(output_file).resolve() print(f"Generated: {abs_path}") try: webbrowser.open(f"file://{abs_path}") print("Opened in browser.") except Exception: print("Could not open browser automatically. Open the file manually.") if __name__ == "__main__": main()