mcpField
D
dead-code-detector

dead-code-detector

github.com/terrylica测试与质量2149 次安装1 天前更新
代码仓库

关于 dead-code-detector

用于检测和清理 Python、TypeScript 与 Rust 项目中未使用代码的编码技能。它结合各语言分析工具,并提供误报处理及删除前验证的指导。

主要功能

  1. 01使用 vulture 分析 Python
  2. 02使用 knip 分析 TypeScript
  3. 03基于 Rust lint 检测
  4. 04误报处理指导
  5. 05删除前验证发现项

适用场景

  1. 01发布前清理代码
  2. 02降低重构维护负担
  3. 03调查包体积或编译时间
  4. 04入门时了解代码使用情况

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/terrylica/cc-skills --skill dead-code-detector

安装后在 Claude Code 中输入/dead-code-detector确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
evolution-log.md
python-workflow.md
rust-workflow.md
typescript-workflow.md

详细介绍

死代码检测器

在 Python、TypeScript 和 Rust 代码库中查找并移除未使用的代码。

自我演进技能:此技能会随着使用不断改进。如果说明有误、参数发生偏移,或需要采用变通方法,请立即修复此文件,不要拖延。仅针对真实、可复现的问题进行更新。

各语言对应的工具

语言工具检测内容
Pythonvulture v2.14+未使用的导入、函数、类、变量
TypeScriptknip v5.0+未使用的导出、依赖、文件
Rustcargo clippy + rustc lint未使用的函数、导入、dead_code 警告

为什么选择这些工具?

  • vulture:基于 AST,提供置信度评分(60-100%),支持白名单
  • knip:ts-prune 的后继工具(后者处于维护模式),支持 monorepo,可自动修复
  • cargo clippy:内置于 Rust 工具链,无需额外依赖

何时使用此技能

在以下情况下使用此技能:

  • 发布前清理代码库
  • 重构以减轻维护负担
  • 调查打包体积/编译时间问题
  • 熟悉代码库,了解哪些代码实际在使用

不适用于:代码重复(请使用 quality-tools:code-clone-assistant)


快速入门工作流

Python(vulture)
# Step 1: Install
uv pip install vulture

# Step 2: Scan with 80% confidence threshold
vulture src/ --min-confidence 80

# Step 3: Generate whitelist for false positives
vulture src/ --make-whitelist > vulture_whitelist.py

# Step 4: Re-scan with whitelist
vulture src/ vulture_whitelist.py --min-confidence 80
TypeScript(knip)
# Step 1: Install (project-local recommended)
bun add -d knip

# Step 2: Initialize config
bunx knip --init

# Step 3: Scan for dead code
bunx knip

# Step 4: Auto-fix (removes unused exports)
bunx knip --fix
Rust(cargo clippy)
# Step 1: Scan for dead code warnings
cargo clippy -- -W dead_code -W unused_imports -W unused_variables

# Step 2: For stricter enforcement
cargo clippy -- -D dead_code  # Deny (error) instead of warn

# Step 3: Auto-fix what's possible
cargo clippy --fix --allow-dirty

置信度与误报

Python(vulture)
置信度含义操作
100%确定在已分析的文件中未使用可安全移除
80-99%很可能未使用移除前进行审查
60-79%可能未使用(动态调用、框架)若有意保留,则加入白名单

常见误报(由框架调用的代码):

  • 路由处理程序/控制器方法(由 Web 框架调用)
  • 测试夹具和初始化工具(由测试运行器调用)
  • 公共 API 导出项(重新导出供使用者使用)
  • 后台任务处理程序(由任务队列/调度器调用)
  • 事件监听器/钩子(由事件系统调用)
  • 序列化回调(在编码/解码期间调用)
TypeScript(knip)

Knip 使用 TypeScript 的类型系统来提高准确性。在 knip.json 中配置:

{
  "entry": ["src/index.ts"],
  "project": ["src/**/*.ts"],
  "ignore": ["**/*.test.ts"],
  "ignoreDependencies": ["@types/*"]
}
Rust

使用属性抑制误报:

#[allow(dead_code)]  // Single item
fn intentionally_unused() {}

// Or module-wide
#![allow(dead_code)]

与 CI 集成

Python(pyproject.toml)
[tool.vulture]
min_confidence = 80
paths = ["src"]
exclude = ["*_test.py", "conftest.py"]
TypeScript(package.json)
{
  "scripts": {
    "dead-code": "knip",
    "dead-code:fix": "knip --fix"
  }
}
Rust(Cargo.toml)
[lints.rust]
dead_code = "warn"
unused_imports = "warn"

参考文档

如需详细信息,请参阅:


故障排查

问题原因解决方案
报告由框架调用的代码框架魔法机制/回调添加到白名单或排除配置中
未发现动态加载的代码不在静态入口点中配置入口点,以包含插件/扩展目录
对仅用于测试的辅助代码发出警告测试代码单独编译使用条件编译或针对测试的排除项
误报过多阈值过低提高置信度阈值或配置忽略模式
缺少仅限类型的引用仅在编译时使用大多数现代工具都能处理;请检查工具版本

多视角验证(重要)

重要:在移除任何检测到的“死代码”之前,启动并行子 Agent,从多个角度验证发现。死代码实际上可能是尚未实现的功能或未完成的集成。

分类矩阵
发现类型真正的死代码尚未实现的功能未完成的集成
未使用的可调用项没有调用方、测试或文档有 TODO/FIXME,在规范中有引用存在部分调用链
未使用的导出/公共项未在任何地方导入属于公共 API,且有文档说明在同级模块中使用
未使用的导入/包含项拼写错误,已重构移除需要副作用仅用于类型或编译时
未使用的绑定已赋值但从未读取为未来预留的占位符调试/检测代码已移除
验证工作流

运行检测工具后,启动以下并行子 Agent:

┌─────────────────────────────────────────────────────────────────┐
│                    Dead Code Findings                           │
└─────────────────────────────────────────────────────────────────┘
                              │
          ┌───────────────────┼───────────────────┐
          ▼                   ▼                   ▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Intent Agent    │ │ Integration     │ │ History Agent   │
│                 │ │ Agent           │ │                 │
│ - Check TODOs   │ │ - Trace call    │ │ - Git blame     │
│ - Search specs  │ │   chains        │ │ - Commit msgs   │
│ - Find issues   │ │ - Check exports │ │ - PR context    │
│ - Read ADRs     │ │ - Test coverage │ │ - Author intent │
└─────────────────┘ └─────────────────┘ └─────────────────┘
          │                   │                   │
          └───────────────────┼───────────────────┘
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│              AskUserQuestion: Confirm Classification            │
│  [ ] True dead code - safe to remove                            │
│  [ ] Unimplemented - create GitHub Issue to track               │
│  [ ] Incomplete - investigate integration gaps                  │
│  [ ] False positive - add to whitelist                          │
└─────────────────────────────────────────────────────────────────┘
Agent 提示词

意图 Agent(搜索计划中的用法):

Search for references to [IDENTIFIER] in:
1. TODO/FIXME/HACK comments in codebase
2. Issue tracker (open and closed issues)
3. Design documents and architecture decision records
4. README and project documentation files
Report: Was this code planned but not yet integrated?

集成 Agent(追踪执行路径):

For [IDENTIFIER], analyze:
1. All module import/include/use statements
2. Runtime module loading mechanisms (lazy loading, plugins)
3. Framework-invoked patterns (metadata attributes, config bindings, annotations)
4. Test files that may exercise this code path
Report: Is there a partial or indirect call chain?

历史 Agent(调查来源):

For [IDENTIFIER], check:
1. VCS blame/annotate - who wrote it and when
2. Commit message - what was the stated intent
3. Code review / merge request context - was it part of larger feature
4. Recent commits - was calling code removed or refactored
Report: Was this intentionally orphaned or accidentally broken?
示例:验证发现
# Step 1: Run detection tool for your language
<tool> <source-path> --confidence-threshold 80 > findings.txt

# Step 2: For each high-confidence finding, spawn validation
# (Claude Code will use Task tool with Explore agents)

示例发现:unused function 'calculate_metrics' (src/analytics.py:45)

多 Agent 调查结果:

  • 意图 Agent:“在 src/dashboard.py:12 发现 TODO——‘在此处集成 calculate_metrics’”
  • 集成 Agent:“该函数已在 tests/test_analytics.py 中导入,但测试标记为 skip/pending”
  • 历史 Agent:“在 MR #234 ‘Add analytics foundation’ 中添加——仪表盘集成已延期”

结论:不是死代码——这是一个尚未实现的功能。请创建跟踪问题。

用户确认流程

Agent 分析后,使用 AskUserQuestion 并设置 multiSelect: true:

AskUserQuestion({
  questions: [
    {
      question: "How should we handle these findings?",
      header: "Action",
      multiSelect: true,
      options: [
        {
          label: "Remove confirmed dead code",
          description: "Delete items verified as truly unused",
        },
        {
          label: "Create issues for unimplemented",
          description: "Track planned features in GitHub Issues",
        },
        {
          label: "Investigate incomplete integrations",
          description: "Spawn deeper analysis for partial implementations",
        },
        {
          label: "Update whitelist",
          description: "Add false positives to tool whitelist",
        },
      ],
    },
  ],
});
风险分类
风险级别标准操作
低置信度 100%,无任何引用,超过 6 个月自动移除并提交 VCS
中置信度 80–99%,存在一些间接引用先由 Agent 验证
高置信度低于 80%,代码较新,有测试覆盖需要人工审查
严重公共 API 表面,有文档说明,有外部依赖项绝不自动移除

来源

执行后反思

此技能完成后,在结束前进行检查:

  1. 命令是否成功? — 如果没有,请修复导致失败的指令或错误表。
  2. 参数或输出是否发生变化? — 如果底层工具的接口发生变化,请更新 Usage 示例和 Parameters 表,使之保持一致。
  3. 是否需要采用变通方法? — 如果你不得不临时变通(使用不同的标志、增加步骤),请更新此 SKILL.md,避免下次调用时再次需要相同的变通方法。

仅在问题真实存在且可复现时更新,不要基于猜测更新。

评论

支持 Markdown