gopkg.in/src-d/enry.v1@v1.7.3/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  	"go/format"
     8  	"io"
     9  	"io/ioutil"
    10  	"path/filepath"
    11  	"text/template"
    12  )
    13  
    14  // File is a common type for all generator functions.
    15  // It generates Go source code file based on template in tmplPath,
    16  // by parsing the data in fileToParse and linguist's samplesDir
    17  // saving results to an outFile.
    18  type File func(fileToParse, samplesDir, outPath, tmplPath, tmplName, commit string) error
    19  
    20  func formatedWrite(outPath string, source []byte) error {
    21  	formatedSource, err := format.Source(source)
    22  	if err != nil {
    23  		return err
    24  	}
    25  	if err := ioutil.WriteFile(outPath, formatedSource, 0666); err != nil {
    26  		return err
    27  	}
    28  	return nil
    29  }
    30  
    31  func executeTemplate(w io.Writer, name, path, commit string, fmap template.FuncMap, data interface{}) error {
    32  	getCommit := func() string {
    33  		return commit
    34  	}
    35  
    36  	const headerTmpl = "header.go.tmpl"
    37  	headerPath := filepath.Join(filepath.Dir(path), headerTmpl)
    38  
    39  	h := template.Must(template.New(headerTmpl).Funcs(template.FuncMap{
    40  		"getCommit": getCommit,
    41  	}).ParseFiles(headerPath))
    42  
    43  	buf := bytes.NewBuffer(nil)
    44  	if err := h.Execute(buf, data); err != nil {
    45  		return err
    46  	}
    47  
    48  	if fmap == nil {
    49  		fmap = make(template.FuncMap)
    50  	}
    51  	fmap["getCommit"] = getCommit
    52  
    53  	t := template.Must(template.New(name).Funcs(fmap).ParseFiles(path))
    54  	if err := t.Execute(buf, data); err != nil {
    55  		return err
    56  	}
    57  
    58  	src, err := format.Source(buf.Bytes())
    59  	if err != nil {
    60  		return err
    61  	}
    62  	_, err = w.Write(src)
    63  	return err
    64  }