dead-code-removal
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDead Code Removal
未使用代码移除
This skill safely identifies and removes unused code across multiple programming languages. It includes comprehensive safety checks to prevent removing code that's actually needed.
本Skill可跨多种编程语言安全识别并移除未使用的代码,包含全面的安全检查机制,可防止误删实际需要的代码。
When to Use This Skill
适用场景
- After refactoring code and removing features
- Before production deployment to reduce bundle size
- When cleaning up legacy code
- When removing deprecated functionality
- When optimizing codebase size
- When maintaining code quality standards
- 代码重构及功能移除后
- 生产部署前用于减小包体积
- 清理遗留代码时
- 移除已弃用功能时
- 优化代码库体积时
- 维护代码质量标准时
What This Skill Does
功能说明
- Language Detection: Identifies project languages and structure
- Entry Point Mapping: Maps entry points and critical paths
- Dependency Analysis: Builds dependency graphs and usage patterns
- Safe Detection: Identifies unused elements with safety checks
- Incremental Removal: Removes code incrementally with validation
- Backup Creation: Creates backups before making changes
- 语言检测:识别项目使用的语言及结构
- 入口点映射:映射代码入口点与关键路径
- 依赖分析:构建依赖图与使用模式
- 安全检测:通过安全检查识别未使用元素
- 增量移除:通过验证机制增量式移除代码
- 备份创建:在修改前创建代码备份
Helper Scripts
辅助脚本
This skill includes Python helper scripts in :
scripts/-
: Uses AST parsing to accurately detect unused imports in Python files. Outputs JSON with unused imports and line numbers.
find_unused_imports.pybashpython scripts/find_unused_imports.py src/utils.py src/services.py
本Skill在目录下包含Python辅助脚本:
scripts/-
:使用AST解析准确检测Python文件中的未使用导入,输出包含未使用导入及行号的JSON结果。
find_unused_imports.pybashpython scripts/find_unused_imports.py src/utils.py src/services.py
How to Use
使用方法
Remove Unused Code
移除未使用代码
Find and remove unused imports and functions in this projectClean up dead code in src/ directory, but be conservative查找并移除本项目中的未使用导入与函数清理src/目录下的未使用代码,操作请保守处理Specific Analysis
专项分析
Check for unused functions in src/utils/ and remove them safely检查src/utils/中的未使用函数并安全移除Analysis Process
分析流程
1. Language Detection
1. 语言检测
Identify Project Type:
- Python: Look for ,
pyproject.toml,setup.pyrequirements.txt - JavaScript/TypeScript: Check ,
package.jsontsconfig.json - Java: Look for ,
pom.xmlbuild.gradle - Go: Check
go.mod - Rust: Check
Cargo.toml
Detect Entry Points:
- Python: ,
main.py,__main__.py,app.pyrun.py - JavaScript: ,
index.js,main.js,server.jsapp.js - Java: ,
Main.java,*Application.java*Controller.java - Config files: ,
*.config.*,settings.*setup.* - Test files: ,
test_*.py,*.test.js*.spec.js
识别项目类型:
- Python:查找、
pyproject.toml、setup.pyrequirements.txt - JavaScript/TypeScript:检查、
package.jsontsconfig.json - Java:查找、
pom.xmlbuild.gradle - Go:检查
go.mod - Rust:检查
Cargo.toml
检测入口点:
- Python:、
main.py、__main__.py、app.pyrun.py - JavaScript:、
index.js、main.js、server.jsapp.js - Java:、
Main.java、*Application.java*Controller.java - 配置文件:、
*.config.*、settings.*setup.* - 测试文件:、
test_*.py、*.test.js*.spec.js
2. Build Dependency Graph
2. 构建依赖图
Cross-File Dependencies:
- Track imports and requires
- Map function/method calls
- Identify class inheritance
- Track dynamic usage patterns
Framework Patterns:
- Preserve framework-specific patterns (Django models, React components, etc.)
- Check for decorators and annotations
- Verify entry point registrations
跨文件依赖:
- 跟踪导入与引用关系
- 映射函数/方法调用
- 识别类继承关系
- 跟踪动态使用模式
框架模式:
- 保留框架特定模式(如Django模型、React组件等)
- 检查装饰器与注解
- 验证入口点注册
3. Detect Unused Elements
3. 检测未使用元素
Using Helper Script:
The skill includes a Python helper script for finding unused imports:
bash
undefined使用辅助脚本:
本Skill包含用于查找未使用导入的Python辅助脚本:
bash
undefinedFind unused imports in Python files
查找Python文件中的未使用导入
python scripts/find_unused_imports.py src/utils.py src/services.py
**Unused Imports:**
```pythonpython scripts/find_unused_imports.py src/utils.py src/services.py
**未使用导入:**
```pythonPython: AST-based analysis
Python:基于AST的分析
import ast
import ast
Track: Import statements vs actual usage
跟踪:导入语句与实际使用情况
Skip: Dynamic imports (importlib, import)
排除:动态导入(importlib、import)
```javascript
// JavaScript: Module analysis
// Track: import/require vs references
// Skip: Dynamic imports, lazy loadingUnused Functions/Classes:
- Define: All declared functions/classes
- Reference: Direct calls, inheritance, callbacks
- Preserve: Entry points, framework hooks, event handlers
```javascript
// JavaScript:模块分析
// 跟踪:import/require与引用关系
// 排除:动态导入、懒加载未使用函数/类:
- 定义:所有已声明的函数/类
- 引用:直接调用、继承、回调
- 保留:入口点、框架钩子、事件处理器
4. Safety Checks
4. 安全检查
Never Remove If:
- Python: ,
getattr(),eval()usage detectedglobals() - JavaScript: ,
window[], dynamicthis[]usageimport() - Java: Reflection, annotations (,
@Component)@Service - Framework patterns: Models, controllers, routes, components
- Entry points: Main functions, app initialization
- Test files: All test-related code
Framework Preservation:
Python:
- Django: Models, migrations, admin registrations
- Flask: Routes, blueprints, app factories
- FastAPI: Endpoints, dependencies
JavaScript:
- React: Components, hooks, context providers
- Vue: Components, directives, mixins
- Angular: Decorators, services, modules
Java:
- Spring: Beans, controllers, repositories
- JPA: Entities, repositories
以下情况绝对不能移除:
- Python:检测到、
getattr()、eval()使用globals() - JavaScript:、
window[]、动态this[]使用import() - Java:反射、注解(、
@Component)@Service - 框架模式:模型、控制器、路由、组件
- 入口点:主函数、应用初始化代码
- 测试文件:所有测试相关代码
框架代码保留规则:
Python:
- Django:模型、迁移文件、admin注册
- Flask:路由、蓝图、应用工厂
- FastAPI:端点、依赖项
JavaScript:
- React:组件、钩子、上下文提供者
- Vue:组件、指令、混入
- Angular:装饰器、服务、模块
Java:
- Spring:Bean、控制器、仓库
- JPA:实体、仓库
5. Safe Removal Process
5. 安全移除流程
Backup Creation:
bash
backup_dir="./unused_code_backup_$(date +%Y%m%d_%H%M%S)"
cp -r . "$backup_dir" 2>/dev/null || mkdir -p "$backup_dir" && rsync -a . "$backup_dir"Incremental Removal:
- Create temp file with change
- Validate syntax
- Run tests if available
- Apply or rollback
Validation:
bash
undefined创建备份:
bash
backup_dir="./unused_code_backup_$(date +%Y%m%d_%H%M%S)"
cp -r . "$backup_dir" 2>/dev/null || mkdir -p "$backup_dir" && rsync -a . "$backup_dir"增量式移除:
- 创建包含修改内容的临时文件
- 验证语法正确性
- 如有测试用例则运行测试
- 应用修改或回滚
验证操作:
bash
undefinedPython
Python
python -m py_compile file.py
python -m pytest
python -m py_compile file.py
python -m pytest
JavaScript
JavaScript
npx eslint file.js
npm test
npx eslint file.js
npm test
Java
Java
javac -Xlint file.java
mvn test
undefinedjavac -Xlint file.java
mvn test
undefinedExamples
示例
Example 1: Remove Unused Imports
示例1:移除未使用导入
Input: Clean up unused imports in
src/utils/helpers.pyOutput:
markdown
undefined输入:清理中的未使用导入
src/utils/helpers.py输出:
markdown
undefinedDead Code Removal: src/utils/helpers.py
未使用代码移除:src/utils/helpers.py
Analysis
分析结果
- File:
src/utils/helpers.py - Total imports: 8
- Unused imports: 3
- 文件:
src/utils/helpers.py - 总导入数:8
- 未使用导入数:3
Unused Imports Found
检测到的未使用导入
- - Line 2 (not used anywhere)
import os - - Line 3 (not used anywhere)
import json - - Line 5 (not used anywhere)
from datetime import timedelta
- - 第2行(未在任何地方使用)
import os - - 第3行(未在任何地方使用)
import json - - 第5行(未在任何地方使用)
from datetime import timedelta
Safe to Remove
可安全移除
✅ All 3 imports are safe to remove (no dynamic usage detected)
✅ 所有3个导入均可安全移除(未检测到动态使用情况)
Changes
修改内容
python
undefinedpython
undefinedBefore
修改前
import os
import json
from datetime import datetime, timedelta
import requests
import os
import json
from datetime import datetime, timedelta
import requests
After
修改后
from datetime import datetime
import requests
undefinedfrom datetime import datetime
import requests
undefinedValidation
验证结果
- ✅ Syntax check passed
- ✅ Tests pass
- ✅ No dynamic imports detected
undefined- ✅ 语法检查通过
- ✅ 测试用例全部通过
- ✅ 未检测到动态导入
undefinedExample 2: Remove Unused Functions
示例2:移除未使用函数
Input: Find unused functions in
src/services/Output:
markdown
undefined输入:查找中的未使用函数
src/services/输出:
markdown
undefinedDead Code Removal: src/services/
未使用代码移除:src/services/
Analysis
分析结果
- Files analyzed: 12
- Functions found: 45
- Unused functions: 2
- 分析文件数:12
- 检测到的函数数:45
- 未使用函数数:2
Unused Functions
未使用函数
1. in
formatOldDate()src/services/utils.js- Location: Line 34-42
- Status: ✅ Safe to remove
- Reason: No references found, not exported, not used in tests
2. in
legacyAuth()src/services/auth.js- Location: Line 78-95
- Status: ⚠️ Preserved (framework pattern)
- Reason: Referenced in route configuration (line 12)
1. 位于
formatOldDate()src/services/utils.js- 位置:第34-42行
- 状态:✅ 可安全移除
- 原因:未找到任何引用,未导出,未在测试中使用
2. 位于
legacyAuth()src/services/auth.js- 位置:第78-95行
- 状态:⚠️ 保留(符合框架模式)
- 原因:在路由配置中被引用(第12行)
Summary
总结
- Removed: 1 function ()
formatOldDate - Preserved: 1 function (framework usage)
- Lines removed: 9
- Size reduction: ~300 bytes
undefined- 已移除:1个函数()
formatOldDate - 已保留:1个函数(框架用途)
- 移除代码行数:9
- 体积减少:约300字节
undefinedBest Practices
最佳实践
Safety Guidelines
安全指南
Do:
- Run tests after each removal
- Preserve framework patterns
- Check string references in templates
- Validate syntax continuously
- Create comprehensive backups
- Remove incrementally
Don't:
- Remove without understanding purpose
- Batch remove without testing
- Ignore dynamic usage patterns
- Skip configuration files
- Remove from migrations
- Remove exported/public APIs
建议操作:
- 每次移除后运行测试
- 保留框架特定模式
- 检查模板中的字符串引用
- 持续验证语法正确性
- 创建全面的代码备份
- 增量式移除代码
禁止操作:
- 在未理解代码用途的情况下移除
- 批量移除而不进行测试
- 忽略动态使用模式
- 跳过配置文件检查
- 移除迁移文件中的代码
- 移除已导出/公开的API
Detection Patterns
检测模式
Static Analysis:
- Use AST parsing for accurate detection
- Track cross-file references
- Check for dynamic usage patterns
- Verify framework-specific patterns
Validation:
- Always run syntax checks
- Run tests after removal
- Verify build still works
- Check for runtime errors
静态分析:
- 使用AST解析实现精准检测
- 跟踪跨文件引用
- 检查动态使用模式
- 验证框架特定模式
验证操作:
- 始终运行语法检查
- 移除后运行测试
- 验证构建是否正常
- 检查运行时错误
Reporting
报告规范
Report Should Include:
- Files analyzed (count and types)
- Unused detected (imports, functions, classes)
- Safely removed (with validation status)
- Preserved (reason for keeping)
- Impact metrics (lines removed, size reduction)
报告应包含:
- 分析的文件(数量与类型)
- 检测到的未使用代码(导入、函数、类)
- 已安全移除的代码(含验证状态)
- 已保留的代码(保留原因)
- 影响指标(移除行数、体积减少量)
Related Use Cases
相关使用场景
- Code cleanup before release
- Reducing bundle size
- Removing deprecated code
- Maintaining code quality
- Refactoring legacy codebases
- Optimizing build times
- 版本发布前的代码清理
- 减小包体积
- 移除已弃用代码
- 维护代码质量
- 重构遗留代码库
- 优化构建时间