From 9dc17f9144779230ef9c15f512037d046fd15df4 Mon Sep 17 00:00:00 2001
From: Liam Murphy <liamphmurphy@gmail.com>
Date: Mon, 4 Apr 2022 17:24:49 +0000
Subject: [PATCH] Allow passed in env vars to supersede ones declared in the
 workflow (#1100)

* don't merge env var if it exists already

* remove test workflow

* add some tests

* change mergeMaps order instead of checking for existence

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
---
 pkg/runner/run_context.go      |  2 +-
 pkg/runner/run_context_test.go | 51 ++++++++++++++++++++++++++++++++++
 2 files changed, 52 insertions(+), 1 deletion(-)

diff --git a/pkg/runner/run_context.go b/pkg/runner/run_context.go
index 8b1d3e1..e5caaf5 100644
--- a/pkg/runner/run_context.go
+++ b/pkg/runner/run_context.go
@@ -75,7 +75,7 @@ func (rc *RunContext) String() string {
 // GetEnv returns the env for the context
 func (rc *RunContext) GetEnv() map[string]string {
 	if rc.Env == nil {
-		rc.Env = mergeMaps(rc.Config.Env, rc.Run.Workflow.Env, rc.Run.Job().Environment())
+		rc.Env = mergeMaps(rc.Run.Workflow.Env, rc.Run.Job().Environment(), rc.Config.Env)
 	}
 	rc.Env["ACT"] = "true"
 	return rc.Env
diff --git a/pkg/runner/run_context_test.go b/pkg/runner/run_context_test.go
index 730d8de..ca85930 100644
--- a/pkg/runner/run_context_test.go
+++ b/pkg/runner/run_context_test.go
@@ -485,3 +485,54 @@ if: always()`, ""),
 	rc.Run.JobID = "job2"
 	assertObject.True(rc.isEnabled(context.Background()))
 }
+
+func TestRunContextGetEnv(t *testing.T) {
+	tests := []struct {
+		description string
+		rc          *RunContext
+		targetEnv   string
+		want        string
+	}{
+		{
+			description: "Env from Config should overwrite",
+			rc: &RunContext{
+				Config: &Config{
+					Env: map[string]string{"OVERWRITTEN": "true"},
+				},
+				Run: &model.Run{
+					Workflow: &model.Workflow{
+						Jobs: map[string]*model.Job{"test": {Name: "test"}},
+						Env:  map[string]string{"OVERWRITTEN": "false"},
+					},
+					JobID: "test",
+				},
+			},
+			targetEnv: "OVERWRITTEN",
+			want:      "true",
+		},
+		{
+			description: "No overwrite occurs",
+			rc: &RunContext{
+				Config: &Config{
+					Env: map[string]string{"SOME_OTHER_VAR": "true"},
+				},
+				Run: &model.Run{
+					Workflow: &model.Workflow{
+						Jobs: map[string]*model.Job{"test": {Name: "test"}},
+						Env:  map[string]string{"OVERWRITTEN": "false"},
+					},
+					JobID: "test",
+				},
+			},
+			targetEnv: "OVERWRITTEN",
+			want:      "false",
+		},
+	}
+
+	for _, test := range tests {
+		t.Run(test.description, func(t *testing.T) {
+			envMap := test.rc.GetEnv()
+			assert.EqualValues(t, test.want, envMap[test.targetEnv])
+		})
+	}
+}