Docker template generator
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

template_generator.go 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "path"
  6. "sort"
  7. "strings"
  8. "text/template"
  9. )
  10. type Context struct {
  11. Containers map[string]Container
  12. }
  13. type TemplateConfig struct {
  14. Source string
  15. Destination string
  16. }
  17. type Template struct {
  18. config TemplateConfig
  19. content string
  20. template *template.Template
  21. }
  22. type TemplateGenerator struct {
  23. templates []*Template
  24. }
  25. var funcMap = template.FuncMap{
  26. "replace": func(from, to, input string) string { return strings.Replace(input, from, to, -1) },
  27. "split": func(sep, input string) []string { return strings.Split(input, sep) },
  28. "join": func(sep string, input []string) string { return strings.Join(input, sep) },
  29. "sortlines": func(input string) string {
  30. lines := strings.Split(input, "\n")
  31. sort.Strings(lines)
  32. return strings.Join(lines, "\n")
  33. },
  34. }
  35. func NewTemplateGenerator() *TemplateGenerator {
  36. return &TemplateGenerator{}
  37. }
  38. func (t *TemplateGenerator) AddTemplate(config TemplateConfig) {
  39. tmpl, err := template.New(path.Base(config.Source)).Funcs(funcMap).ParseFiles(config.Source)
  40. if err != nil {
  41. panic(err)
  42. }
  43. t.templates = append(t.templates, &Template{
  44. config: config,
  45. content: "", // TODO: Read this in initially
  46. template: tmpl,
  47. })
  48. }
  49. func (t *TemplateGenerator) Generate(context Context) {
  50. for _, tmpl := range t.templates {
  51. // TODO: Actually write to file :)
  52. // TODO: Retrieve the output and check if it matches our cache
  53. fmt.Printf("--- Writing %s to %s ---\n", tmpl.config.Source, tmpl.config.Destination)
  54. err := tmpl.template.Execute(os.Stdout, context)
  55. fmt.Printf("--- / writing %s ---\n", tmpl.config.Destination)
  56. if err != nil {
  57. panic(err)
  58. }
  59. }
  60. }