github.com/prebid/prebid-server/v2@v2.18.0/modules/generator/buildergen.go (about) 1 //go:build ignore 2 3 package main 4 5 import ( 6 "bytes" 7 "fmt" 8 "go/format" 9 "io/fs" 10 "os" 11 "path/filepath" 12 "regexp" 13 "sort" 14 "strings" 15 "text/template" 16 ) 17 18 var ( 19 r = regexp.MustCompile("^([^/]+)/([^/]+)/module.go$") 20 tmplName = "builder.tmpl" 21 outName = "builder.go" 22 ) 23 24 func main() { 25 modules := make(map[string][]string) 26 27 filepath.WalkDir("./", func(path string, d fs.DirEntry, err error) error { 28 if !r.MatchString(path) { 29 return nil 30 } 31 match := r.FindStringSubmatch(path) 32 vendorModules := modules[match[1]] 33 vendorModules = append(vendorModules, match[2]) 34 modules[match[1]] = vendorModules 35 36 return nil 37 }) 38 39 for vendorName, names := range modules { 40 sort.Strings(names) 41 modules[vendorName] = names 42 } 43 44 funcMap := template.FuncMap{"Title": strings.Title} 45 t, err := template.New(tmplName).Funcs(funcMap).ParseFiles(fmt.Sprintf("generator/%s", tmplName)) 46 if err != nil { 47 panic(fmt.Sprintf("failed to parse builder template: %s", err)) 48 } 49 50 f, err := os.Create(outName) 51 if err != nil { 52 panic(fmt.Sprintf("failed to create %s file: %s", outName, err)) 53 } 54 defer f.Close() 55 56 var buf bytes.Buffer 57 if err = t.Execute(&buf, modules); err != nil { 58 panic(fmt.Sprintf("failed to generate %s file content: %s", outName, err)) 59 } 60 61 content, err := format.Source(buf.Bytes()) 62 if err != nil { 63 panic(fmt.Sprintf("failed to format generated code: %s", err)) 64 } 65 66 if _, err = f.Write(content); err != nil { 67 panic(fmt.Sprintf("failed to write file content: %s", err)) 68 } 69 70 fmt.Printf("%s file successfully generated\n", outName) 71 }