From c70d9c915b8e823c44dd591088d15cde70d5e813 Mon Sep 17 00:00:00 2001 From: James Bardin Date: Mon, 9 Oct 2023 17:12:44 -0400 Subject: [PATCH] don't change GIT_SSH_COMMAND if there's no keyfile The reason for setupGitEnv is to add a `-i keyfile` argument to GIT_SSH_COMMAND. If there is no keyfile, we do not need to modify the environment at all. --- get_git.go | 17 ++++++++++------- get_git_test.go | 23 +++++++++++++++++++++++ 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/get_git.go b/get_git.go index 2313a3fba..908493b9d 100644 --- a/get_git.go +++ b/get_git.go @@ -302,6 +302,11 @@ func findRemoteDefaultBranch(ctx context.Context, u *url.URL) string { // setupGitEnv sets up the environment for the given command. This is used to // pass configuration data to git and ssh and enables advanced cloning methods. func setupGitEnv(cmd *exec.Cmd, sshKeyFile string) { + // If there's no sshKeyFile argument to deal with, we can skip this + // entirely. + if sshKeyFile == "" { + return + } const gitSSHCommand = "GIT_SSH_COMMAND=" var sshCmd []string @@ -323,14 +328,12 @@ func setupGitEnv(cmd *exec.Cmd, sshKeyFile string) { sshCmd = []string{gitSSHCommand + "ssh"} } - if sshKeyFile != "" { - // We have an SSH key temp file configured, tell ssh about this. - if runtime.GOOS == "windows" { - sshKeyFile = strings.Replace(sshKeyFile, `\`, `/`, -1) - } - sshCmd = append(sshCmd, "-i", sshKeyFile) - env = append(env, strings.Join(sshCmd, " ")) + // We have an SSH key temp file configured, tell ssh about this. + if runtime.GOOS == "windows" { + sshKeyFile = strings.Replace(sshKeyFile, `\`, `/`, -1) } + sshCmd = append(sshCmd, "-i", sshKeyFile) + env = append(env, strings.Join(sshCmd, " ")) cmd.Env = env } diff --git a/get_git_test.go b/get_git_test.go index d123bb5c5..31892b98d 100644 --- a/get_git_test.go +++ b/get_git_test.go @@ -699,6 +699,29 @@ func TestGitGetter_setupGitEnvWithExisting_sshKey(t *testing.T) { } } +func TestGitGetter_setupGitEnvWithNoKeyFile(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skipf("skipping on windows since the test requires sh") + return + } + + // start with an existing ssh command configuration + os.Setenv("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=no") + defer os.Setenv("GIT_SSH_COMMAND", "") + + cmd := exec.Command("/bin/sh", "-c", "echo $GIT_SSH_COMMAND") + setupGitEnv(cmd, "") + out, err := cmd.Output() + if err != nil { + t.Fatal(err) + } + + actual := strings.TrimSpace(string(out)) + if actual != "ssh -o StrictHostKeyChecking=no" { + t.Fatalf("unexpected GIT_SSH_COMMAND: %q", actual) + } +} + func TestGitGetter_subdirectory_symlink(t *testing.T) { if !testHasGit { t.Skip("git not found, skipping")