2017-04-04 11:10:35 +00:00
|
|
|
package generator
|
|
|
|
|
|
|
|
import (
|
2018-04-28 13:12:03 +00:00
|
|
|
"bytes"
|
2017-04-04 11:10:35 +00:00
|
|
|
"go/format"
|
2018-04-28 13:12:03 +00:00
|
|
|
"io"
|
2017-04-04 11:10:35 +00:00
|
|
|
"io/ioutil"
|
2018-04-28 13:12:03 +00:00
|
|
|
"path/filepath"
|
|
|
|
"text/template"
|
2017-04-04 11:10:35 +00:00
|
|
|
)
|
|
|
|
|
2017-06-13 11:56:07 +00:00
|
|
|
// File is the function's type that generate source file from a file to be parsed, linguist's samples dir and a template.
|
|
|
|
type File func(fileToParse, samplesDir, outPath, tmplPath, tmplName, commit string) error
|
2017-05-25 10:33:26 +00:00
|
|
|
|
|
|
|
func formatedWrite(outPath string, source []byte) error {
|
2017-04-04 11:10:35 +00:00
|
|
|
formatedSource, err := format.Source(source)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err := ioutil.WriteFile(outPath, formatedSource, 0666); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2018-04-28 13:12:03 +00:00
|
|
|
|
|
|
|
func executeTemplate(w io.Writer, name, path, commit string, fmap template.FuncMap, data interface{}) error {
|
|
|
|
getCommit := func() string {
|
|
|
|
return commit
|
|
|
|
}
|
|
|
|
|
|
|
|
buf := bytes.NewBuffer(nil)
|
|
|
|
|
|
|
|
const headerTmpl = "header.go.tmpl"
|
|
|
|
|
|
|
|
headerPath := filepath.Join(filepath.Dir(path), headerTmpl)
|
|
|
|
|
|
|
|
h := template.Must(template.New(headerTmpl).Funcs(template.FuncMap{
|
|
|
|
"getCommit": getCommit,
|
|
|
|
}).ParseFiles(headerPath))
|
|
|
|
|
|
|
|
if err := h.Execute(buf, data); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if fmap == nil {
|
|
|
|
fmap = make(template.FuncMap)
|
|
|
|
}
|
|
|
|
fmap["getCommit"] = getCommit
|
|
|
|
|
|
|
|
t := template.Must(template.New(name).Funcs(fmap).ParseFiles(path))
|
|
|
|
if err := t.Execute(buf, data); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
src, err := format.Source(buf.Bytes())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
_, err = w.Write(src)
|
|
|
|
return err
|
|
|
|
}
|