Token导航 LogoToken导航TokenDH.com
研究检索执行命令github未标认证来源可访问许可证需确认审计通过

ast-grep搜索结果 grep

Agent Skill

ast-grep 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

1,697

周安装

70

GitHub Stars

67

下载量

554
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:ast-grep(搜索结果 grep)
来源仓库:https://github.com/ampcode/amp-contrib
仓库路径:skills/ast-grep
安装命令:
npx skills add https://github.com/ampcode/amp-contrib --skill ast-grep
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/ampcode/amp-contrib --skill ast-grep

简介

ast-grep 帮助将自然语言查询转换为 ast-grep 规则,实现基于抽象语法树的结构化代码搜索。

  • 适用于需要匹配代码模式、定位语言构造或搜索特定参数调用的场景。
  • 支持精确的结构匹配而非仅文本匹配,适用于大型代码库搜索。
  • 安装命令:npx skills add https://github.com/ampcode/amp-contrib --skill ast-grep。
  • 使用前请确认代码库规模和搜索模式的复杂度要求。

SKILL.md

ast-grep Code Search

Overview

This skill helps translate natural language queries into ast-grep rules for structural code search. ast-grep uses Abstract Syntax Tree (AST) patterns to match code based on its structure rather than just text, enabling powerful and precise code search across large codebases.

When to Use This Skill

Use this skill when users:

  • Need to search for code patterns using structural matching (e.g., "find all async functions that don't have error handling")
  • Want to locate specific language constructs (e.g., "find all function calls with specific parameters")
  • Request searches that require understanding code structure rather than just text
  • Ask to search for code with particular AST characteristics
  • Need to perform complex code queries that traditional text search cannot handle

General Workflow

Follow this process to help users write effective ast-grep rules:

Step 1: Understand the Query

Clearly understand what the user wants to find. Ask clarifying questions if needed:

  • What specific code pattern or structure are they looking for?
  • Which programming language?
  • Are there specific edge cases or variations to consider?
  • What should be included or excluded from matches?

Step 2: Create Example Code

Write a simple code snippet that represents what the user wants to match. Save this to a temporary file for testing.

Example: If searching for "async functions that use await", create a test file:

// test_example.js
async function example() {
	const result = await fetchData()
	return result
}

Step 3: Write the ast-grep Rule

Translate the pattern into an ast-grep rule. Start simple and add complexity as needed.

Key principles:

  • Always use stopBy: end for relational rules (inside, has) to ensure search goes to the end of the direction
  • Use pattern for simple structures
  • Use kind with has/inside for complex structures
  • Break complex queries into smaller sub-rules using all, any, or not

Example rule file (test_rule.yml):

id: async-with-await
language: javascript
rule:
  kind: function_declaration
  has:
    pattern: await $EXPR
    stopBy: end

See references/rule_reference.md for comprehensive rule documentation.

Step 4: Test the Rule

Use ast-grep CLI to verify the rule matches the example code. There are two main approaches:

Option A: Test with inline rules (for quick iterations)

echo "async function test() { await fetch(); }" | ast-grep scan --inline-rules "id: test
language: javascript
rule:
  kind: function_declaration
  has:
    pattern: await \$EXPR
    stopBy: end" --stdin

Option B: Test with rule files (recommended for complex rules)

ast-grep scan --rule test_rule.yml test_example.js

Debugging if no matches:

  1. Simplify the rule (remove sub-rules)
  2. Add stopBy: end to relational rules if not present
  3. Use --debug-query to understand the AST structure (see below)
  4. Check if kind values are correct for the language

Step 5: Search the Codebase

Once the rule matches the example code correctly, search the actual codebase:

For simple pattern searches:

ast-grep run --pattern 'console.log($ARG)' --lang javascript /path/to/project

For complex rule-based searches:

ast-grep scan --rule my_rule.yml /path/to/project

For inline rules (without creating files):

ast-grep scan --inline-rules "id: my-rule
language: javascript
rule:
  pattern: \$PATTERN" /path/to/project

Rewriting Code with ast-grep

ast-grep is a powerful AST-based tool that can search for code patterns and transform them into new code. It works like a syntax-aware sed/grep that understands code structure rather than just text.

Method 1: Command Line with --rewrite

The simplest approach is using the --rewrite (or -r) flag directly in your terminal:

ast-grep run --pattern 'foo' --rewrite 'bar' --lang python

This finds all occurrences of foo and replaces them with bar. A practical example:

# Convert old-style property checks to optional chaining
ast-grep -p '$PROP && $PROP()' --rewrite '$PROP?.()' --interactive -l ts ./src

Key flags:

  • --interactive or -i: Review each change before applying
  • --update-all or -U: Apply all changes without confirmation

Method 2: YAML Rules with fix

For more complex transformations, use YAML rule files with the fix field:

id: change_def
language: Python
rule:
  pattern: |
    def foo($X):
      $$$S
fix: |-
  def baz($X):
    $$$S

Run with: ast-grep scan -r rule.yml./src

Meta-Variables

Meta-variables are the key to powerful rewrites. They act like capture groups in regex:

Meta-variableMatches
$NAMEAny single AST node (expression, identifier, etc.)
$$$ITEMSMultiple nodes (like function arguments)

Example — Swapping assignment sides:

rule:
  pattern: $X = $Y
fix: $Y = $X

Transforms a = b into b = a.

Indentation Sensitivity

ast-grep preserves indentation in rewrites. If your fix template has indentation, it's maintained relative to the original code position:

rule:
  pattern: '$B = lambda: $R'
fix: |-
  def $B():
    return $R

Expanding the Match Range with FixConfig

Sometimes you need to delete surrounding characters (like commas). Use FixConfig with expandStart and expandEnd:

rule:
  kind: pair
  has:
    field: key
    regex: Remove
fix:
  template: ''
  expandEnd: { regex: ',' } # Also deletes trailing comma

This removes the matched node *plus* any trailing comma.

Advanced Features: Rewriters

For complex multi-node transformations, use rewriters to process lists of matched nodes:

id: barrel-to-single
language: JavaScript
rule:
  pattern: import {$$$IDENTS} from './module'
rewriters:
  - id: rewrite-identifier
    rule:
      pattern: $IDENT
      kind: identifier
    transform:
      LIB: { convert: { source: $IDENT, toCase: lowerCase } }
    fix: import $IDENT from './module/$LIB'
transform:
  IMPORTS:
    rewrite:
      rewriters: [rewrite-identifier]
      source: $$$IDENTS
      joinBy: "\n"
fix: $IMPORTS

This converts barrel imports like import {A, B} from './module' into individual imports.

Workflow Summary

  1. Find: Use patterns to match AST nodes
  2. Capture: Meta-variables ($VAR, $$$ARGS) capture matched content
  3. Transform: Optionally process captured content (case conversion, regex replacement)
  4. Patch: Replace matched nodes with the fix template

Tips

  • Use single quotes on command line to prevent shell expansion of $
  • Non-matched meta-variables become empty strings in the fix

ast-grep CLI Commands

Inspect Code Structure (--debug-query)

Dump the AST structure to understand how code is parsed:

ast-grep run --pattern 'async function example() { await fetch(); }' \
  --lang javascript \
  --debug-query=cst

Available formats:

  • cst: Concrete Syntax Tree (shows all nodes including punctuation)
  • ast: Abstract Syntax Tree (shows only named nodes)
  • pattern: Shows how ast-grep interprets your pattern

Use this to:

  • Find the correct kind values for nodes
  • Understand the structure of code you want to match
  • Debug why patterns aren't matching

Example:

# See the structure of your target code
ast-grep run --pattern 'class User { constructor() {} }' \
  --lang javascript \
  --debug-query=cst

# See how ast-grep interprets your pattern
ast-grep run --pattern 'class $NAME { $$$BODY }' \
  --lang javascript \
  --debug-query=pattern

Test Rules (scan with --stdin)

Test a rule against code snippet without creating files:

echo "const x = await fetch();" | ast-grep scan --inline-rules "id: test
language: javascript
rule:
  pattern: await \$EXPR" --stdin

Add --json for structured output:

echo "const x = await fetch();" | ast-grep scan --inline-rules "..." --stdin --json

Search with Patterns (run)

Simple pattern-based search for single AST node matches:

# Basic pattern search
ast-grep run --pattern 'console.log($ARG)' --lang javascript .

# Search specific files
ast-grep run --pattern 'class $NAME' --lang python /path/to/project

# JSON output for programmatic use
ast-grep run --pattern 'function $NAME($$$)' --lang javascript --json .

When to use:

  • Simple, single-node matches
  • Quick searches without complex logic
  • When you don't need relational rules (inside/has)

Search with Rules (scan)

YAML rule-based search for complex structural queries:

# With rule file
ast-grep scan --rule my_rule.yml /path/to/project

# With inline rules
ast-grep scan --inline-rules "id: find-async
language: javascript
rule:
  kind: function_declaration
  has:
    pattern: await \$EXPR
    stopBy: end" /path/to/project

# JSON output
ast-grep scan --rule my_rule.yml --json /path/to/project

When to use:

  • Complex structural searches
  • Relational rules (inside, has, precedes, follows)
  • Composite logic (all, any, not)
  • When you need the power of full YAML rules

Tip: For relational rules (inside/has), always add stopBy: end to ensure complete traversal.

Tips for Writing Effective Rules

Always Use stopBy: end

For relational rules, always use stopBy: end unless there's a specific reason not to:

has:
  pattern: await $EXPR
  stopBy: end

This ensures the search traverses the entire subtree rather than stopping at the first non-matching node.

Start Simple, Then Add Complexity

Begin with the simplest rule that could work:

  1. Try a pattern first
  2. If that doesn't work, try kind to match the node type
  3. Add relational rules (has, inside) as needed
  4. Combine with composite rules (all, any, not) for complex logic

Use the Right Rule Type

  • Pattern: For simple, direct code matching (e.g., console.log($ARG))
  • Kind + Relational: For complex structures (e.g., "function containing await")
  • Composite: For logical combinations (e.g., "function with await but not in try-catch")

Debug with AST Inspection

When rules don't match:

  1. Use --debug-query=cst to see the actual AST structure
  2. Check if metavariables are being detected correctly
  3. Verify the node kind matches what you expect
  4. Ensure relational rules are searching in the right direction

Escaping in Inline Rules

When using --inline-rules, escape metavariables in shell commands:

  • Use \$VAR instead of $VAR (shell interprets $ as variable)
  • Or use single quotes: '$VAR' works in most shells

Example:

# Correct: escaped $
ast-grep scan --inline-rules "rule: {pattern: 'console.log(\$ARG)'}" .

# Or use single quotes
ast-grep scan --inline-rules 'rule: {pattern: "console.log($ARG)"}' .

Common Use Cases

Find Functions with Specific Content

Find async functions that use await:

ast-grep scan --inline-rules "id: async-await
language: javascript
rule:
  all:
    - kind: function_declaration
    - has:
        pattern: await \$EXPR
        stopBy: end" /path/to/project

Find Code Inside Specific Contexts

Find console.log inside class methods:

ast-grep scan --inline-rules "id: console-in-class
language: javascript
rule:
  pattern: console.log(\$\$\$)
  inside:
    kind: method_definition
    stopBy: end" /path/to/project

Find Code Missing Expected Patterns

Find async functions without try-catch:

ast-grep scan --inline-rules "id: async-no-trycatch
language: javascript
rule:
  all:
    - kind: function_declaration
    - has:
        pattern: await \$EXPR
        stopBy: end
    - not:
        has:
          pattern: try { \$\$\$ } catch (\$E) { \$\$\$ }
          stopBy: end" /path/to/project

Resources

references/

Contains detailed documentation for ast-grep rule syntax:

  • rule_reference.md: Comprehensive ast-grep rule documentation covering atomic rules, relational rules, composite rules, and metavariables

Load these references when detailed rule syntax information is needed.

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

35.11%
按下载量换算195

Claude

28.01%
按下载量换算155

Cursor

19.2%
按下载量换算106

Gemini CLI

8.98%
按下载量换算50

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

执行命令

安装流程涉及命令执行,可能通过 npx skills add https://github.com/ampcode/amp-contrib --skill ast-grep 联网下载 Skill 或依赖。用户安装前应确认命令来源、仓库内容和执行环境。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills