ast-grep

Creates ast-grep patterns for structural code search. Use when finding functions/classes by structure, refactoring code, or when grep returns too many false positives.

9 stars

Best use case

ast-grep is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Creates ast-grep patterns for structural code search. Use when finding functions/classes by structure, refactoring code, or when grep returns too many false positives.

Teams using ast-grep should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/ast-grep/SKILL.md --create-dirs "https://raw.githubusercontent.com/ssiumha/dots/main/prompts/skills/ast-grep/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/ast-grep/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How ast-grep Compares

Feature / Agentast-grepStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Creates ast-grep patterns for structural code search. Use when finding functions/classes by structure, refactoring code, or when grep returns too many false positives.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# ast-grep Patterns

AST 기반 구조적 코드 검색을 지원합니다. 텍스트 매칭이 아닌 코드 구조로 정밀 검색.

**핵심 철학**:
- 구조적 검색: 코드의 의미 단위로 검색 (변수명, 함수 시그니처 등)
- 노이즈 제거: 주석, 공백, 포맷 차이 무시
- 언어 인식: 각 언어의 AST 구조에 맞는 패턴
- Grep 대체: 복잡한 정규식 대신 직관적 패턴

## Instructions

### 워크플로우 1: 패턴 작성

사용자 요청에서 파악:
1. **언어**: TypeScript, Python, Go, Rust 등
2. **대상**: 함수, 클래스, import, 변수 등
3. **조건**: 특정 이름, 패턴, 구조

기본 명령:
```bash
ast-grep --lang <language> -p '<pattern>'
```

### 워크플로우 2: 메타변수 활용

| 메타변수 | 의미 | 예시 |
|----------|------|------|
| `$NAME` | 단일 노드 캡처 | `function $NAME()` |
| `$_` | 단일 노드 (무시) | `import { $_ } from "react"` |
| `$$$` | 0개 이상 노드 | `function $NAME($$$) { $$$ }` |
| `$$ARGS` | 이름 붙인 다중 캡처 | `console.log($$ARGS)` |

### 워크플로우 3: 언어별 패턴

요청 언어에 따라 적절한 패턴 제공:

| 언어 | 확장자 | --lang 값 |
|------|--------|-----------|
| TypeScript | .ts, .tsx | typescript, tsx |
| JavaScript | .js, .jsx | javascript, jsx |
| Python | .py | python |
| Go | .go | go |
| Rust | .rs | rust |
| Java | .java | java |

## Quick Reference

### 필수 옵션

```bash
--lang <lang>       # 언어 지정 (필수)
-p '<pattern>'      # 패턴 (필수)
--json              # JSON 출력
-r '<replacement>'  # 대체 문자열
--rewrite           # 실제 파일 수정
-i                  # 대화형 모드
```

### 자주 쓰는 패턴

```bash
# 함수 정의
ast-grep --lang typescript -p 'function $NAME($$$) { $$$ }'

# 화살표 함수
ast-grep --lang typescript -p 'const $NAME = ($$$) => $$$'

# React 컴포넌트
ast-grep --lang tsx -p 'function $NAME($$$): JSX.Element { $$$ }'

# 특정 import
ast-grep --lang typescript -p 'import { $_ } from "react"'

# 클래스 정의
ast-grep --lang typescript -p 'class $NAME { $$$ }'

# console.log 찾기
ast-grep --lang javascript -p 'console.log($$$)'
```

## Examples

### 함수 찾기

**요청**: "fetchUser 함수 정의 위치"

```bash
ast-grep --lang typescript -p 'function fetchUser($$$) { $$$ }'
# 또는 화살표 함수도 포함
ast-grep --lang typescript -p 'const fetchUser = $$$'
```

### React Hook 사용 찾기

**요청**: "useState 사용하는 곳"

```bash
ast-grep --lang tsx -p 'const [$_, $_] = useState($$$)'
```

### API 엔드포인트 찾기

**요청**: "Express 라우트 핸들러"

```bash
ast-grep --lang typescript -p 'app.$METHOD($$$)'
# 또는 특정 메서드
ast-grep --lang typescript -p 'app.get($$$)'
```

### Python 데코레이터

**요청**: "@property 사용하는 메서드"

```bash
ast-grep --lang python -p '
@property
def $NAME(self):
    $$$
'
```

### Go 구조체

**요청**: "Error 인터페이스 구현"

```bash
ast-grep --lang go -p 'func ($_ $_) Error() string { $$$ }'
```

### 리팩토링 (대체)

**요청**: "console.log를 logger.debug로 변경"

```bash
ast-grep --lang typescript -p 'console.log($$$ARGS)' -r 'logger.debug($$$ARGS)'
# 미리보기 후 적용
ast-grep --lang typescript -p 'console.log($$$ARGS)' -r 'logger.debug($$$ARGS)' --rewrite
```

## vs Grep

| 상황 | Grep | ast-grep | 이유 |
|------|------|----------|------|
| 단순 텍스트 | ✅ 빠름 | 불필요 | 구조 분석 오버헤드 |
| 함수 정의 | ❌ 노이즈 | ✅ 정확 | 주석/문자열 내 false positive 제거 |
| 변수 추적 | ❌ 혼동 | ✅ 인식 | AST로 스코프 구분 |
| 리팩토링 | ❌ 불가 | ✅ `-r` | 구조 보존 대체 |

**선택 기준**: 구조가 중요하면 ast-grep, 텍스트만 찾으면 Grep

## Technical Details

- **공식 문서**: https://ast-grep.github.io/
- **지원 언어**: TypeScript, JavaScript, Python, Go, Rust, Java, C, C++, Kotlin 등
- **설치**: `brew install ast-grep` 또는 `cargo install ast-grep`

**skill 호출 vs 직접 사용**:
- 직접 사용: 단일 메타변수, 표준 함수/클래스 검색
- skill 호출: 리팩토링 (-r), 언어별 특수 구문, 조건부 매칭

### 고급 기능 리소스
- `resources/advanced-rules.md`: YAML 룰 시스템, Relational Rules(inside/has/follows), 보안 스캐닝 룰, CI 통합

Related Skills

tree-sitter

9
from ssiumha/dots

AST parsing, S-expression queries, tag extraction via tree-sitter CLI. Use when parsing code into AST, extracting tags, visualizing syntax trees, or performing structural analysis beyond ast-grep.

tidy

9
from ssiumha/dots

Performs small structural code cleanups (tidyings). Use when preparing code changes, removing dead code, reducing nesting, or cleaning up before feature work.

task-naming

9
from ssiumha/dots

CLI command naming convention for Justfile and Makefile. Enforces GAT (group-action-target) word order, grouped listing, mandatory descriptions. Use when creating Justfile recipes, Makefile targets, or reviewing task runner configs for naming consistency. Also use when asking "what should I name this command?" for task runners. Do NOT use for npm scripts, mise tasks, or Claude Code skill naming.

strategic-thinking

9
from ssiumha/dots

체계적 의사결정 프레임워크. First Principles, Trade-off 분석, Cognitive Bias 점검

security

9
from ssiumha/dots

Security expert hub. Code security review (OWASP Top 10, injection, XSS, credentials), vulnerability assessment (KISA 292 items, Unix/Windows server, web pentest, network, DBMS, cloud), ISMS-P certification (101 items, checklist, implementation plan), EFSR financial regulation compliance (전자금융감독규정, 12 articles). 보안 리뷰, 취약점 점검, 인증 준비, 금융규정 준수.

reflect

9
from ssiumha/dots

방향 수정 신호 감지 및 세션 전체 회고. Use when detecting course correction signals ("아니/잠깐/근데"), session retrospective, or reviewing overall progress. /reflect 또는 "회고해줘"로 수동 호출.

refactoring

9
from ssiumha/dots

기존 코드의 안전한 리팩토링. Characterization Test로 동작 보존하며 구조 개선

recall

9
from ssiumha/dots

Load context from Obsidian vault (journals, session pages) and JSONL session history. Vault 위치/구조는 `documentation` skill 참조. Temporal queries scan JSONL by date, topic queries use ir BM25. Use when "recall", "어제 뭐 했지", "what did we work on", "이전 작업", "session history".

qmd

9
from ssiumha/dots

Searches local markdown notes and documents using ir CLI. Use when searching notes, querying documents, managing collections, or retrieving document content.

qa

9
from ssiumha/dots

기능별 QA 체크리스트 생성, 수동 테스트 실행, 결과 기록. Use when QA 테스트, 체크리스트 만들기, 수동 검증, 기능 확인, qa 진행, checklist. Do NOT use for automated test code (use plan-review tdd / code-review instead) or BDD spec (use plan-review bdd instead).

principles

9
from ssiumha/dots

소프트웨어 공학 원칙 바스켓. 원칙 카탈로그 열람, 코드/설계/프로세스/테스트의 원칙 준수도 평가, 위반 식별 및 개선 가이드. Use when 원칙 평가, 원칙 점검, 원칙 검증, principles check, 코드 품질 근본 진단, 설계 원칙 리뷰, 아키텍처 원칙 점검, 프로세스 원칙 점검, 테스트 원칙 점검, 테스트 설계, or when other review skills need a principled foundation. Do NOT use for specific code review (use code-review), security audit (use security), or strategic decisions (use strategic-thinking).

ppt

9
from ssiumha/dots

Generates PowerPoint architecture diagrams with auto-layout and orthogonal routing using PPTXGenJS. Use when creating AWS architecture diagrams, infrastructure layouts, system design slides, IDC 구성도, or any diagram that needs boxes with right-angle connectors in .pptx format. Also use when 아키텍처 다이어그램, 인프라 구성도, PPT 생성, 구성도 만들기, 슬라이드 자동 생성. Do NOT use for simple text-only presentations (use PowerPoint directly), data charts (use data-investigation), or ASCII/Mermaid diagrams (use diagram skill).