Find function declarations with names of certain pattern
Description
ast-grep can find function declarations by their names. But not all names can be matched by a meta variable pattern. For instance, you cannot use a meta variable pattern to find function declarations whose names start with a specific prefix, e.g. TestAbs
with the prefix Test
. Attempting Test$_
will fail because it is not a valid syntax.
Instead, you can use a YAML rule to use the regex
atomic rule.
YAML
yaml
id: test-functions
language: go
rule:
kind: function_declaration
has:
field: name
regex: Test.*
Example
go
package abs
import "testing"
func TestAbs(t *testing.T) {
got := Abs(-1)
if got != 1 {
t.Errorf("Abs(-1) = %d; want 1", got)
}
}
Contributed by
kevinkjt2000 on Discord.