ast-grep-codemods
БесплатноБез исполняемых скриптовНе проверенSearch and refactor code structurally with ast-grep (Tree-sitter AST rules). Replace multi-line call sites without corrupting comments or strings, preview…
от sickn33★ 50 670 звёзд на GitHubОб этом скилле
ast-grep Codemods
When to Use
- Migrate deprecated APIs, rename call signatures, or enforce structural lint rules across many files where regex search-and-replace breaks on multi-line arguments, comments, or string literals.
- Author reusable YAML
ast-greprules withpattern,fix,not, orinsideconstraints. - Preview and apply repeatable repository-wide codemods safely with dry-run diffs before writing files.
Prerequisites
Verify ast-grep (sg or ast-grep) is installed and check its version (ast-grep --version), target languages, and git working-tree cleanliness. Keep edits in a clean git branch so codemod diffs can be reviewed and reverted cleanly.
Author structural patterns instead of regexes
- Use Tree-sitter metavariables:
$VARmatches a single AST node (an identifier, expression, or literal),$$$ARGSmatches zero or more sibling nodes (such as variadic argument lists), and$_matches an anonymous node without capturing. - When writing YAML rule files (
rule.yml), quote anypatternorfixvalue that contains:or braces (for examplefix: "apiClient.request({ url: $URL, options: $OPTS })"). Unquoted colons inside object literals cause YAML parse errors. - Narrow broad matches with relational clauses (
inside,has,not) andconstraintsso only genuine call sites match (for example excluding the helper's own definition or test mocks). - Inspect ambiguous syntax with
ast-grep run --debug-query=ast -l <lang> -p '<snippet>'when a pattern fails to match the expected AST node kind.
Preview, apply, and verify codemods
- Always run a read-only preview first:
ast-grep scan --rule rule.yml <paths>(or--json=compactto audit match counts) and inspect the proposed diff before modifying source files. - Apply changes only after verifying the preview (
--update-all, or-ifor interactive review on risky refactors). - Follow every applied codemod with the project's formatter, type checker, and test suite.
ast-greprewrites syntax structurally; it does not resolve cross-file types or imports automatically unless your rule explicitly handles them.
Example
Migrate multi-line
legacyFetch(url, opts)calls in TypeScript toapiClient.request({ url, options })without altering comments or string literals that mentionlegacyFetch.
Run the worked TypeScript structural rewrite to verify the quoted YAML rule, dry-run diff output, and --update-all result.
Limitations
ast-grepmatches syntax trees per file, not semantic symbol tables or resolved TypeScript/Rust types; a different function with the same local name can match unless constrained by context or import checks.- Rewritten multi-line expressions may need a follow-up pass from the project formatter (such as Biome, Prettier, or
rustfmt).
Safety and Side Effects
Always start with a clean git working tree and run ast-grep scan without --update-all first. Limit target paths to authorized source directories so generated bundles, vendored dependencies, or fixtures are not rewritten unintentionally.
Related Skills and Documentation
- For deciding refactor scope, risk tiers, and domain boundaries before editing, see Repo-Native Refactor.
- For behavior-preservation checklists during cleanup, see Codebase Cleanup Refactor.
- See the official ast-grep documentation, rule configuration guide, and metavariable reference.
Установить ast-grep-codemods в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл ast-grep-codemods?
Search and refactor code structurally with ast-grep (Tree-sitter AST rules). Replace multi-line call sites without corrupting comments or strings, preview diffs first, and verify YAML rules.
Как установить скилл ast-grep-codemods?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл ast-grep-codemods запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic