#!/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"""