Skip to content

Commit f0801b2

Browse files
committed
Simplify reading current branch from git
1 parent 2c94616 commit f0801b2

File tree

2 files changed

+10
-50
lines changed

2 files changed

+10
-50
lines changed

context/context.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,12 +90,12 @@ func (c *fsContext) Branch() (string, error) {
9090
return c.branch, nil
9191
}
9292

93-
currentBranch, err := git.Head()
93+
currentBranch, err := git.CurrentBranch()
9494
if err != nil {
9595
return "", err
9696
}
9797

98-
c.branch = strings.Replace(currentBranch, "refs/heads/", "", 1)
98+
c.branch = currentBranch
9999
return c.branch, nil
100100
}
101101

git/git.go

Lines changed: 8 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -2,70 +2,30 @@ package git
22

33
import (
44
"bytes"
5+
"errors"
56
"fmt"
6-
"io/ioutil"
77
"net/url"
88
"os/exec"
9-
"path/filepath"
109
"regexp"
1110
"strings"
1211

1312
"github.com/github/gh-cli/utils"
1413
)
1514

16-
func Dir() (string, error) {
17-
dirCmd := exec.Command("git", "rev-parse", "-q", "--git-dir")
18-
output, err := utils.PrepareCmd(dirCmd).Output()
19-
if err != nil {
20-
return "", fmt.Errorf("Not a git repository (or any of the parent directories): .git")
21-
}
22-
23-
gitDir := firstLine(output)
24-
if !filepath.IsAbs(gitDir) {
25-
gitDir, err = filepath.Abs(gitDir)
26-
if err != nil {
27-
return "", err
28-
}
29-
gitDir = filepath.Clean(gitDir)
30-
}
31-
32-
return gitDir, nil
33-
}
34-
3515
func VerifyRef(ref string) bool {
3616
showRef := exec.Command("git", "show-ref", "--verify", "--quiet", ref)
3717
err := utils.PrepareCmd(showRef).Run()
3818
return err == nil
3919
}
4020

41-
func BranchAtRef(paths ...string) (name string, err error) {
42-
dir, err := Dir()
43-
if err != nil {
44-
return
45-
}
46-
47-
segments := []string{dir}
48-
segments = append(segments, paths...)
49-
path := filepath.Join(segments...)
50-
b, err := ioutil.ReadFile(path)
51-
if err != nil {
52-
return
53-
}
54-
55-
n := string(b)
56-
refPrefix := "ref: "
57-
if strings.HasPrefix(n, refPrefix) {
58-
name = strings.TrimPrefix(n, refPrefix)
59-
name = strings.TrimSpace(name)
60-
} else {
61-
err = fmt.Errorf("No branch info in %s: %s", path, n)
21+
func CurrentBranch() (string, error) {
22+
branchCmd := exec.Command("git", "branch", "--show-current")
23+
output, err := utils.PrepareCmd(branchCmd).Output()
24+
branchName := firstLine(output)
25+
if err == nil && branchName == "" {
26+
return "", errors.New("git: not on any branch")
6227
}
63-
64-
return
65-
}
66-
67-
func Head() (string, error) {
68-
return BranchAtRef("HEAD")
28+
return branchName, err
6929
}
7030

7131
func listRemotes() ([]string, error) {

0 commit comments

Comments
 (0)