github.com/searchspring/haus@v0.1.8-0.20200414161854-a7ca8bb9ea93/app/template.go (about) 1 package haus 2 3 import( 4 "bytes" 5 "io/ioutil" 6 "text/template" 7 8 "gopkg.in/yaml.v2" 9 ) 10 11 // Template represents a single instance of a haus template file. 12 type Template struct { 13 Path string 14 Pwd string 15 Image string 16 Name string 17 Branch string 18 Version string 19 Variables map[string]string 20 Env map[string]string 21 Parsed *ParsedTmpl 22 23 24 } 25 26 // ParsedTmpl represents a collection of Repo and DockerCfgs created from haus templates. 27 type ParsedTmpl struct { 28 Repotsar map[string]Repo 29 Docker map[string]DockerCfg 30 } 31 32 // Parse processes template files to create Repo and DockerCfgs, returns a ParsedTmpl. 33 func (t *Template) Parse() (ParsedTmpl, error){ 34 if t.Parsed != nil { 35 return *t.Parsed,nil 36 } 37 // Read template 38 templatefile := t.Pwd+"/templates/"+t.Name+".yml.tmpl" 39 source, err := ioutil.ReadFile(templatefile) 40 if err != nil { 41 return ParsedTmpl{}, err 42 } 43 44 // Parse template 45 template,err := template.New(t.Name).Parse(string(source[:])) 46 if err != nil { 47 return ParsedTmpl{}, err 48 } 49 // 50 buf := &bytes.Buffer{} 51 err = template.Execute(buf,t) 52 if err != nil { 53 return ParsedTmpl{},err 54 } 55 parsed := &ParsedTmpl{} 56 err = yaml.Unmarshal(buf.Bytes(),parsed) 57 if err != nil { 58 return *parsed,err 59 } 60 t.Parsed = parsed 61 return *parsed, nil 62 63 } 64 65 // DockerCfgs returns DockerCfgs stored in Template. 66 func (t *Template) DockerCfgs() (map[string]DockerCfg, error) { 67 parsed,err := t.Parse() 68 return parsed.Docker,err 69 } 70 71 // RepoTsarCfgs returns RepoTsarCfgs stored in Template. 72 func (t *Template) RepoTsarCfgs() (map[string]Repo, error) { 73 parsed,err := t.Parse() 74 return parsed.Repotsar,err 75 } 76