본문으로 건너뛰기
Skillpedia
일반 코딩70k · #3128

ast-grep

하는 일

ast-grep은 여러 언어의 코드를 검색하고 수정하는 도구입니다. 단순한 텍스트가 아니라 코드 구조를 이해해서 특정 패턴을 찾거나 변경합니다.

사용하는 경우

  • ✓특정 매개변수를 받는 모든 함수를 찾을 때.
  • ✓여러 파일에서 한 코드 조각을 다른 코드로 바꿀 때.
  • ✓코드가 특정 구조 규칙을 따르는지 확인하는 경우.

스킬 링크

https://github.com/code-yeongyu/oh-my-openagent/blob/dev/packages/shared-skills/skills/ast-grep/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/code-yeongyu/oh-my-openagent/blob/dev/packages/shared-skills/skills/ast-grep/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“제 TypeScript 프로젝트에서 모든 `console.log` 호출을 찾아 `logger.info`로 바꿔 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

코드 구조를 이해하는 언어를 사용해 찾거나 바꾸고 싶은 것을 설명합니다. 도구는 코드를 실제 코드처럼 분석하고 필요한 수정을 합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

ast-grep

sg (also installed as ast-grep) is an AST-aware search and rewrite tool across 25 languages. It treats your pattern as code, parses it the same way it parses your project, and matches structurally. It is the right tool whenever your question depends on code shape rather than text bytes.

This skill ships a Python wrapper at scripts/ast_grep_helper.py and platform install scripts at install.sh (POSIX) and install.ps1 (Windows). The helper adds offline pattern validation, the two-pass write trick, and binary auto-resolution. Use it as your default entry point.


OmO native: the ast-grep MCP tools (fastest path, no CLI needed)

OmO native also registers a bundled ast-grep MCP server. Its three tools are deferred: they are absent from the resident tool list and activate automatically the first time you call them by name — no tool_search round trip needed.

  • mcp__ast_grep_search({ pattern, language, paths }) — AST-shape search, the MCP equivalent of sg run -p. Prefer this over shelling out to sg for one-off lookups: no install, no PATH issues.
  • mcp__ast_grep_rewrite({ pattern, rewrite, language, paths, apply }) — preview matches (apply: false, the default) or apply the rewrite (apply: true). Same two-pass discipline as sg run -r: preview first, then apply.
  • mcp__ast_grep_scan({ paths }) — run project YAML rules (sgconfig.yml, rules/), the MCP equivalent of sg scan.

Same pattern language as the CLI: $VAR matches one AST node, $$$VAR matches zero or more, and the pattern is code, not regex. paths accepts a file or directory list; language is required for patterns that are ambiguous across languages.


When to use this skill

Use it whenever the user's question is about code structure, not bytes:

  • "Find every function that takes a Request parameter."
  • "Rewrite every console.log(x) to logger.info(x)."
  • "Strip every as any cast."
  • "Replace require(...) with import across the repo."
  • "Find empty catch blocks."
  • "Migrate Optional[X] to X | None."
  • "Apply this codemod across these 200 files."
  • "Run our YAML lint rules and surface violations."

Switch to plain grep / rg when the question is text-shaped (string literal contents, comments, license headers, file names, cross-language regex). When in doubt, ask: "does the answer depend on the language's syntax tree, or just on the file's bytes?" If the former, ast-grep. If the latter, grep.


Three things the agent must internalize

1. ast-grep is NOT regex

The wildcards are $VAR (one AST node) and $$$ (zero or more nodes). Regex syntax fails silently:

You wrote What ast-grep saw What you wanted
foo|bar bitwise-or of foo and bar run two separate searches
.*foo not parseable $$$ foo (if $$$ is a list of nodes) or use rg
\w+ not parseable $VAR to capture any identifier
[a-z] character class, not parseable switch to rg

The full anti-pattern table is in references/pitfalls.md §1. The helper's validate subcommand catches these mechanically — call it before debugging "no matches" by hand.

2. Patterns must be valid code

The pattern itself must parse. def $FN($$$): fails because the trailing : makes it incomplete; use def $FN($$$). function $NAME without params/body fails; use function $NAME($$$) { $$$ }. Full table per language in references/pitfalls.md §2.

3. --update-all and --json are mutually exclusive (silently)

This is the single biggest gotcha when scripting. sg run -p P -r R --json --update-all returns the JSON but does not mutate files. To both preview AND apply, run two passes:

sg run -p P -r R --json=compact .   # pass 1: see what would change
sg run -p P -r R --update-all .     # pass 2: actually apply

The helper does this automatically when you call replace --apply. Read references/pitfalls.md §9.


The helper script — scripts/ast_grep_helper.py

A single-file Python 3 stdlib wrapper. Same on every OS. The agent's default entry point.

search — find all matches of a pattern

python3 scripts/ast_grep_helper.py search 'console.log($MSG)' --lang ts src/

Validates the pattern offline first. If the pattern looks like regex (\w, .*, |, etc.) the helper exits with a hint and never calls sg — saves a round-trip. Pass --force to skip validation.

Flags:

…

자주 묻는 질문

ast-grep과 grep(또는 정규 표현식)의 차이는 무엇인가요?

grep과 정규 표현식은 텍스트를 문자의 연속으로 봅니다. ast-grep은 코드 구조(함수, 변수 등)를 이해해서 코드 모양에 기반한 더 정밀한 검색과 수정을 가능하게 합니다.

`$VAR`과 `$$$` 문자는 무엇인가요?

`$VAR`은 코드 구조의 일부(변수나 함수 이름 등)를 잡아내는 데 쓰입니다. `$$$`는 0개 이상의 코드 구조 부분을 잡아내는 데 쓰입니다.

찾은 변경 사항은 어떻게 적용하나요?

먼저 변경 사항 미리보기(dry-run)를 볼 수 있고, 그다음 적용 옵션을 붙여 명령을 다시 실행해 실제로 파일을 수정합니다.

상세 정보

작성자의 원본 설명

Searches and rewrites code by AST shape across 25 languages. Use when the target is a syntax pattern (every call/class/import shaped like X, a codemod, a YAML rule) rather than literal text; for plain strings, comments, or filenames, use rg.

repo: code-yeongyu/oh-my-openagent

인기도

GitHub 스타
70k
순위
#3128
라이선스
NOASSERTION
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬