name: ast-grep-refactor description: Structural refactoring and safe code rewrites with ast-grep across supported languages. Use for codemods, removing or replacing AST nodes (imports, docstrings, arguments), pattern-based migrations, and multi-file transformations when plain text search/replace is likely to be unsafe.
ast-grep Refactor
Use ast-grep to refactor by AST, not by text. Keep rules small, test on samples, then scale to the codebase.
Quick workflow
- Inspect AST for the target pattern.
- Write a rule that matches only what you intend.
- Dry-run on small files and review diffs.
- Apply at scale only after review or tests.
- Format and run checks.
ast-grep run --pattern '...' --lang <language> --debug-query=ast path/to/file
ast-grep scan -r rule.yml path/to/file
ast-grep scan -r rule.yml --update-all path/glob/**
Review matches via ast-grep scan output, --interactive, or git diff before --update-all.
Decide the rule shape
- Use
patternfor simple rewrites with metavariables. - Use
kindplus relational rules (inside,has,nthChild) for structural or positional changes. - Use
fixstring for direct replacement; useFixConfigwhen you must remove punctuation or neighbors. - Use
transformto change captured strings; userewritersto rewrite different subnodes differently.
Rule files
- Separate multiple rules with
---. - Keep rules focused and composable.
- For repeatable or risky changes, add rule tests and run
ast-grep test.
References
- Rule basics and selection:
references/rule-basics.md - Rewrite and
fix:references/rewrite.md - FixConfig expansion:
references/fix-expand.md - Transformations:
references/transform.md - Rewriters:
references/rewriter.md - Troubleshooting:
references/troubleshooting.md - Examples:
references/examples.md
When to skip ast-grep
- Very small, one-off edits where manual editing is faster.
- Pure text replacement where AST structure does not matter.
- Changes requiring type-aware or semantic analysis.