github.com/amarpal/go-tools@v0.0.0-20240422043104-40142f59f616/generate.go (about) 1 //go:build ignore 2 3 package main 4 5 import ( 6 "bytes" 7 "go/format" 8 "log" 9 "os" 10 "path/filepath" 11 "regexp" 12 "text/template" 13 ) 14 15 var tmpl = ` 16 {{define "analyzers"}} 17 // Code generated by generate.go. DO NOT EDIT. 18 19 package {{.dir}} 20 21 import ( 22 "github.com/amarpal/go-tools/analysis/lint" 23 {{- range $check := .checks}} 24 "github.com/amarpal/go-tools/{{$.dir}}/{{$check}}" 25 {{- end}} 26 ) 27 28 var Analyzers = []*lint.Analyzer{ 29 {{- range $check := .checks}} 30 {{$check}}.SCAnalyzer, 31 {{- end}} 32 } 33 {{end}} 34 35 {{define "tests"}} 36 // Code generated by generate.go. DO NOT EDIT. 37 38 package {{.check}} 39 40 import ( 41 "testing" 42 43 "github.com/amarpal/go-tools/analysis/lint/testutil" 44 ) 45 46 func TestTestdata(t *testing.T) { 47 testutil.Run(t, SCAnalyzer) 48 } 49 {{end}} 50 ` 51 52 func main() { 53 log.SetFlags(0) 54 55 dir, err := os.Getwd() 56 if err != nil { 57 log.Fatalln("couldn't determine current directory:", err) 58 } 59 60 dir = filepath.Base(dir) 61 62 var t template.Template 63 if _, err = t.Parse(tmpl); err != nil { 64 log.Fatalln("couldn't parse templates:", err) 65 } 66 67 dirs, err := filepath.Glob("*") 68 if err != nil { 69 log.Fatalln("couldn't enumerate checks:", err) 70 } 71 72 checkRe := regexp.MustCompile(`^[a-z]+\d{4}$`) 73 out := dirs[:0] 74 for _, dir := range dirs { 75 if checkRe.MatchString(dir) { 76 out = append(out, dir) 77 } 78 } 79 dirs = out 80 81 buf := bytes.NewBuffer(nil) 82 83 if err := t.ExecuteTemplate(buf, "analyzers", map[string]any{"checks": dirs, "dir": dir}); err != nil { 84 log.Fatalln("couldn't generate analysis.go:", err) 85 } 86 87 b, err := format.Source(buf.Bytes()) 88 if err != nil { 89 log.Fatalln("couldn't gofmt analysis.go:", err) 90 } 91 if err := os.WriteFile("analysis.go", b, 0666); err != nil { 92 log.Fatalln("couldn't write analysis.go:", err) 93 } 94 95 for _, dir := range dirs { 96 buf.Reset() 97 dst := filepath.Join(dir, dir+"_test.go") 98 if err := t.ExecuteTemplate(buf, "tests", map[string]any{"check": dir}); err != nil { 99 log.Fatalf("couldn't generate %s: %s", dst, err) 100 } 101 102 b, err := format.Source(buf.Bytes()) 103 if err != nil { 104 log.Fatalf("couldn't gofmt %s: %s", dst, err) 105 } 106 if err := os.WriteFile(dst, b, 0666); err != nil { 107 log.Fatalf("couldn't write %s: %s", dst, err) 108 } 109 } 110 }