environment.go 1.8 KB

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