code-intelligence.com/cifuzz@v0.40.0/internal/cmdutils/node.go (about) 1 package cmdutils 2 3 import ( 4 "fmt" 5 "os" 6 "path/filepath" 7 "regexp" 8 "strings" 9 10 "github.com/mattn/go-zglob" 11 "github.com/pkg/errors" 12 13 "code-intelligence.com/cifuzz/util/regexutil" 14 ) 15 16 func ListNodeFuzzTests(projectDir string, prefixFilter string) ([]string, error) { 17 // use zglob to support globbing in windows 18 fuzzTestFiles, err := zglob.Glob(filepath.Join(projectDir, "**", "*.fuzz.*")) 19 if err != nil { 20 return nil, errors.WithStack(err) 21 } 22 23 var fuzzTests []string 24 for _, testFile := range fuzzTestFiles { 25 methods, err := getTargetMethodsFromNodeTestFile(testFile) 26 if err != nil { 27 return nil, err 28 } 29 30 fuzzTest := filepath.Base(testFile) 31 if strings.HasSuffix(fuzzTest, ".ts") { 32 fuzzTest = strings.TrimSuffix(fuzzTest, ".fuzz.ts") 33 } else { 34 fuzzTest = strings.TrimSuffix(fuzzTest, ".fuzz.js") 35 } 36 if len(methods) == 1 { 37 if prefixFilter == "" || strings.HasPrefix(testFile, prefixFilter) { 38 fuzzTests = append(fuzzTests, fuzzTest) 39 } 40 continue 41 } 42 43 for _, method := range methods { 44 fuzzTestIdentifier := fuzzTest + ":" + fmt.Sprintf("%q", method) 45 if prefixFilter == "" || strings.HasPrefix(fuzzTestIdentifier, prefixFilter) { 46 fuzzTests = append(fuzzTests, fuzzTestIdentifier) 47 } 48 } 49 } 50 51 return fuzzTests, nil 52 } 53 54 func getTargetMethodsFromNodeTestFile(path string) ([]string, error) { 55 bytes, err := os.ReadFile(path) 56 if err != nil { 57 return nil, errors.WithStack(err) 58 } 59 60 var targetMethods []string 61 fuzzTestRegex := regexp.MustCompile(`\.fuzz\s*\(\s*"(?P<fuzzTest>(\w|\s|\d)+)`) 62 matches, _ := regexutil.FindAllNamedGroupsMatches(fuzzTestRegex, string(bytes)) 63 for _, match := range matches { 64 targetMethods = append(targetMethods, match["fuzzTest"]) 65 } 66 67 return targetMethods, nil 68 }