From ea7503bc258e11529e6e426bf5c231dfc603aff2 Mon Sep 17 00:00:00 2001 From: Robert Stupp Date: Mon, 3 May 2021 16:32:00 +0200 Subject: [PATCH] Prefer go-git to find the reference name (#633) Walking the directory tree underneath `.git/refs` is not reliable, as it usually does not return tags, especially for freshly cloned repos and/or tags fetched from a remote. The go-git library provides an iterator over all git references. This approach prefers a reference (tag, branch) from go-git, if found. If none is found, it falls back to the previous implementation. --- pkg/common/git.go | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/pkg/common/git.go b/pkg/common/git.go index e88266a..2cfecf8 100644 --- a/pkg/common/git.go +++ b/pkg/common/git.go @@ -71,6 +71,40 @@ func FindGitRef(file string) (string, error) { log.Debugf("HEAD points to '%s'", ref) + // Prefer the git library to iterate over the references and find a matching tag or branch. + var refTag = "" + var refBranch = "" + r, err := git.PlainOpen(filepath.Join(gitDir, "..")) + if err == nil { + iter, err := r.References() + if err == nil { + for { + r, err := iter.Next() + if r == nil || err != nil { + break + } + log.Debugf("Reference: name=%s sha=%s", r.Name().String(), r.Hash().String()) + if r.Hash().String() == ref { + if r.Name().IsTag() { + refTag = r.Name().String() + } + if r.Name().IsBranch() { + refBranch = r.Name().String() + } + } + } + iter.Close() + } + } + if refTag != "" { + return refTag, nil + } + if refBranch != "" { + return refBranch, nil + } + + // If the above doesn't work, fall back to the old way + // try tags first tag, err := findGitPrettyRef(ref, gitDir, "refs/tags") if err != nil || tag != "" {