12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- package main
-
- import (
- "fmt"
- "os"
- "path"
- "sort"
- "strings"
- "text/template"
- )
-
- type Context struct {
- Containers map[string]Container
- }
-
- type TemplateConfig struct {
- Source string
- Destination string
- }
-
- type Template struct {
- config TemplateConfig
- content string
- template *template.Template
- }
-
- type TemplateGenerator struct {
- templates []*Template
- }
-
- var funcMap = template.FuncMap{
- "replace": func(from, to, input string) string { return strings.Replace(input, from, to, -1) },
- "split": func(sep, input string) []string { return strings.Split(input, sep) },
- "join": func(sep string, input []string) string { return strings.Join(input, sep) },
- "sortlines": func(input string) string {
- lines := strings.Split(input, "\n")
- sort.Strings(lines)
- return strings.Join(lines, "\n")
- },
- }
-
- func NewTemplateGenerator() *TemplateGenerator {
- return &TemplateGenerator{}
- }
-
- func (t *TemplateGenerator) AddTemplate(config TemplateConfig) {
- tmpl, err := template.New(path.Base(config.Source)).Funcs(funcMap).ParseFiles(config.Source)
- if err != nil {
- panic(err)
- }
-
- t.templates = append(t.templates, &Template{
- config: config,
- content: "", // TODO: Read this in initially
- template: tmpl,
- })
- }
-
- func (t *TemplateGenerator) Generate(context Context) {
- for _, tmpl := range t.templates {
- // TODO: Actually write to file :)
- // TODO: Retrieve the output and check if it matches our cache
- fmt.Printf("--- Writing %s to %s ---\n", tmpl.config.Source, tmpl.config.Destination)
- err := tmpl.template.Execute(os.Stdout, context)
- fmt.Printf("--- / writing %s ---\n", tmpl.config.Destination)
- if err != nil {
- panic(err)
- }
- }
- }
|