CtrlK
BlogDocsLog inGet started
Tessl Logo
SkillPublic

ast-grep-patterns

This reference explains when to use ast-grep instead of plain-text search and provides commands and recipes for finding or rewriting code by structure. It covers checks for error handling, deprecated APIs, SQL injection risks, secret-like literals, and other code patterns, along with troubleshooting and prompt templates. It recommends testing patterns on a small file first and waiting for approval before applying a rewrite in the large-refactor prompt template.

Quality

87%

Does it follow best practices?

Run evals on this skill

Adds up to 20 points to the overall score

View guide
SecuritybySnyk

Low

Low-risk findings worth noting

SKILL.md
Quality
Evals
Security

ast-grep patterns

ast-grep matches code by syntax tree, so it survives formatting differences and needs no regex escaping. The patterns below were run against ast-grep 0.51.3 on small TypeScript and TSX samples. Test each one on a small file before running it across a repository.

Install

brew install ast-grep            # or: npm install --global @ast-grep/cli
ast-grep --version

The binary is ast-grep (alias sg). An optional agent skill is published at ast-grep/agent-skill (install command not verified here).

When to use it

RequestTool
Find a string, a name, an importGrep
Find code by meaning ("where is auth handled")A semantic search tool such as grepai, or an LSP or symbol-aware MCP server
Find or rewrite code by structureast-grep
Rename every call, change an API signature, migrate a frameworkast-grep

For a small project or a one-off lookup, Grep is enough. ast-grep pays off when the same structural change touches many files.

Quick commands

# One-off pattern ($X = one node, $$$X = zero or more nodes)
ast-grep run -p 'console.log($$$ARGS)' -l ts src/

# Rewrite (preview first, then add --update-all to apply)
ast-grep run -p 'oldApi($A)' -r 'newApi($A)' -l ts src/

# Run a YAML rule file
ast-grep scan -r rules/async-no-try.yml src/

# Machine-readable output
ast-grep run -p 'class $C extends React.Component { $$$ }' -l tsx --json=compact src/

# Print the syntax tree of a pattern when it does not match
ast-grep run --debug-query=ast -p 'foo($A)' -l ts

The language is required for run; use ts for .ts files and tsx for .tsx files, because a rule written for one does not scan the other.

Rule recipes

Each recipe is saved as a rule file (id, language, rule) and run with ast-grep scan -r <file> <path>.

Async functions without try/catch

id: async-no-try
language: tsx
rule:
  pattern: async function $F($$$P) { $$$B }
  not:
    has:
      kind: try_statement
      stopBy: end

stopBy: end makes has search the whole subtree instead of only direct children. Without it the rule reports functions that do have a nested try.

useEffect without a cleanup function

id: effect-no-cleanup
language: tsx
rule:
  pattern: useEffect(() => { $$$B })
  not:
    has:
      pattern: return () => { $$$C };
      stopBy: end

Only effects with a block body and no dependency array match the pattern. Add a second pattern with , [$$$D] for effects that declare dependencies.

Functions with more than five parameters

ast-grep run -p 'function $N($A, $B, $C, $D, $E, $F, $$$R) { $$$ }' -l ts src/

Empty catch blocks

ast-grep run -p 'try { $$$T } catch ($E) {}' -l ts src/

A catch block that holds only a comment is also reported, because comments are not statements.

Deprecated lifecycle methods

id: deprecated-lifecycle
language: tsx
rule:
  kind: method_definition
  has:
    field: name
    regex: "^(componentWillMount|componentWillReceiveProps|componentWillUpdate)$"

A bare componentWillMount() { $$$B } is not a valid pattern (it parses as several nodes), so match the node kind and filter its name instead.

Template-literal SQL (injection risk)

id: sql-template
language: tsx
rule:
  pattern: db.query($Q)
  has:
    kind: template_substitution
    stopBy: end

Matches only queries built with ${...} interpolation, not static template strings.

Functions without an explicit return type

id: no-return-type
language: tsx
rule:
  kind: function_declaration
  not:
    has:
      field: return_type
      kind: type_annotation

innerHTML assignments

ast-grep run -p '$E.innerHTML = $V' -l ts src/

Hardcoded secret-looking properties

id: secret-literal
language: tsx
rule:
  kind: pair
  has:
    field: key
    regex: "(?i)^(password|secret|api_?key|token)$"
  all:
    - has:
        field: value
        kind: string

A metavariable must be a whole node: password: "$P" does not bind inside the string, which is why this rule filters by key and value kind instead.

Troubleshooting

SymptomFix
Pattern matches nothingPrint the tree with --debug-query=ast and compare it with the code. A pattern must be one complete syntax node.
"Multiple AST nodes are detected"The pattern is a fragment. Match the enclosing node by kind and add has or regex.
Rule scans nothingCheck language against the file extension (typescript vs tsx).
"Rule must have one positive matcher"A not or has with only field is not enough. Add kind or pattern.
Slow on a large repositoryNarrow the path, set -l, or use --globs to skip generated files.
Claude reaches for GrepAsk explicitly: "use ast-grep to find ...".

Prompt templates

Large refactor:

Use ast-grep to find every call to [OLD_API] in [DIRECTORY], list the affected files,
and propose a phased rewrite. Analysis only: wait for my approval before applying a rewrite.

Framework migration:

Use ast-grep to find deprecated [FRAMEWORK] APIs in [DIRECTORY], map each to its
replacement, and order the migration by risk. Do not apply changes.

Resources

  • ast-grep documentation: https://ast-grep.github.io/
  • Pattern playground: https://ast-grep.github.io/playground.html
  • Source: https://github.com/ast-grep/ast-grep
Repository

FlorianBruniaux/claude-code-ultimate-guide

Path

examples/skills/ast-grep-patterns/SKILL.md

Last updated
First committed
Purpose
DevelopmentTesting and QASecurity and complianceDebugging and error handling
Form
WorkflowRulesBest practicesReferenceTemplate
Commands
brewbrew installnpmnpm installast-grepast-grep runast-grep scan
Tools
brewnpmast-grep
Usage
One-off
Human confirmation
Required before acting

Is this your skill?

If you maintain this skill, you can claim it as your own. Once claimed, you can manage eval scenarios, bundle related skills, attach documentation or rules, and ensure cross-agent compatibility.