|
| 1 | +# Delete Dead Code |
| 2 | + |
| 3 | +This example demonstrates how to identify and remove dead code from a codebase using Codegen. The script efficiently cleans up unused functions and variables, helping maintain a lean and efficient codebase. |
| 4 | + |
| 5 | +> [!NOTE] |
| 6 | +> Dead code refers to code that is not being used or referenced anywhere in your codebase. However, some code might appear unused but should not be deleted, such as test files, functions with decorators, public API endpoints, and event handlers. |
| 7 | +
|
| 8 | +## How the Dead Code Removal Script Works |
| 9 | + |
| 10 | +The script (`run.py`) performs the dead code removal in several key steps: |
| 11 | + |
| 12 | +1. **Codebase Loading** |
| 13 | + ```python |
| 14 | + codebase = Codebase.from_repo("tox-dev/tox", programming_language=ProgrammingLanguage.PYTHON) |
| 15 | + ``` |
| 16 | + - Loads a codebase using the `Codebase.from_repo` method |
| 17 | + - This example uses the `tox-dev/tox` repository because it is mostly self-contained |
| 18 | + |
| 19 | +2. **Function Removal** |
| 20 | + ```python |
| 21 | + for function in codebase.functions: |
| 22 | + if "test" in function.file.filepath: |
| 23 | + continue |
| 24 | + if function.decorators: |
| 25 | + continue |
| 26 | + if not function.usages and not function.call_sites: |
| 27 | + print(f"🗑️ Removing unused function: {function.name}") |
| 28 | + function.remove() |
| 29 | + ``` |
| 30 | + - Skips test files and decorated functions |
| 31 | + - Removes functions with no usages or call sites |
| 32 | + |
| 33 | +3. **Variable Cleanup** |
| 34 | + ```python |
| 35 | + for func in codebase.functions: |
| 36 | + for var_assignments in func.code_block.local_var_assignments: |
| 37 | + if not var_assignments.local_usages: |
| 38 | + print(f"🧹 Removing unused variable: {var_assignments.name}") |
| 39 | + var_assignments.remove() |
| 40 | + ``` |
| 41 | + - Iterates through local variable assignments |
| 42 | + - Removes variables with no local usages |
| 43 | + |
| 44 | +## Running the Script |
| 45 | + |
| 46 | +```bash |
| 47 | +# Install Codegen |
| 48 | +pip install codegen |
| 49 | + |
| 50 | +# Run the script |
| 51 | +python run.py |
| 52 | +``` |
| 53 | + |
| 54 | +## Example Output |
| 55 | + |
| 56 | +``` |
| 57 | +� Deleting dead code... |
| 58 | +
|
| 59 | +🗑️ Removing unused function: _get_parser_doc |
| 60 | +🧹 Removing unused variable: decoded |
| 61 | +🧹 Removing unused variable: shebang_line |
| 62 | +... |
| 63 | +🧹 Removing unused variable: _ |
| 64 | +
|
| 65 | +🔧 Total functions removed: 2 |
| 66 | +📦 Total variables removed: 240 |
| 67 | +``` |
| 68 | + |
| 69 | + |
| 70 | +## Learn More |
| 71 | + |
| 72 | +- [Deleting Dead Code](https://docs.codegen.com/tutorials/deleting-dead-code) |
| 73 | +- [Codegen Documentation](https://docs.codegen.com) |
| 74 | + |
| 75 | +## Contributing |
| 76 | + |
| 77 | +Feel free to submit issues and enhancement requests! |
0 commit comments