environment.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package got
  2. import (
  3. "fmt"
  4. "text/template"
  5. . "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/common"
  6. G "github.com/dave/jennifer/jen"
  7. )
  8. var (
  9. environmentStmtsTmpl *template.Template
  10. environmentStmtsErr error
  11. )
  12. func init() {
  13. environmentStmtsTmpl, environmentStmtsErr = ParseTemplate(`
  14. import (
  15. "fmt"
  16. common "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/common"
  17. "os"
  18. )
  19. const (
  20. {{range .variables}} Env{{.CamelID}} = "{{.ID}}"
  21. {{end}}
  22. )
  23. func InitEnvironment() error {
  24. var (
  25. value string
  26. variables = []common.EnvironmentVariable{
  27. {{range .variables}}{
  28. ID: Env{{.CamelID}},
  29. Description: "{{.Description}}",
  30. Required: {{.Required}},
  31. Default: "{{.Default}}",
  32. },{{end}}
  33. }
  34. )
  35. for _, variable := range variables {
  36. if value = os.Getenv(variable.ID); value == "" {
  37. if variable.Default == "" && variable.Required {
  38. panic(fmt.Errorf("Environment Variable '%s' not defined! %s", variable.ID, variable.Description))
  39. }
  40. value = variable.Default
  41. }
  42. common.Setenv(variable.ID, value)
  43. }
  44. fmt.Println("Environment...")
  45. for _, pair := range os.Environ() {
  46. fmt.Printf("\t├ %s\n",pair)
  47. }
  48. return nil
  49. }`)
  50. }
  51. func CreateEnvironment(p *Project) error {
  52. for id, environment := range p.Environment {
  53. environment.CamelID = UnderToCamel(id)
  54. }
  55. var (
  56. context = map[string]interface{}{
  57. "variables": p.Environment,
  58. }
  59. )
  60. out, _ := TemplateToString(environmentStmtsTmpl, context)
  61. file := G.NewFile(p.Package)
  62. file.Id(out)
  63. return Write(fmt.Sprintf("%s/%s/environment.go", p.OutPath, p.Package), file)
  64. }