Search code examples
searchreplacecommand-lineabstract-syntax-treeast-grep

How to apply ast-grep rewrite rules to a file automatically?


I am using ast-grep, a CLI tool for code structural search and rewriting, to find and replace some patterns in my code. I have written a YAML file with some rewrite rules, and I can use sg scan to see the matches and replacements in the terminal. However, I am not sure how to apply the changes to the original file automatically, without manually editing it.

Here is an example of my YAML file rule.yaml:

id: replace-var-with-let
language: js
rule:
  pattern: var $A = $B
fix: let $A = $B

Here is an example of my test file test.js:

var x = 10;
var y = 20;
var z = x + y;
console.log(z);

Here is the output of sg scan:

sg scan -r rule.yaml test.js
test.js
help[replace-var-with-let]:
@@ -0,4 +0,4 @@
1  │-var x = 10;
  1│+let x = 10
2 2│ var y = 20;
3 3│ var z = x + y;
4 4│ console.log(z);
help[replace-var-with-let]:
@@ -0,4 +0,4 @@
1 1│ var x = 10;
2  │-var y = 20;
  2│+let y = 20
3 3│ var z = x + y;
4 4│ console.log(z);
help[replace-var-with-let]:
@@ -0,4 +0,4 @@
1 1│ var x = 10;
2 2│ var y = 20;
3  │-var z = x + y;
  3│+let z = x + y
4 4│ console.log(z);

How can I make ast-grep modify the code file directly, so that it becomes:

let x = 10;
let y = 20;
let z = x + y;
console.log(z);

I am using ast-grep version 0.19.0, JavaScript as the programming language, and Mac OSX as the operating system.


Solution

  • ast-grep will not modify the file directly, but it will print the modified code to the terminal. You can use the --update-all or -U flag to write the changes to the file. see the rewrite guide. This is similar to eslint --fix option or prettier -w

    Here is the command to apply the changes to the file:

    $ sg scan -r rule.yaml test.js -U
    # or 
    $ sg scan -r rule.yaml test.js --update-all
    

    For more information, you can check out the command line references

    https://ast-grep.github.io/reference/cli/scan.html#u-update-all