Saltar al contenido
Skillpedia
Programación general70 mil · #3128

ast-grep

Qué hace

ast-grep es una herramienta que busca y modifica código en muchos lenguajes. Entiende la estructura del código, no solo el texto, para encontrar patrones concretos o hacer cambios.

Cuándo usarla

  • ✓Para encontrar todas las funciones que reciben un parámetro concreto.
  • ✓Para sustituir un fragmento de código por otro en varios archivos.
  • ✓Para comprobar si el código sigue ciertas reglas de estructura.

Link de la skill

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

Cópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.

Cómo usar

La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.

Mensaje listo para pegar

Usa esta skill para ayudarme: https://github.com/code-yeongyu/oh-my-openagent/blob/dev/packages/shared-skills/skills/ast-grep/SKILL.md Lee el archivo SKILL.md de ese link y sigue sus instrucciones en mi tarea.
¿Quieres que tu IA encuentre skills como esta por sí sola?Instala el MCP gratis de Skillpedia: una línea, y busca entre 15.000+ skills antes de cada tarea.Instalar en 1 minuto →

Ejemplo de qué pedirle a la IA

“Busca todas las llamadas a `console.log` y cámbialas por `logger.info` en mi proyecto de TypeScript.”

5 skills nuevas por semana. 1 minuto de lectura.

Cómo funciona

Describes lo que quieres encontrar o cambiar usando un lenguaje que entiende la estructura del código. La herramienta analiza tu código como código real y hace las modificaciones necesarias.

Contenido técnico (SKILL.md original)

Texto original del autor, en inglés, directo de 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:

…

Preguntas frecuentes

¿Cuál es la diferencia entre ast-grep y grep (o las expresiones regulares)?

grep y las expresiones regulares miran el texto como una secuencia de caracteres. ast-grep entiende la estructura del código (como funciones, variables, etc.), lo que permite búsquedas y cambios más precisos según la forma del código.

¿Qué son los caracteres `$VAR` y `$$$`?

`$VAR` sirve para capturar una parte de la estructura del código (como un nombre de variable o de función). `$$$` sirve para capturar cero o más partes de la estructura del código.

¿Cómo aplico los cambios que encontré?

Primero puedes ver una vista previa de los cambios (simulación o dry-run) y después ejecutar el comando de nuevo con la opción de aplicar para modificar los archivos de verdad.

Detalles

Descripción original del autor

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

Popularidad

Estrellas en GitHub
70 mil
Posición en el ranking
#3128
Licencia
NOASSERTION
Actualizada
15/10/2026

¿Te sirve esta skill?

0

Entra para votar.

Comentarios

  • …

Más skills de este repositorio

Skills parecidas