ast-grep

A CLI tool for code structural search, lint, and rewriting using Abstract Syntax Trees.

Screenshot of ast-grep

ast-grep (also known as sg) is a CLI tool for code structural search, lint, and rewriting using Abstract Syntax Trees. Unlike text-based tools like grep or sed, ast-grep matches code by its syntactic structure, making it possible to write precise, language-aware search and replace patterns across large codebases. It supports over 20 programming languages via tree-sitter grammars.

Features

  • Structural search and replace — match code patterns using AST nodes instead of text, then rewrite matches with metavariable capture
  • Intuitive pattern syntax — write patterns as ordinary code with $VAR metavariables, no complex query language required
  • Multi-language support — works with JavaScript, TypeScript, Python, Rust, Go, Java, C, C++, and many more via tree-sitter
  • Custom linting — define rules in YAML with pattern matching, fix suggestions, and pretty error reporting
  • High performance — written in Rust with multi-threaded file traversal for fast results across thousands of files
  • Interactive codemod — review and confirm each replacement interactively before applying changes
  • Programmatic API — Node.js bindings with a jQuery-like API for AST traversal and manipulation

Installation

cargo install ast-grep --locked

Or via package managers:

# Debian / Ubuntu / Fedora
# Install via npm (works on all Linux distributions)
npm install --global @ast-grep/cli

# macOS
brew install ast-grep

# Arch Linux
pacman -S ast-grep

# Nix
nix-shell -p ast-grep

# pip
pip install ast-grep-cli

Usage

# Search for a pattern in the current directory
sg -p 'console.log($MSG)'

# Search in a specific language
sg -p '$PROP && $PROP()' -l ts

# Replace a pattern across files
sg -p '$PROP && $PROP()' -r '$PROP?.()' -l ts

# Interactive codemod — review each replacement before applying
sg -p '$PROP && $PROP()' -r '$PROP?.()' --interactive -l ts

# Scan project with custom lint rules
sg scan

# Run a single rule from a YAML file
sg scan -r my-rule.yml

Configuration

ast-grep uses a sgconfig.yml file for project-level configuration and custom rules. Initialize a project with:

sg new

Define custom lint rules in YAML:

id: no-console-log
language: TypeScript
rule:
  pattern: console.log($$$ARGS)
message: Remove console.log before committing
severity: warning
fix: ""

Why ast-grep over grep/sed?

Capabilitygrep/sedast-grep
Match typeText / regexAST structure
Understands nestingNoYes
Language-awareNo20+ languages
RefactoringFragilePrecise
Custom lint rulesNoYAML-based
Interactive modeNoYes