Skip to content

Commit

Permalink
Merge pull request #504 from hashicorp/james-warren0/git-bad-ref-clea…
Browse files Browse the repository at this point in the history
…n-up

Clean up git repo on disk when the ref checkout fails
  • Loading branch information
james-warren0 authored Nov 6, 2024
2 parents 4f07d24 + 768e85f commit b19f8af
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
7 changes: 6 additions & 1 deletion get_git.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,12 @@ func (g *GitGetter) clone(ctx context.Context, dst, sshKeyFile string, u *url.UR
// If we didn't add --depth and --branch above then we will now be
// on the remote repository's default branch, rather than the selected
// ref, so we'll need to fix that before we return.
return g.checkout(ctx, dst, originalRef)
err := g.checkout(ctx, dst, originalRef)
if err != nil {
// Clean up git repository on disk
_ = os.RemoveAll(dst)
return err
}
}
return nil
}
Expand Down
32 changes: 32 additions & 0 deletions get_git_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -984,6 +984,38 @@ func TestGitGetter_BadGitDirName(t *testing.T) {
}
}

func TestGitGetter_BadRef(t *testing.T) {
if !testHasGit {
t.Log("git not found, skipping")
t.Skip()
}

ctx := context.Background()
g := new(GitGetter)
dst := tempDir(t)

url, err := url.Parse("https://github.com/hashicorp/go-getter")
if err != nil {
t.Fatal(err)
}

_, err = os.Stat(dst)
if err != nil && !os.IsNotExist(err) {
t.Fatalf(err.Error())
}

// Clone a repository with non-existent ref
err = g.clone(ctx, dst, "", url, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 0)
if err == nil {
t.Fatalf(err.Error())
}

// Expect that the dst was cleaned up after failed ref checkout
if _, err := os.Stat(dst); !os.IsNotExist(err) {
t.Fatalf("cloned repository still exists after bad ref checkout")
}
}

// gitRepo is a helper struct which controls a single temp git repo.
type gitRepo struct {
t *testing.T
Expand Down

0 comments on commit b19f8af

Please sign in to comment.