Skip to main content

Module ast_edit

Module ast_edit 

Source
Expand description

AST-aware structural code rewriting tool (ast-grep backed). AST-edit tool — structural code rewriting via the sg (ast-grep) CLI.

Like the ast_grep search tool but applies pattern-driven rewrites. Accepts an array of { pat, out } operations applied against a list of files / directories / globs.

§Empirical CLI behavior (verified against ast-grep 0.45.0)

  • sg does not expand shell globs in positional path args: sg -p P --json 'src/**/*.rs' errors with No such file or directory. This tool expands globs via the glob crate before invoking sg.
  • -U (--update-all) is silently ignored when --json is set: the process exits 0, prints JSON, and the file is untouched. We therefore drop --json for the apply pass.
  • With -U and no --json, sg writes changes in place AND prints Applied N changes on stderr — so we get the replacement count without a second dry-run pass.
  • --json=stream emits one JSON object per match per line on stdout, making it cheap to count and group by file.
  • sg accepts any number of positional paths (directories + concrete files + globs-expanded files) in a single invocation, so we issue one process per (op × path-chunk) and never loop over individual paths.

§Modes

  • dry_run=true (default) — previews via sg -p P -r R --json=stream. No files are modified; counts come from stdout line count.
  • dry_run=false — applies via sg -p P -r R -U. Counts come from the Applied N changes line on stderr.

Structs§

AstEditTool
AstEditTool — wraps the sg (ast-grep) CLI for structural rewriting.