用途
CodeMapper(cm)是一款基于 tree-sitter AST 解析的快速代码分析工具,无需数据库即可提供即时的代码分析能力。它可以在毫秒级内获取项目结构、查找符号、追踪调用图并分析依赖关系。
支持的语言包括:Python、JavaScript、TypeScript、Rust、Java、Go、C、Markdown。
主要能力
CodeMapper 适用于以下场景:
- 探索不熟悉的代码库(获取概览、查找结构)
- 查找符号定义与用法(函数、类、方法)
- 理解调用图(谁调用了什么、调用路径)
- 检查测试覆盖(找出未测试的代码)
- 在符号级别分析 git 变更(破坏性变更)
- 重构前的影响分析(理解依赖关系)
不适用于:
- 全文搜索(应使用 ripgrep/grep)
- 运行时分析(应使用 profiler)
- 代码执行(应使用解释器/编译器)
使用方式
快速开始:
# 步骤 1:获取概览
cm stats .
# 步骤 2:查看文件结构(为 LLM 分析时始终使用 --format ai)
cm map . --level 2 --format ai
# 步骤 3:查找特定代码
cm query <symbol> --format ai
# 步骤 4:深入查看某个文件
cm inspect ./path/to/file --format ai
重要提示:为 LLM 上下文分析代码时,始终使用 --format ai。这是最节省 token 的格式(减少 60-80%)。
常用命令:
| 任务 | 命令 |
|---|---|
| 项目概览 | cm stats . |
| 文件结构 | cm map . --level 2 --format ai |
| 查找符号 | cm query <name> --format ai |
| 显示实现 | cm query <name> --show-body --format ai |
| 谁调用了它? | cm callers <symbol> --format ai |
| 它调用了什么? | cm callees <symbol> --format ai |
| 调用路径 A→B | cm trace <from> <to> --format ai |
| 查找测试 | cm tests <symbol> --format ai |
| 未测试代码 | cm untested . --format ai |
| 破坏性变更 | cm since <commit> --breaking --format ai |
完整命令参考请阅读 references/command-reference.md。
关键工作流
探索未知代码:
cm stats .
cm map . --level 2 --format ai
cm query <symbol> --format ai
重构前:
cm callers <function> --format ai # 谁依赖它?
cm tests <function> --format ai # 它被测试了吗?
cm callees <function> --format ai # 它依赖什么?
代码健康检查:
cm untested . --format ai # 什么没被测试?
cm since <last_release> --breaking --format ai # 有破坏性变更吗?
详细工作流请阅读 references/workflows.md。
常见错误
- 忘记
--format ai:
# 错误(冗长、消耗大量 token)
cm map . --level 2
# 正确(紧凑、为 LLM 优化)
cm map . --level 2 --format ai
- 使用 grep 处理调用图:
# 错误(遗漏间接调用、误报)
grep -r "process_payment"
# 正确(基于 AST 的准确调用图)
cm callers process_payment --format ai
- 跳过 stats/map:
# 错误(没有上下文就直接查询)
cm query something --format ai
# 正确(先理解结构)
cm stats .
cm map . --level 2 --format ai
cm query something --format ai
更多示例请阅读 references/common-mistakes.md。
最佳实践
- 始终从概览开始:先
cm stats .,再cm map . --level 2 --format ai - 为 LLM 始终使用
--format ai:token 效率很重要 - 优先使用模糊搜索:默认模糊匹配更宽容
- 重构前先检查:修改前运行
cm callers和cm tests - 使用正确的工具:结构/调用用 CodeMapper,文本搜索用 ripgrep
故障排除
找不到符号?
- 检查文件扩展名:
cm stats .显示已索引的内容 - 尝试模糊搜索(默认)与
--exact
查询缓慢?
- 首次运行会构建缓存(约 10 秒)
- 后续运行使用缓存(约 0.5 秒)
Git 命令失败?
- 必须在 git 仓库中才能使用:diff、since、blame、history
详细故障排除请阅读 references/troubleshooting.md。
参考文档
references/command-reference.md- 完整命令与标志参考references/workflows.md- 常见任务的详细工作流模式references/common-mistakes.md- 应避免的扩展示例references/troubleshooting.md- 全面的故障排除指南references/integration-examples.md- CI/CD、文档、代码审查模式
性能
- 小型仓库(< 100 文件):< 20ms 即时
- 中型仓库(100-1000):约 0.5s(使用缓存)
- 大型仓库(1000+):自动启用快速模式
- 缓存位置:项目根目录下的
.codemapper/(自动管理)
限制
CodeMapper 不适用于全文搜索、运行时分析或代码执行。Git 相关命令(diff、since、blame、history)必须在 git 仓库中运行。首次运行需要构建缓存,可能耗时约 10 秒。