From ada315a81033cb2648a802914292f3de399cdd59 Mon Sep 17 00:00:00 2001 From: Andreas Karis Date: Fri, 3 Oct 2025 19:15:31 +0200 Subject: [PATCH] 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 --- generate/generate.go | 3 +++ generate/generate_test.go | 6 ++++++ 2 files changed, 9 insertions(+) diff --git a/generate/generate.go b/generate/generate.go index ae5a9984..140ba4f5 100644 --- a/generate/generate.go +++ b/generate/generate.go @@ -540,6 +540,9 @@ func (g *Generator) addEnv(env, key string) { } else { // else the env doesn't exist, so add it and add it's index to g.envMap g.Config.Process.Env = append(g.Config.Process.Env, env) + if g.envMap == nil { + g.envMap = map[string]int{} + } g.envMap[key] = len(g.Config.Process.Env) - 1 } } diff --git a/generate/generate_test.go b/generate/generate_test.go index b27dc3fc..ea8f188a 100644 --- a/generate/generate_test.go +++ b/generate/generate_test.go @@ -124,6 +124,12 @@ func TestEnvCaching(t *testing.T) { } g.AddProcessEnv("", "") assert.Equal(t, []string(nil), g.Config.Process.Env) + + // Test with nil envMap. + g = generate.Generator{} + expected = []string{"k1=v1"} + g.AddProcessEnv("k1", "v1") + assert.Equal(t, expected, g.Config.Process.Env) } func TestMultipleEnvCaching(t *testing.T) {