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.

templates.go 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package main
  2. import (
  3. "io/ioutil"
  4. "path"
  5. "sort"
  6. "strings"
  7. "text/template"
  8. )
  9. type Context struct {
  10. Containers map[string]*Container
  11. Hostnames map[string]*Hostname
  12. }
  13. type Template struct {
  14. config TemplateConfig
  15. content string
  16. template *template.Template
  17. }
  18. type TemplateGenerator struct {
  19. templates []*Template
  20. }
  21. var funcMap = template.FuncMap{
  22. "replace": func(from, to, input string) string { return strings.Replace(input, from, to, -1) },
  23. "split": func(sep, input string) []string { return strings.Split(input, sep) },
  24. "join": func(sep string, input []string) string { return strings.Join(input, sep) },
  25. "sortlines": func(input string) string {
  26. lines := strings.Split(input, "\n")
  27. sort.Strings(lines)
  28. return strings.Join(lines, "\n")
  29. },
  30. }
  31. func NewTemplateGenerator() *TemplateGenerator {
  32. return &TemplateGenerator{}
  33. }
  34. func (t *TemplateGenerator) AddTemplate(config TemplateConfig) {
  35. logger.Infof("Registered template from %s, writing to %s", config.Source, config.Destination)
  36. tmpl, err := template.New(path.Base(config.Source)).Funcs(funcMap).ParseFiles(config.Source)
  37. if err != nil {
  38. logger.Fatal("Unable to parse template", err)
  39. }
  40. buf, _ := ioutil.ReadFile(config.Destination)
  41. t.templates = append(t.templates, &Template{
  42. config: config,
  43. content: string(buf),
  44. template: tmpl,
  45. })
  46. }
  47. func (t *TemplateGenerator) Generate(context Context) (updated bool) {
  48. for _, tmpl := range t.templates {
  49. logger.Debugf("Checking for updates to %s", tmpl.config.Source)
  50. builder := &strings.Builder{}
  51. err := tmpl.template.Execute(builder, context)
  52. if err != nil {
  53. panic(err)
  54. }
  55. if tmpl.content != builder.String() {
  56. updated = true
  57. logger.Infof("Writing updated template to %s", tmpl.config.Destination)
  58. tmpl.content = builder.String()
  59. err = ioutil.WriteFile(tmpl.config.Destination, []byte(builder.String()), 0666)
  60. if err != nil {
  61. logger.Fatal("Unable to write template", err)
  62. }
  63. } else {
  64. logger.Debugf("Not writing template to %s as content is the same", tmpl.config.Destination)
  65. }
  66. }
  67. return
  68. }