From f7ccfa2ab931708795763107a3c9743a8da87e92 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Tue, 23 Aug 2022 14:29:01 +0300 Subject: [PATCH] feat: Set `CODER=true` in workspaces (#3637) Fixes #2340 --- agent/agent.go | 4 ++++ agent/agent_test.go | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/agent/agent.go b/agent/agent.go index cb2f42ed3c..586a1785e8 100644 --- a/agent/agent.go +++ b/agent/agent.go @@ -394,6 +394,10 @@ func (a *agent) createCommand(ctx context.Context, rawCommand string, env []stri if err != nil { return nil, xerrors.Errorf("getting os executable: %w", err) } + // Set environment variables reliable detection of being inside a + // Coder workspace. + cmd.Env = append(cmd.Env, "CODER=true") + cmd.Env = append(cmd.Env, fmt.Sprintf("USER=%s", username)) // Git on Windows resolves with UNIX-style paths. // If using backslashes, it's unable to find the executable. diff --git a/agent/agent_test.go b/agent/agent_test.go index e3d3a80886..5094ba0f6d 100644 --- a/agent/agent_test.go +++ b/agent/agent_test.go @@ -232,6 +232,26 @@ func TestAgent(t *testing.T) { require.Equal(t, expect, strings.TrimSpace(string(output))) }) + t.Run("Coder env vars", func(t *testing.T) { + t.Parallel() + + for _, key := range []string{"CODER"} { + key := key + t.Run(key, func(t *testing.T) { + t.Parallel() + + session := setupSSHSession(t, agent.Metadata{}) + command := "sh -c 'echo $" + key + "'" + if runtime.GOOS == "windows" { + command = "cmd.exe /c echo %" + key + "%" + } + output, err := session.Output(command) + require.NoError(t, err) + require.NotEmpty(t, strings.TrimSpace(string(output))) + }) + } + }) + t.Run("StartupScript", func(t *testing.T) { t.Parallel() tempPath := filepath.Join(t.TempDir(), "content.txt")