Skip to content

Commit b19f8af

Browse files
Merge pull request #504 from hashicorp/james-warren0/git-bad-ref-clean-up
Clean up git repo on disk when the ref checkout fails
2 parents 4f07d24 + 768e85f commit b19f8af

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

get_git.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,12 @@ func (g *GitGetter) clone(ctx context.Context, dst, sshKeyFile string, u *url.UR
223223
// If we didn't add --depth and --branch above then we will now be
224224
// on the remote repository's default branch, rather than the selected
225225
// ref, so we'll need to fix that before we return.
226-
return g.checkout(ctx, dst, originalRef)
226+
err := g.checkout(ctx, dst, originalRef)
227+
if err != nil {
228+
// Clean up git repository on disk
229+
_ = os.RemoveAll(dst)
230+
return err
231+
}
227232
}
228233
return nil
229234
}

get_git_test.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -984,6 +984,38 @@ func TestGitGetter_BadGitDirName(t *testing.T) {
984984
}
985985
}
986986

987+
func TestGitGetter_BadRef(t *testing.T) {
988+
if !testHasGit {
989+
t.Log("git not found, skipping")
990+
t.Skip()
991+
}
992+
993+
ctx := context.Background()
994+
g := new(GitGetter)
995+
dst := tempDir(t)
996+
997+
url, err := url.Parse("https://github.com/hashicorp/go-getter")
998+
if err != nil {
999+
t.Fatal(err)
1000+
}
1001+
1002+
_, err = os.Stat(dst)
1003+
if err != nil && !os.IsNotExist(err) {
1004+
t.Fatalf(err.Error())
1005+
}
1006+
1007+
// Clone a repository with non-existent ref
1008+
err = g.clone(ctx, dst, "", url, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 0)
1009+
if err == nil {
1010+
t.Fatalf(err.Error())
1011+
}
1012+
1013+
// Expect that the dst was cleaned up after failed ref checkout
1014+
if _, err := os.Stat(dst); !os.IsNotExist(err) {
1015+
t.Fatalf("cloned repository still exists after bad ref checkout")
1016+
}
1017+
}
1018+
9871019
// gitRepo is a helper struct which controls a single temp git repo.
9881020
type gitRepo struct {
9891021
t *testing.T

0 commit comments

Comments
 (0)