Refactoring code across a large codebase requires precision and safety. The Gemini CLI provides a suite of tools that, when combined, create a powerful workflow for automated refactoring.
1. Discovery with Search Tools
Before changing anything, you must understand the scope. Use search_file_content to find all occurrences of the symbol or pattern you intend to refactor. Use the include parameter to narrow down to specific file types (e.g., *.ts) to avoid noise.
2. Context Validation
Never rely solely on search results. Use read_file to inspect the code around the matches. This ensures you aren't accidentally changing a string literal or a comment that looks like code.
3. Multi-File Changes
Perform the refactoring using the replace tool. For changes affecting multiple files, execute a series of replace calls. It is often best to group these logically (e.g., definition first, then usages).
4. Verification and Safety
After applying changes, immediate verification is crucial.
- Visual Check: Use
run_shell_commandwithgit diffto see exactly what changed. - Automated Check: Run the project's test suite (e.g.,
npm test) to ensure no regressions were introduced. - Rollback: If the tests fail, you can safely undo your changes using
git restore .orgit checkout ..