github.com/wawandco/oxpecker-plugins@v0.1.1/tools/pop/builder.go (about) 1 package pop 2 3 import ( 4 "bytes" 5 "context" 6 "io/ioutil" 7 "os" 8 "path/filepath" 9 "text/template" 10 11 "github.com/wawandco/oxpecker-plugins/tools/pop/templates" 12 ) 13 14 func (p *Plugin) RunBeforeBuild(ctx context.Context, root string, args []string) error { 15 f, err := p.findConfig() 16 if err != nil { 17 return err 18 } 19 20 content, err := p.buildDatabaseInit(f) 21 if err != nil { 22 return err 23 } 24 25 return ioutil.WriteFile(filepath.Join("config", "gen_database.go"), []byte(content), 0600) 26 } 27 28 func (p *Plugin) findConfig() ([]byte, error) { 29 f, err := ioutil.ReadFile(filepath.Join("config", "database.yml")) 30 if err != nil { 31 return []byte{}, err 32 } 33 34 return f, err 35 } 36 37 func (p *Plugin) buildDatabaseInit(fileContent []byte) (string, error) { 38 tmpl, err := template.New("config").Parse(templates.DatabaseConfiguration) 39 if err != nil { 40 return "", err 41 } 42 43 bb := bytes.NewBuffer([]byte{}) 44 err = tmpl.Execute(bb, struct { 45 Config string 46 }{ 47 Config: string(fileContent), 48 }) 49 50 if err != nil { 51 return "", err 52 } 53 54 dat, err := ioutil.ReadAll(bb) 55 if err != nil { 56 return "", err 57 } 58 59 return string(dat), nil 60 } 61 62 func (p *Plugin) RunAfterBuild(root string, args []string) error { 63 err := os.Remove(filepath.Join("config", "gen_database.go")) 64 if os.IsNotExist(err) { 65 return nil 66 } 67 68 return err 69 }