tartrazine/internal/code-generator/generator/filenames.go

53 lines
1.5 KiB
Go
Raw Normal View History

package generator
import (
"bytes"
"io"
2017-05-31 10:07:46 +00:00
"strings"
"text/template"
yaml "gopkg.in/yaml.v2"
)
2017-05-29 08:05:16 +00:00
// Filenames reads from buf and builds source file from filenamesTmplPath.
func Filenames(data []byte, filenamesTmplPath, filenamesTmplName, commit string) ([]byte, error) {
languages := make(map[string]*languageInfo)
if err := yaml.Unmarshal(data, &languages); err != nil {
return nil, err
}
languagesByFilename := buildFilenameLanguageMap(languages)
buf := &bytes.Buffer{}
if err := executeFilenamesTemplate(buf, languagesByFilename, filenamesTmplPath, filenamesTmplName, commit); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
2017-05-31 10:07:46 +00:00
func buildFilenameLanguageMap(languages map[string]*languageInfo) map[string][]string {
filenameLangMap := make(map[string][]string)
for lang, langInfo := range languages {
for _, filename := range langInfo.Filenames {
2017-05-31 10:07:46 +00:00
filenameLangMap[filename] = append(filenameLangMap[filename], lang)
}
}
return filenameLangMap
}
2017-05-31 10:07:46 +00:00
func executeFilenamesTemplate(out io.Writer, languagesByFilename map[string][]string, filenamesTmplPath, filenamesTmpl, commit string) error {
fmap := template.FuncMap{
2017-05-31 10:07:46 +00:00
"getCommit": func() string { return commit },
"formatStringSlice": func(slice []string) string { return `"` + strings.Join(slice, `","`) + `"` },
}
t := template.Must(template.New(filenamesTmpl).Funcs(fmap).ParseFiles(filenamesTmplPath))
if err := t.Execute(out, languagesByFilename); err != nil {
return err
}
return nil
}