Using ast-grep for Code Refactoring

lesson tools active tools/ast-grep-refactoring.md View on GitHub

Using ast-grep for Code Refactoring

Rule

Use ast-grep (sg) for structural code search and refactoring when patterns are complex or language-specific.

Context

When you need to find or refactor code patterns across many files, enforce coding standards, or perform precise structural searches beyond regex capabilities.

Detection

Observable signals you should use ast-grep:

Pattern

Structural search and rewrite with ast-grep:

# Search for function patterns
sg run --pattern 'def $FUNC($ARGS): $$$' --lang python src/

# Rewrite with preview
sg run --pattern 'print($MSG)' --rewrite 'logger.info($MSG)' --lang python

# Interactive selective changes
sg run --pattern 'old_func($ARGS)' --rewrite 'new_func($ARGS)' --lang python -i

Anti-pattern: Text-based refactoring

# smell: brittle text manipulation
sed -i 's/old_func/new_func/g' *.py  # breaks strings, comments
grep -r "def.*function" --include="*.py"  # imprecise

Outcome

Following this pattern leads to:

Related

Match Keywords

sg run --pattern ast-grep structural search code refactoring across files replace pattern in codebase AST-based code transformation