Automate Your Code Refactoring with Structural Search and Replace
Let's be honest: large-scale refactoring is a pain. Find-and-replace is too dumb, and writing a custom script for every little syntax change is a time sink. What if you could search and replace code based on its structure—not just text—without having to become a compiler expert?
That's exactly what ast-grep offers. It's a CLI tool for code restructuring, linting, and massive refactoring, using the concrete syntax tree of your code. Think of it as grep or your IDE's "find in files," but it understands the grammar of your programming language.
What It Does
ast-grep (Abstract Syntax Tree grep) lets you define patterns to match code structures. You write a pattern that looks like the code you want to find, using placeholders for variables, expressions, or any syntax node. Then, you can transform those matches automatically.
For example, you could find all console.log statements and comment them out, change a deprecated API call to a new one, or enforce a custom naming convention—across your entire codebase in one command.
Why It's Cool
The magic is in its simplicity and power. You don't write complex abstract syntax tree traversals; you write patterns that look like the code you're editing every day. It supports multiple languages (JavaScript, TypeScript, Python, Rust, and more) out of the box because it builds on tree-sitter.
A killer feature is the interactive playground on its website, where you can test patterns live. You can also create and share custom rules as YAML configs, making it easy to automate code quality checks unique to your project. It's like having a programmable linter for your very specific refactoring needs.
How to Try It
The quickest way is to check out the online playground. Paste some code, write a simple pattern (like console.log($ARG)), and see what it matches.
To run it locally, install via cargo (Rust's package manager):
cargo install ast-grep
Or use npm:
npm install @ast-grep/cli -g
Then, run sg scan in your project directory with a rule file. The GitHub repo has comprehensive examples to get you started.
Final Thoughts
For one-off refactors or building custom lint rules, ast-grep feels like a secret weapon. It won't replace your linter or formatter, but it perfectly fills that gap when you need to make a systematic, syntax-aware change and don't want to manually edit 200 files. It's the kind of tool you might only use once a month, but when you need it, you'll be really glad it exists.
@githubprojects
Repository: https://github.com/ast-grep/ast-grep