gitlab.com/thomasboni/go-enry/v2@v2.8.3-0.20220418031202-30b0d7a3de98/internal/code-generator/generator/generator.go (about)

     1  // Package generator provides facilities to generate Go code for the
     2  // package data in enry from YAML files describing supported languages in Linguist.
     3  package generator
     4  
     5  import (
     6  	"bytes"
     7  	"fmt"
     8  	"go/format"
     9  	"io"
    10  	"io/ioutil"
    11  	"path/filepath"
    12  	"strings"
    13  	"text/template"
    14  )
    15  
    16  // File is a common type for all generator functions.
    17  // It generates Go source code file based on template in tmplPath,
    18  // by parsing the data in fileToParse and linguist's samplesDir
    19  // saving results to an outFile.
    20  type File func(fileToParse, samplesDir, outPath, tmplPath, tmplName, commit string) error
    21  
    22  func formatedWrite(outPath string, source []byte) error {
    23  	formatedSource, err := format.Source(source)
    24  	if err != nil {
    25  		return err
    26  	}
    27  	if err := ioutil.WriteFile(outPath, formatedSource, 0666); err != nil {
    28  		return err
    29  	}
    30  	return nil
    31  }
    32  
    33  func executeTemplate(w io.Writer, name, path, commit string, fmap template.FuncMap, data interface{}) error {
    34  	getCommit := func() string {
    35  		return commit
    36  	}
    37  	// stringVal returns escaped string that can be directly placed into go code.
    38  	// for value test`s it would return `test`+"`"+`s`
    39  	stringVal := func(val string) string {
    40  		val = strings.ReplaceAll(val, "`", "`+\"`\"+`")
    41  		return fmt.Sprintf("`%s`", val)
    42  	}
    43  
    44  	const headerTmpl = "header.go.tmpl"
    45  	headerPath := filepath.Join(filepath.Dir(path), headerTmpl)
    46  
    47  	h := template.Must(template.New(headerTmpl).Funcs(template.FuncMap{
    48  		"getCommit": getCommit,
    49  		"stringVal": stringVal,
    50  	}).ParseFiles(headerPath))
    51  
    52  	buf := bytes.NewBuffer(nil)
    53  	if err := h.Execute(buf, data); err != nil {
    54  		return err
    55  	}
    56  
    57  	if fmap == nil {
    58  		fmap = make(template.FuncMap)
    59  	}
    60  	fmap["getCommit"] = getCommit
    61  	fmap["stringVal"] = stringVal
    62  
    63  	t := template.Must(template.New(name).Funcs(fmap).ParseFiles(path))
    64  	if err := t.Execute(buf, data); err != nil {
    65  		return err
    66  	}
    67  
    68  	src, err := format.Source(buf.Bytes())
    69  	if err != nil {
    70  		return err
    71  	}
    72  	_, err = w.Write(src)
    73  	return err
    74  }