1
0

dotenv.go 1011 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package taskfile
  2. import (
  3. "os"
  4. "github.com/joho/godotenv"
  5. "github.com/go-task/task/v3/internal/compiler"
  6. "github.com/go-task/task/v3/internal/filepathext"
  7. "github.com/go-task/task/v3/internal/templater"
  8. "github.com/go-task/task/v3/taskfile/ast"
  9. )
  10. func Dotenv(c *compiler.Compiler, tf *ast.Taskfile, dir string) (*ast.Vars, error) {
  11. if len(tf.Dotenv) == 0 {
  12. return nil, nil
  13. }
  14. vars, err := c.GetTaskfileVariables()
  15. if err != nil {
  16. return nil, err
  17. }
  18. env := &ast.Vars{}
  19. cache := &templater.Cache{Vars: vars}
  20. for _, dotEnvPath := range tf.Dotenv {
  21. dotEnvPath = templater.Replace(dotEnvPath, cache)
  22. if dotEnvPath == "" {
  23. continue
  24. }
  25. dotEnvPath = filepathext.SmartJoin(dir, dotEnvPath)
  26. if _, err := os.Stat(dotEnvPath); os.IsNotExist(err) {
  27. continue
  28. }
  29. envs, err := godotenv.Read(dotEnvPath)
  30. if err != nil {
  31. return nil, err
  32. }
  33. for key, value := range envs {
  34. if ok := env.Exists(key); !ok {
  35. env.Set(key, ast.Var{Value: value})
  36. }
  37. }
  38. }
  39. return env, nil
  40. }