From 4ea320cb8ef71c2fc9ee391e2e8be915ba99b17e Mon Sep 17 00:00:00 2001 From: Tonis Tiigi Date: Fri, 8 Dec 2017 11:51:10 -0800 Subject: [PATCH] gitutils: remove checkout directory on error Signed-off-by: Tonis Tiigi --- builder/remotecontext/git/gitutils.go | 12 +++++++++--- builder/remotecontext/git/gitutils_test.go | 20 ++++++++++---------- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/builder/remotecontext/git/gitutils.go b/builder/remotecontext/git/gitutils.go index b579db9765..67cff594ab 100644 --- a/builder/remotecontext/git/gitutils.go +++ b/builder/remotecontext/git/gitutils.go @@ -32,7 +32,7 @@ func Clone(remoteURL string) (string, error) { return cloneGitRepo(repo) } -func cloneGitRepo(repo gitRepo) (string, error) { +func cloneGitRepo(repo gitRepo) (checkoutDir string, err error) { fetch := fetchArgs(repo.remote, repo.ref) root, err := ioutil.TempDir("", "docker-build-git") @@ -40,6 +40,12 @@ func cloneGitRepo(repo gitRepo) (string, error) { return "", err } + defer func() { + if err != nil { + os.RemoveAll(root) + } + }() + if out, err := gitWithinDir(root, "init"); err != nil { return "", errors.Wrapf(err, "failed to init repo at %s: %s", root, out) } @@ -54,7 +60,7 @@ func cloneGitRepo(repo gitRepo) (string, error) { return "", errors.Wrapf(err, "error fetching: %s", output) } - root, err = checkoutGit(root, repo.ref, repo.subdir) + checkoutDir, err = checkoutGit(root, repo.ref, repo.subdir) if err != nil { return "", err } @@ -66,7 +72,7 @@ func cloneGitRepo(repo gitRepo) (string, error) { return "", errors.Wrapf(err, "error initializing submodules: %s", output) } - return root, nil + return checkoutDir, nil } func parseRemoteURL(remoteURL string) (gitRepo, error) { diff --git a/builder/remotecontext/git/gitutils_test.go b/builder/remotecontext/git/gitutils_test.go index b4c49195f0..fd58d6bd98 100644 --- a/builder/remotecontext/git/gitutils_test.go +++ b/builder/remotecontext/git/gitutils_test.go @@ -234,17 +234,17 @@ func TestCheckoutGit(t *testing.T) { if c.fail { assert.Error(t, err) continue - } else { + } + require.NoError(t, err) + defer os.RemoveAll(r) + if c.submodule { + b, err := ioutil.ReadFile(filepath.Join(r, "sub/subfile")) require.NoError(t, err) - if c.submodule { - b, err := ioutil.ReadFile(filepath.Join(r, "sub/subfile")) - require.NoError(t, err) - assert.Equal(t, "subcontents", string(b)) - } else { - _, err := os.Stat(filepath.Join(r, "sub/subfile")) - require.Error(t, err) - require.True(t, os.IsNotExist(err)) - } + assert.Equal(t, "subcontents", string(b)) + } else { + _, err := os.Stat(filepath.Join(r, "sub/subfile")) + require.Error(t, err) + require.True(t, os.IsNotExist(err)) } b, err := ioutil.ReadFile(filepath.Join(r, "Dockerfile"))