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.9KB

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