ast-grep
Skill4 starsChanged 3 months agoMITView on GitHub
AST-based structural code search, lint, and rewrite via the `ast-grep` (`sg`) CLI. Use when a search or edit is about code SYNTAX STRUCTURE rather than text: finding every call site of a function, matching shapes such as "async functions without try/catch" or "useEffect without a dependency array", codemods that rewrite matched nodes, YAML lint rules that enforce project patterns, multi-pass symbol renaming, or listing a file's symbols, imports and exports. Also use whenever the request names ast-grep, sg, metavariables ($NAME, $$$ARGS), tree-sitter patterns, or sgconfig.yml. Use INSTEAD of grep/ripgrep whenever the pattern spans multiple lines, nests parentheses or brackets, or would otherwise match inside strings and comments. Covers 25+ languages (JS, TS, TSX, Python, Rust, Go, Java, C, C++, C#, Kotlin, Swift, Ruby, PHP and more). Prefer a sibling skill instead when the task is template/SQL/HTML/multi-format replacement or a Python 2 to 3 migration (use structural-refactor). Do NOT use for: plain string or regex searches, file-name lookups, log or config file searches, or a single edit in one known file.
We split this skill into the rules it gives an agent
7 rules. 0 are common, 2 are distinctive, and 5 are very specific to this project.
0
Common
Most of the 20 edited versions we read keep these.
2
Distinctive
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 43
Check first: which ast-grep.
- Very specific: line 104
Always put patterns in single quotes — double quotes let the shell expand $NAME first.
- Very specific: line 118
Inspect: add --json=compact if you must verify match boundaries.
- Very specific: line 119
Preview: add -r '<rewrite>' — the diff prints to stdout, nothing is written.
- Very specific: line 120
Apply: add --interactive for per-match review, or -U to apply all.
- Distinctive: line 121
Verify: run the search again and expect exit code 1 (no matches).
- Distinctive: line 134
Read these on demand. Do not load them all at once.
“Common” is measured: kept by at least 6 in 10 of the 20 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
ast-grep — Structural Code Search, Lint, and Rewrite
Content verified against ast-grep 0.45.1. Flags can drift between versions — when a command fails, check ast-grep <cmd> --help.
Overview
ast-grep is a fast, Rust-based CLI tool. It parses code with tree-sitter and matches the syntax tree, not the text. You write patterns that look like the code you search for. Metavariables ($NAME, $$$ARGS) act as wildcards for AST nodes.
Three main modes:
| Mode | Command | Use for |
| Search / rewrite | ast-grep run -p '<pattern>' (default command) | One-time queries and codemods |
| Lint | ast-grep scan | YAML rule sets, CI checks, complex rules |
| Explore | ast-grep outline | Symbols, imports, exports of files |
It supports 25+ languages: JavaScript, TypeScript, TSX, Python, Rust, Go, Java, C, C++, C#, Kotlin, Swift, Ruby, PHP, and more. See the language table in references/cli-reference.md.
Installation
Check first: which ast-grep. If it is not installed, run the bundled helper:
bash <SKILL_DIR>/scripts/install.shThe script tries brew, cargo, npm, pip3, and MacPorts in order, and verifies the result. For manual installation see https://ast-grep.github.io/guide/quick-start.html.
Note: some systems have a different sg binary (shell group). Always use the full name ast-grep.
Tool Selection: grep vs ast-grep vs LSP
| The question is about... | Use |
| Text: strings, error messages, config values, file names | grep / rg / fd |
| Syntax: "all calls that look like X", pattern rewrites, codemods, lint rules | ast-grep |
| Semantics: go-to-definition, find-references across scopes, types, scope-aware rename | LSP / compiler tooling |
| Graphs: transitive callers, circular imports, dead-code detection across a whole codebase | A graph script over ast-grep --json output; ast-grep alone sees only per-file matches |
ast-grep matches syntax, not semantics. It cannot tell two same-named symbols in different scopes apart. A rename with ast-grep is an exact syntactic replace (it skips comments, strings, and oldNameHelper), but it hits every scope. For a true semantic rename, prefer an LSP rename; use ast-grep when no LSP is available and verify the diff.
There is no runtime conflict with LSP tools: the ast-grep CLI is stateless — it reads files, matches, and exits. It starts no server and builds no index.
Also do NOT use ast-grep when:
- The pattern spans comments or string contents — patterns cannot match inside them.
- The codebase is tiny (< 5 files) — just read the files.
Files with syntax errors are usually fine: tree-sitter error recovery still matches the valid regions.
Quick Start
# Find all console.log calls in TypeScript
ast-grep -p 'console.log($$$ARGS)' -l ts src/
# Rewrite: var -> const, interactive review per match
ast-grep -p 'var $N = $V' -r 'const $N = $V' -l js --interactive src/
# Apply all rewrites without confirmation
ast-grep -p '$P && $P()' -r '$P?.()' -l ts -U src/
# Only list files that contain a match
ast-grep -p 'eval($$$A)' -l js --files-with-matches src/
# JSON output for scripts (note: --json requires `=` for its value)
ast-grep -p 'function $NAME($$$P) { $$$B }' -l ts --json=compact src/ > matches.json
# Run one inline YAML rule without a file
ast-grep scan --inline-rules 'id: no-eval
language: typescript
severity: error
rule: {pattern: "eval($$$A)"}' src/
# Show the structure of a file
ast-grep outline src/parser.ts --type class,function
# Test a pattern without files, via stdin
echo 'var x = 1' | ast-grep -p 'var $N = $V' -l js --stdinAlways put patterns in single quotes — double quotes let the shell expand $NAME first. For interactive pattern experiments there is an online playground: https://ast-grep.github.io/playground.html
Metavariables — Minimal Reminder
$VARmatches exactly one AST node.$$$ARGSmatches zero or more.- Default to
$$$for arguments, parameters, and bodies.foo($ARG)matches only one-argument calls — this is the most common cause of missed matches. - Repeated names must match identical content:
$A == $Amatchesx == x, notx == y. - Names use
A-Z,_, digits.$varis invalid.$_NAMEis non-capturing.
Full syntax, pattern objects, strictness, and language pitfalls (TypeScript generics, keywords, statement-vs-expression): references/pattern-syntax.md.
Standard Workflow: Rewrite
- Search:
ast-grep -p '<pattern>' -l <lang> <path>— check the matches. - Inspect: add
--json=compactif you must verify match boundaries. - Preview: add
-r '<rewrite>'— the diff prints to stdout, nothing is written. - Apply: add
--interactivefor per-match review, or-Uto apply all. - Verify: run the search again and expect exit code 1 (no matches). Then run the project tests.
A rename needs multiple passes (definition, call sites, imports are distinct node kinds) — see references/pattern-syntax.md.
Exit Codes
run:0= at least one match,1= no match. In scripts, "no matches" is not an error.scan:0= clean,1= diagnostics witherrorseverity found. Use this as a CI gate.- Other non-zero codes signal usage or config errors (e.g.
2bad flag,8invalid pattern/rule). - Pipelines mask exit codes.
ast-grep ... | other-toolreports the last command's status. Setset -o pipefail(bash/zsh) when the ast-grep status matters.
Reference Files
Read these on demand. Do not load them all at once.
- references/cli-reference.md — All subcommands and flags (verified against 0.45.1), flag syntax rules, language table.
- references/pattern-syntax.md — Full pattern syntax, pattern objects, strictness levels, pitfalls with examples.
- references/rule-yaml.md — YAML rule files, rule object (atomic/relational/composite),
sgconfig.ymlproject setup, rule testing, CI. - references/pattern-cookbook.md — Ready-to-use patterns for JS/TS/Python, rewrite recipes with semantic warnings, task recipes (find callers, dead exports), YAML rule scenarios.
Bundled Scripts
Replace <SKILL_DIR> with the absolute directory of this SKILL.md file.
scripts/install.sh— Try available package managers in order and install ast-grep.scripts/json-summary.py— Summarizeast-grep --jsonoutput: match counts per file plus a compact match list. Usage:set -o pipefail # keep ast-grep's exit code visible ast-grep -p '<pattern>' --json=compact <path> | python3 <SKILL_DIR>/scripts/json-summary.py
Other versions20 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 20
- AprilNEA/OpenLogi★ 25ksame name
- ccusage/ccusage★ 19ksame name
- ryoppippi/ccusage★ 19ksame name
- warp-drive-data/warp-drive★ 3.2ksame name
- coleam00/skills★ 725same name
- nodetool-ai/nodetool★ 603same name
- moeru-ai/auv★ 198same name
- damusix/skills★ 61same name
- ulpi-io/browse★ 15same name
- tstapler/dotfiles★ 8same name
10 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
Used alongsideProjects with it also use rust, github-issues and 4 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
MicrosoftSkillrust
Use this guide when working on Rust changes in the FAST monorepo.
Also in 3 projects that use this
SentrySkillgithub-issues
Create, update, comment on, label, and inspect GitHub issues with concise, evidence-backed content. Use when users ask to open, edit, view, close, reopen, or triage GitHub issues — including tracking bugs, features, or tasks. Prefer this skill over generic repository tools for issue operations; do not use for pull requests, branches, pushes, or PR creation order questions.
Also in 3 projects that use this
SentrySkillcreate-pr
Create pull requests following Sentry conventions. Use when opening PRs, writing PR descriptions, or preparing changes for review. Follows Sentry's code review guidelines.
Also in 4 projects that use this
GoogleSkilltdd
Test-driven development. Use when the user wants to build features or fix bugs test-first, mentions "red-green-refactor", or wants integration tests.
Also in 4 projects that use this
- +2 more from getsentry
In this repository7 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- llms.txtllms.txt
- ast-code-graphSkill
- self-reflectionSkill
- structural-refactorSkill
- systematic-debuggingSkill
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

