ast-grep logo

ast-grep

CLI for structural code search, lint, and rewriting that matches tree-sitter AST nodes using patterns written as ordinary code. Written in Rust.

install

ast-grep (command: sg or ast-grep) is a command-line tool for structural code search, linting, and rewriting. It works like grep, but matches abstract syntax tree nodes produced by tree-sitter rather than text. Patterns are written as ordinary code in the target language, and they match all code with the same syntactic structure.

Patterns use $ followed by upper-case letters, such as $MATCH, as a wildcard that matches any single AST node. A search and replace is a single command, for example ast-grep -p '$A && $A()' -l ts -r '$A?.()' rewrites a guard-and-call expression in TypeScript into optional call syntax. The -p flag gives the pattern, -l the language, -r the rewrite, and -i is used in the README example for interactive rewriting.

Beyond one-off commands, ast-grep supports YAML configuration for writing custom lint rules and code modifications, and the README mentions a jQuery-like API for AST traversal and manipulation. It is written in Rust, parses with tree-sitter, and uses multiple cores. An online playground is available for trying patterns.

Typical users are developers doing large-scale refactors or codemods, library authors who want to help users migrate across breaking changes, tech leads enforcing code conventions, and security researchers writing detection rules.

Installation

# via Homebrew
brew install ast-grep
# via npm
npm install --global @ast-grep/cli
# via pip
pip install ast-grep-cli

ast-grep search and replace demo

Alternatives & related tools

add a badge to your README

Maintain ast-grep? Show that it's featured on trmn. The badge links back to this page.

Featured on trmn
Markdown
[![Featured on trmn](https://www.trmn.sh/badge/ast-grep.svg)](https://www.trmn.sh/tools/ast-grep?utm_source=badge)
HTML
<a href="https://www.trmn.sh/tools/ast-grep?utm_source=badge"><img src="https://www.trmn.sh/badge/ast-grep.svg" alt="Featured on trmn" height="20"></a>