From 661af29d46517c69871f3980d9d9be2c389050f2 Mon Sep 17 00:00:00 2001 From: CrazyMax Date: Fri, 3 Feb 2023 14:29:43 +0100 Subject: [PATCH] build: check reachable git commits Signed-off-by: CrazyMax (cherry picked from commit fd5884189cc0d24a92c98fd4747847361c49c9c0) --- build/git.go | 2 +- util/gitutil/gitutil.go | 9 +++++++++ util/gitutil/gitutil_test.go | 12 ++++++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/build/git.go b/build/git.go index 47f3fc1c..e7b5d8eb 100644 --- a/build/git.go +++ b/build/git.go @@ -64,7 +64,7 @@ func getGitAttributes(ctx context.Context, contextPath string, dockerfilePath st return res, nil } - if sha, err := gitc.FullCommit(); err != nil { + if sha, err := gitc.FullCommit(); err != nil && !gitutil.IsUnknownRevision(err) { return res, errors.Wrapf(err, "buildx: failed to get git commit") } else if sha != "" { if gitc.IsDirty() { diff --git a/util/gitutil/gitutil.go b/util/gitutil/gitutil.go index 74ec513e..69e6aa31 100644 --- a/util/gitutil/gitutil.go +++ b/util/gitutil/gitutil.go @@ -138,3 +138,12 @@ func (c *Git) clean(out string, err error) (string, error) { } return out, err } + +func IsUnknownRevision(err error) bool { + if err == nil { + return false + } + // https://github.com/git/git/blob/a6a323b31e2bcbac2518bddec71ea7ad558870eb/setup.c#L204 + errMsg := strings.ToLower(err.Error()) + return strings.Contains(errMsg, "unknown revision or path not in the working tree") || strings.Contains(errMsg, "bad revision") +} diff --git a/util/gitutil/gitutil_test.go b/util/gitutil/gitutil_test.go index 28992646..050d4515 100644 --- a/util/gitutil/gitutil_test.go +++ b/util/gitutil/gitutil_test.go @@ -46,6 +46,18 @@ func TestGitShortCommit(t *testing.T) { require.Equal(t, 7, len(out)) } +func TestGitFullCommitErr(t *testing.T) { + Mktmp(t) + c, err := New() + require.NoError(t, err) + + GitInit(c, t) + + _, err = c.FullCommit() + require.Error(t, err) + require.True(t, IsUnknownRevision(err)) +} + func TestGitTagsPointsAt(t *testing.T) { Mktmp(t) c, err := New()