From 64cfcdd19e754a998ebc4e81861ab8512ee92c24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Sun, 1 Mar 2020 10:52:11 +0100 Subject: [PATCH] Use `git symbolic-ref` to read the branch name for HEAD This affects reading the current branch as well as reading the default branch for a remote. Because we're no longer trying to read the ref manually from the filesystem, this approach works with git worktrees. --- git/git.go | 38 ++++++++++---------------------------- github/localrepo.go | 14 ++++++++------ 2 files changed, 18 insertions(+), 34 deletions(-) diff --git a/git/git.go b/git/git.go index 7921e77e3..88848b8ce 100644 --- a/git/git.go +++ b/git/git.go @@ -2,7 +2,6 @@ package git import ( "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -105,32 +104,6 @@ func HasFile(segments ...string) bool { return false } -func BranchAtRef(paths ...string) (name string, err error) { - dir, err := Dir() - if err != nil { - return - } - - segments := []string{dir} - segments = append(segments, paths...) - path := filepath.Join(segments...) - b, err := ioutil.ReadFile(path) - if err != nil { - return - } - - n := string(b) - refPrefix := "ref: " - if strings.HasPrefix(n, refPrefix) { - name = strings.TrimPrefix(n, refPrefix) - name = strings.TrimSpace(name) - } else { - err = fmt.Errorf("No branch info in %s: %s", path, n) - } - - return -} - func Editor() (string, error) { varCmd := gitCmd("var", "GIT_EDITOR") varCmd.Stderr = nil @@ -143,9 +116,18 @@ func Editor() (string, error) { } func Head() (string, error) { - return BranchAtRef("HEAD") + return SymbolicRef("HEAD") +} + +// SymbolicRef reads a branch name from a ref such as "HEAD" +func SymbolicRef(ref string) (string, error) { + refCmd := gitCmd("symbolic-ref", ref) + refCmd.Stderr = nil + output, err := refCmd.Output() + return firstLine(output), err } +// SymbolicFullName reads a branch name from a ref such as "@{upstream}" func SymbolicFullName(name string) (string, error) { parseCmd := gitCmd("rev-parse", "--symbolic-full-name", name) parseCmd.Stderr = nil diff --git a/github/localrepo.go b/github/localrepo.go index bee18717a..ad9e318b9 100644 --- a/github/localrepo.go +++ b/github/localrepo.go @@ -113,14 +113,16 @@ func (r *GitHubRepo) MasterBranch() *Branch { } func (r *GitHubRepo) DefaultBranch(remote *Remote) *Branch { - var name string - if remote != nil { - name, _ = git.BranchAtRef("refs", "remotes", remote.Name, "HEAD") + b := Branch{ + Repo: r, + Name: "refs/heads/master", } - if name == "" { - name = "refs/heads/master" + if remote != nil { + if name, err := git.SymbolicRef(fmt.Sprintf("refs/remotes/%s/HEAD", remote.Name)); err == nil { + b.Name = name + } } - return &Branch{r, name} + return &b } func (r *GitHubRepo) RemoteBranchAndProject(owner string, preferUpstream bool) (branch *Branch, project *Project, err error) {