Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use git symbolic-ref to read the branch name for HEAD #2489

Merged
merged 1 commit into from
Mar 3, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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