diff --git a/README.md b/README.md index 300ee1f9..de09cb54 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,18 @@ task assets build If Bash is available (Linux and Windows while on Git Bash), the commands will run in Bash, otherwise will fallback to `cmd` (on Windows). + +### Environment +You can specify environment variables that are added when running a command: + +```yml +build: + cmds: + - echo $hallo + env: + hallo: welt +``` + ### OS specific task support If you add a `Taskfile_{{GOOS}}` you can override or amend your taskfile based on the op;erating system. diff --git a/task.go b/task.go index ec07617f..f0af7c8e 100644 --- a/task.go +++ b/task.go @@ -1,6 +1,7 @@ package task import ( + "fmt" "log" "os" "os/exec" @@ -44,6 +45,7 @@ type Task struct { Dir string Vars map[string]string Set string + Env map[string]string } // Run runs Task @@ -101,7 +103,7 @@ func RunTask(name string) error { } for i := range t.Cmds { - if err = t.runCommand(i); err != nil { + if err = t.runCommand(i, t.Env); err != nil { return &taskRunError{name, err} } } @@ -126,7 +128,7 @@ func (t *Task) isUpToDate() bool { return generatesMinTime.After(sourcesMaxTime) } -func (t *Task) runCommand(i int) error { +func (t *Task) runCommand(i int, envVariables map[string]string) error { vars, err := t.handleVariables() if err != nil { return err @@ -148,6 +150,21 @@ func (t *Task) runCommand(i int) error { if dir != "" { cmd.Dir = dir } + if nil != envVariables { + env := os.Environ() + for key, value := range envVariables { + replacedValue, err := ReplaceVariables(value, vars) + if err != nil { + return err + } + replacedKey, err := ReplaceVariables(key, vars) + if err != nil { + return err + } + env = append(env, fmt.Sprintf("%s=%s", replacedKey, replacedValue)) + } + cmd.Env = env + } cmd.Stdin = os.Stdin cmd.Stderr = os.Stderr if t.Set != "" {