Home / Market / ast grep codemods

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.

skill★ 508220 dlgithubCC-BY-4.0 content; MIT code; upstream exceptions applyInstall in CosmosUpstream Source

Documentation & Preview

--- name: ast-grep-codemods description: "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." category: development risk: critical source: self source_type: self date_added: "2026-11-30" author: ShianMike tags: [ast-grep, tree-sitter, codemod, refactoring, static-analysis]

---

ast-grep Codemods

When to Use

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

  1. Use Tree-sitter metavariables: $VAR matches a single AST node (an identifier, expression, or literal), $$$ARGS matches zero or more sibling nodes (such as variadic argument lists), and $_ matches an anonymous node without capturing.
  2. When writing YAML rule files (rule.yml), quote any pattern or fix value that contains : or braces (for example fix: "apiClient.request({ url: $URL, options: $OPTS })"). Unquoted colons inside object literals cause YAML parse errors.
  3. Narrow broad matches with relational clauses (inside, has, not) and constraints so only genuine call sites match (for example excluding the helper's own definition or test mocks).
  4. 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

Example

> Migrate multi-line legacyFetch(url, opts) calls in TypeScript to apiClient.request({ url, options }) without altering comments or string literals that mention legacyFetch.

Run the worked TypeScript structural rewrite to verify the quoted YAML rule, dry-run diff output, and --update-all result.

Limitations

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