From c7a67065e165f825894ca2d8e5a02ede6bd3fbea Mon Sep 17 00:00:00 2001
From: Ammar Bandukwala <ammar@ammar.io>
Date: Thu, 9 Mar 2023 19:47:28 +0000
Subject: [PATCH] fix: treat empty env as defaults

---
 cli/clibase/option.go      |  7 ++++++-
 cli/clibase/option_test.go | 22 ++++++++++++++++++++++
 2 files changed, 28 insertions(+), 1 deletion(-)

diff --git a/cli/clibase/option.go b/cli/clibase/option.go
index 1c3c05fda2d44..3fd910441a47d 100644
--- a/cli/clibase/option.go
+++ b/cli/clibase/option.go
@@ -107,7 +107,12 @@ func (s *OptionSet) ParseEnv(globalPrefix string, environ []string) error {
 		}
 
 		envVal, ok := envs[opt.Env]
-		if !ok {
+		// Currently, empty values are treated as if the environment variable is
+		// unset. This behavior is technically not correct as there is now no
+		// way for a user to change a Default value to an empty string from
+		// the environment. Unfortunately, we have old configuration files
+		// that rely on the faulty behavior.
+		if !ok || envVal == "" {
 			continue
 		}
 
diff --git a/cli/clibase/option_test.go b/cli/clibase/option_test.go
index 00a133b712d28..77ede24270896 100644
--- a/cli/clibase/option_test.go
+++ b/cli/clibase/option_test.go
@@ -91,4 +91,26 @@ func TestOptionSet_ParseEnv(t *testing.T) {
 		require.NoError(t, err)
 		require.EqualValues(t, "foo", workspaceName)
 	})
+
+	t.Run("EmptyValue", func(t *testing.T) {
+		t.Parallel()
+
+		var workspaceName clibase.String
+
+		os := clibase.OptionSet{
+			clibase.Option{
+				Name:    "Workspace Name",
+				Value:   &workspaceName,
+				Default: "defname",
+				Env:     "WORKSPACE_NAME",
+			},
+		}
+
+		err := os.SetDefaults()
+		require.NoError(t, err)
+
+		err = os.ParseEnv("CODER_", []string{"CODER_WORKSPACE_NAME="})
+		require.NoError(t, err)
+		require.EqualValues(t, "defname", workspaceName)
+	})
 }