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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. }
  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. buf, _ := ioutil.ReadFile(config.Destination)
  44. t.templates = append(t.templates, &Template{
  45. config: config,
  46. content: string(buf),
  47. template: tmpl,
  48. })
  49. }
  50. func (t *TemplateGenerator) Generate(context Context) {
  51. for _, tmpl := range t.templates {
  52. fmt.Printf("Checking %s\n", tmpl.config.Source)
  53. builder := &strings.Builder{}
  54. err := tmpl.template.Execute(builder, context)
  55. if err != nil {
  56. panic(err)
  57. }
  58. if tmpl.content != builder.String() {
  59. fmt.Printf("--- %s updated, writing to %s ---\n", tmpl.config.Source, tmpl.config.Destination)
  60. fmt.Printf("%s", builder.String())
  61. fmt.Printf("--- / writing %s ---\n", tmpl.config.Destination)
  62. tmpl.content = builder.String()
  63. err = ioutil.WriteFile(tmpl.config.Destination, []byte(builder.String()), 0666)
  64. if err != nil {
  65. panic(err)
  66. }
  67. }
  68. }
  69. }