AgentSkillsCN

os-tk-ast-grep

基于 AST-Grep 的结构化代码搜索与重构(可选)

SKILL.md
--- frontmatter
name: os-tk-ast-grep
description: Structural code search and refactoring via ast-grep (optional)
optional: true
requires: ast-grep CLI

os-tk-ast-grep (optional skill)

Purpose

Perform structural code search and refactoring using ast-grep when you need code‑aware matching beyond simple text search.

When to use

  • Find code patterns that require understanding syntax (e.g., “all async functions without error handling”)
  • Refactor code across multiple files (e.g., convert var to let, rename function calls)
  • Write custom linting rules for project‑specific patterns
  • Search by language constructs (e.g., “all React components using useEffect”)

When NOT to use

  • Simple text searches – use rg instead (faster)
  • Grep‑style keyword huntsrg is better suited
  • Projects without ast-grep installed – this is an optional enhancement

Basic usage

Search for a pattern

bash
ast-grep -p "console.log($MSG)" -l js

Refactor code

bash
ast-grep -p "var $NAME = $VALUE" -r "let $NAME = $VALUE" -l js

Search across multiple languages

bash
ast-grep -p "Promise.all($WAIT)" -l ts,py

Inputs

  • Pattern (-p): the code pattern to search for
  • Rewrite (-r): optional replacement pattern
  • Language (-l): target language(s)
  • Files/directories: defaults to current directory

Output

  • Matching files with line numbers
  • Context around matches
  • When using --rewrite, shows diff of changes

Integration with os-tk workflow

  • Can be invoked from os-tk-worker when a ticket requires structural refactoring
  • Can be used by os-tk-review roles to find code patterns (e.g., “all functions calling X”)
  • Results can be captured and included in review notes or proposals

Installation

bash
# macOS
brew install ast-grep

# Linux (via cargo)
cargo install ast-grep

# Nix
nix-env -iA nixpkgs.ast-grep

Examples

Find all async functions without try/catch

bash
ast-grep -p "async fn $NAME($$$ARGS) $$BODY" -l rust | xargs rg -v "try|catch"

Replace var with let in JavaScript

bash
ast-grep -p "var $NAME = $VALUE" -r "let $NAME = $VALUE" -l js

Find all React useEffect calls

bash
ast-grep -p "useEffect($$$EFFECT, $$DEPS?)" -l ts,tsx

Notes

  • ast-grep uses tree-sitter parsers for accurate syntax understanding
  • Slower than rg for simple text searches – use it only when structural matching matters
  • Supports 20+ languages (see ast-grep --languages)