github.com/prebid/prebid-server@v0.275.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  	"strings"
    14  	"text/template"
    15  )
    16  
    17  var (
    18  	r        = regexp.MustCompile("^([^/]+)/([^/]+)/module.go$")
    19  	tmplName = "builder.tmpl"
    20  	outName  = "builder.go"
    21  )
    22  
    23  type Module struct {
    24  	Vendor string
    25  	Module string
    26  }
    27  
    28  func main() {
    29  	var modules []Module
    30  
    31  	filepath.WalkDir("./", func(path string, d fs.DirEntry, err error) error {
    32  		if !r.MatchString(path) {
    33  			return nil
    34  		}
    35  		match := r.FindStringSubmatch(path)
    36  		modules = append(modules, Module{
    37  			Vendor: match[1],
    38  			Module: match[2],
    39  		})
    40  		return nil
    41  	})
    42  
    43  	funcMap := template.FuncMap{"Title": strings.Title}
    44  	t, err := template.New(tmplName).Funcs(funcMap).ParseFiles(fmt.Sprintf("generator/%s", tmplName))
    45  	if err != nil {
    46  		panic(fmt.Sprintf("failed to parse builder template: %s", err))
    47  	}
    48  
    49  	f, err := os.Create(outName)
    50  	if err != nil {
    51  		panic(fmt.Sprintf("failed to create %s file: %s", outName, err))
    52  	}
    53  	defer f.Close()
    54  
    55  	var buf bytes.Buffer
    56  	if err = t.Execute(&buf, modules); err != nil {
    57  		panic(fmt.Sprintf("failed to generate %s file content: %s", outName, err))
    58  	}
    59  
    60  	content, err := format.Source(buf.Bytes())
    61  	if err != nil {
    62  		panic(fmt.Sprintf("failed to format generated code: %s", err))
    63  	}
    64  
    65  	if _, err = f.Write(content); err != nil {
    66  		panic(fmt.Sprintf("failed to write file content: %s", err))
    67  	}
    68  
    69  	fmt.Printf("%s file successfully generated\n", outName)
    70  }