Dead 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.
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/:
find_unused_imports.py: Uses AST parsing to accurately detect unused imports in Python files. Outputs JSON with unused imports and line numbers.
python 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 project
Clean up dead code in src/ directory, but be conservative
Specific Analysis
Check for unused functions in src/utils/ and remove them safely
Analysis Process
1. Language Detection
Identify Project Type:
- Python: Look for
pyproject.toml, setup.py, requirements.txt
- JavaScript/TypeScript: Check
package.json, tsconfig.json
- Java: Look for
pom.xml, build.gradle
- Go: Check
go.mod
- Rust: Check
Cargo.toml
Detect Entry Points:
- Python:
main.py, __main__.py, app.py, run.py
- JavaScript:
index.js, main.js, server.js, app.js
- Java:
Main.java, *Application.java, *Controller.java
- Config files:
*.config.*, settings.*, setup.*
- Test files:
test_*.py, *.test.js, *.spec.js
2. Build Dependency Graph
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
3. Detect Unused Elements
Using Helper Script:
The skill includes a Python helper script for finding unused imports:
# Find unused imports in Python files
python scripts/find_unused_imports.py src/utils.py src/services.py
Unused Imports:
# Python: AST-based analysis
import ast
# Track: Import statements vs actual usage
# Skip: Dynamic imports (importlib, __import__)
// JavaScript: Module analysis
// Track: import/require vs references
// Skip: Dynamic imports, lazy loading
Unused Functions/Classes:
- Define: All declared functions/classes
- Reference: Direct calls, inheritance, callbacks
- Preserve: Entry points, framework hooks, event handlers
4. Safety Checks
Never Remove If:
- Python:
getattr(), eval(), globals() usage detected
- JavaScript:
window[], this[], dynamic import() usage
- 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
5. Safe Removal Process
Backup Creation:
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:
# Python
python -m py_compile file.py
python -m pytest
# JavaScript
npx eslint file.js
npm test
# Java
javac -Xlint file.java
mvn test
Examples
Example 1: Remove Unused Imports
Input: Clean up unused imports in src/utils/helpers.py
Output:
## Dead Code Removal: src/utils/helpers.py
### Analysis
- **File**: `src/utils/helpers.py`
- **Total imports**: 8
- **Unused imports**: 3
### Unused Imports Found
1. `import os` - Line 2 (not used anywhere)
2. `import json` - Line 3 (not used anywhere)
3. `from datetime import timedelta` - Line 5 (not used anywhere)
### Safe to Remove
✅ All 3 imports are safe to remove (no dynamic usage detected)
### Changes
```python
# Before
import os
import json
from datetime import datetime, timedelta
import requests
# After
from datetime import datetime
import requests
Validation
- ✅ Syntax check passed
- ✅ Tests pass
- ✅ No dynamic imports detected
### Example 2: Remove Unused Functions
**Input**: Find unused functions in `src/services/`
**Output**:
```markdown
## Dead Code Removal: src/services/
### Analysis
- **Files analyzed**: 12
- **Functions found**: 45
- **Unused functions**: 2
### Unused Functions
**1. `formatOldDate()` in `src/services/utils.js`**
- **Location**: Line 34-42
- **Status**: ✅ Safe to remove
- **Reason**: No references found, not exported, not used in tests
**2. `legacyAuth()` in `src/services/auth.js`**
- **Location**: Line 78-95
- **Status**: ⚠️ Preserved (framework pattern)
- **Reason**: Referenced in route configuration (line 12)
### Summary
- **Removed**: 1 function (`formatOldDate`)
- **Preserved**: 1 function (framework usage)
- **Lines removed**: 9
- **Size reduction**: ~300 bytes
Best 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
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
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
1---2name: dead-code-removal3description: Detects and safely removes unused code (imports, functions, classes) across multiple languages. Use after refactoring, when removing features, or before production deployment. Includes safety checks and validation.4---56# Dead Code Removal78This skill safely identifies and removes unused code across multiple programming languages. It includes comprehensive safety checks to prevent removing code that's actually needed.910## When to Use This Skill1112- After refactoring code and removing features13- Before production deployment to reduce bundle size14- When cleaning up legacy code15- When removing deprecated functionality16- When optimizing codebase size17- When maintaining code quality standards1819## What This Skill Does20211. **Language Detection**: Identifies project languages and structure222. **Entry Point Mapping**: Maps entry points and critical paths233. **Dependency Analysis**: Builds dependency graphs and usage patterns244. **Safe Detection**: Identifies unused elements with safety checks255. **Incremental Removal**: Removes code incrementally with validation266. **Backup Creation**: Creates backups before making changes2728## Helper Scripts2930This skill includes Python helper scripts in `scripts/`:3132- **`find_unused_imports.py`**: Uses AST parsing to accurately detect unused imports in Python files. Outputs JSON with unused imports and line numbers.3334 ```bash35 python scripts/find_unused_imports.py src/utils.py src/services.py36 ```3738## How to Use3940### Remove Unused Code4142```43Find and remove unused imports and functions in this project44```4546```47Clean up dead code in src/ directory, but be conservative48```4950### Specific Analysis5152```53Check for unused functions in src/utils/ and remove them safely54```5556## Analysis Process5758### 1. Language Detection5960**Identify Project Type:**6162- Python: Look for `pyproject.toml`, `setup.py`, `requirements.txt`63- JavaScript/TypeScript: Check `package.json`, `tsconfig.json`64- Java: Look for `pom.xml`, `build.gradle`65- Go: Check `go.mod`66- Rust: Check `Cargo.toml`6768**Detect Entry Points:**6970- Python: `main.py`, `__main__.py`, `app.py`, `run.py`71- JavaScript: `index.js`, `main.js`, `server.js`, `app.js`72- Java: `Main.java`, `*Application.java`, `*Controller.java`73- Config files: `*.config.*`, `settings.*`, `setup.*`74- Test files: `test_*.py`, `*.test.js`, `*.spec.js`7576### 2. Build Dependency Graph7778**Cross-File Dependencies:**7980- Track imports and requires81- Map function/method calls82- Identify class inheritance83- Track dynamic usage patterns8485**Framework Patterns:**8687- Preserve framework-specific patterns (Django models, React components, etc.)88- Check for decorators and annotations89- Verify entry point registrations9091### 3. Detect Unused Elements9293**Using Helper Script:**9495The skill includes a Python helper script for finding unused imports:9697```bash98# Find unused imports in Python files99python scripts/find_unused_imports.py src/utils.py src/services.py100```101102**Unused Imports:**103104```python105# Python: AST-based analysis106import ast107# Track: Import statements vs actual usage108# Skip: Dynamic imports (importlib, __import__)109```110111```javascript112// JavaScript: Module analysis113// Track: import/require vs references114// Skip: Dynamic imports, lazy loading115```116117**Unused Functions/Classes:**118119- Define: All declared functions/classes120- Reference: Direct calls, inheritance, callbacks121- Preserve: Entry points, framework hooks, event handlers122123### 4. Safety Checks124125**Never Remove If:**126127- Python: `getattr()`, `eval()`, `globals()` usage detected128- JavaScript: `window[]`, `this[]`, dynamic `import()` usage129- Java: Reflection, annotations (`@Component`, `@Service`)130- Framework patterns: Models, controllers, routes, components131- Entry points: Main functions, app initialization132- Test files: All test-related code133134**Framework Preservation:**135136**Python:**137138- Django: Models, migrations, admin registrations139- Flask: Routes, blueprints, app factories140- FastAPI: Endpoints, dependencies141142**JavaScript:**143144- React: Components, hooks, context providers145- Vue: Components, directives, mixins146- Angular: Decorators, services, modules147148**Java:**149150- Spring: Beans, controllers, repositories151- JPA: Entities, repositories152153### 5. Safe Removal Process154155**Backup Creation:**156157```bash158backup_dir="./unused_code_backup_$(date +%Y%m%d_%H%M%S)"159cp -r . "$backup_dir" 2>/dev/null || mkdir -p "$backup_dir" && rsync -a . "$backup_dir"160```161162**Incremental Removal:**1631641. Create temp file with change1652. Validate syntax1663. Run tests if available1674. Apply or rollback168169**Validation:**170171```bash172# Python173python -m py_compile file.py174python -m pytest175176# JavaScript177npx eslint file.js178npm test179180# Java181javac -Xlint file.java182mvn test183```184185## Examples186187### Example 1: Remove Unused Imports188189**Input**: Clean up unused imports in `src/utils/helpers.py`190191**Output**:192193```markdown194## Dead Code Removal: src/utils/helpers.py195196### Analysis197- **File**: `src/utils/helpers.py`198- **Total imports**: 8199- **Unused imports**: 3200201### Unused Imports Found2021. `import os` - Line 2 (not used anywhere)2032. `import json` - Line 3 (not used anywhere)2043. `from datetime import timedelta` - Line 5 (not used anywhere)205206### Safe to Remove207✅ All 3 imports are safe to remove (no dynamic usage detected)208209### Changes210```python211# Before212import os213import json214from datetime import datetime, timedelta215import requests216217# After218from datetime import datetime219import requests220```221222### Validation223224- ✅ Syntax check passed225- ✅ Tests pass226- ✅ No dynamic imports detected227228```229230### Example 2: Remove Unused Functions231232**Input**: Find unused functions in `src/services/`233234**Output**:235```markdown236## Dead Code Removal: src/services/237238### Analysis239- **Files analyzed**: 12240- **Functions found**: 45241- **Unused functions**: 2242243### Unused Functions244245**1. `formatOldDate()` in `src/services/utils.js`**246- **Location**: Line 34-42247- **Status**: ✅ Safe to remove248- **Reason**: No references found, not exported, not used in tests249250**2. `legacyAuth()` in `src/services/auth.js`**251- **Location**: Line 78-95252- **Status**: ⚠️ Preserved (framework pattern)253- **Reason**: Referenced in route configuration (line 12)254255### Summary256- **Removed**: 1 function (`formatOldDate`)257- **Preserved**: 1 function (framework usage)258- **Lines removed**: 9259- **Size reduction**: ~300 bytes260```261262## Best Practices263264### Safety Guidelines265266**Do:**267268- Run tests after each removal269- Preserve framework patterns270- Check string references in templates271- Validate syntax continuously272- Create comprehensive backups273- Remove incrementally274275**Don't:**276277- Remove without understanding purpose278- Batch remove without testing279- Ignore dynamic usage patterns280- Skip configuration files281- Remove from migrations282- Remove exported/public APIs283284### Detection Patterns285286**Static Analysis:**287288- Use AST parsing for accurate detection289- Track cross-file references290- Check for dynamic usage patterns291- Verify framework-specific patterns292293**Validation:**294295- Always run syntax checks296- Run tests after removal297- Verify build still works298- Check for runtime errors299300### Reporting301302**Report Should Include:**303304- Files analyzed (count and types)305- Unused detected (imports, functions, classes)306- Safely removed (with validation status)307- Preserved (reason for keeping)308- Impact metrics (lines removed, size reduction)309310## Related Use Cases311312- Code cleanup before release313- Reducing bundle size314- Removing deprecated code315- Maintaining code quality316- Refactoring legacy codebases317- Optimizing build times