Skip to content

Commit c3034d0

Browse files
committed
Fix nil ptr panic when adding env variables to uninitialized Generator
When calling AddProcessEnv on a Generator instance that was created using zero-value initialization (Generator{}) rather than through New(), the envMap field would be nil. This caused a panic when attempting to write to the map in the addEnv helper function. This commit adds a nil check before writing to the envMap in addEnv. If the map is uninitialized, it creates a new empty map before proceeding with the map insertion operation. A new test case has been added to TestEnvCaching that validates this scenario by creating a Generator using zero-value initialization and verifying that AddProcessEnv works correctly without panicking. Signed-off-by: Andreas Karis <[email protected]>
1 parent 0ea5ed0 commit c3034d0

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

generate/generate.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -540,6 +540,9 @@ func (g *Generator) addEnv(env, key string) {
540540
} else {
541541
// else the env doesn't exist, so add it and add it's index to g.envMap
542542
g.Config.Process.Env = append(g.Config.Process.Env, env)
543+
if g.envMap == nil {
544+
g.envMap = map[string]int{}
545+
}
543546
g.envMap[key] = len(g.Config.Process.Env) - 1
544547
}
545548
}

generate/generate_test.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,15 @@ func TestEnvCaching(t *testing.T) {
124124
}
125125
g.AddProcessEnv("", "")
126126
assert.Equal(t, []string(nil), g.Config.Process.Env)
127+
128+
// Test empty ENV with nil envMap.
129+
g = generate.Generator{}
130+
if err != nil {
131+
t.Fatal(err)
132+
}
133+
expected = []string{"k1=v1"}
134+
g.AddProcessEnv("k1", "v1")
135+
assert.Equal(t, expected, g.Config.Process.Env)
127136
}
128137

129138
func TestMultipleEnvCaching(t *testing.T) {

0 commit comments

Comments
 (0)