Skip to content

Commit

Permalink
Merge pull request #2489 from github/git-symbolic-ref
Browse files Browse the repository at this point in the history
Use `git symbolic-ref` to read the branch name for HEAD
  • Loading branch information
mislav authored Mar 3, 2020
2 parents badc983 + 64cfcdd commit 6740f5c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 34 deletions.
38 changes: 10 additions & 28 deletions git/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package git

import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
14 changes: 8 additions & 6 deletions github/localrepo.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 6740f5c

Please sign in to comment.