From 55ff0c0dee09b505ecd123f3f893e143651947bf Mon Sep 17 00:00:00 2001 From: Jesse Duffield Date: Sun, 17 Nov 2019 12:07:36 +1100 Subject: support detached heads when showing the selected branch --- pkg/commands/git.go | 15 +++++++++++++-- pkg/commands/loading_remotes.go | 7 ++++--- pkg/commands/remote_branch.go | 5 +++-- 3 files changed, 20 insertions(+), 7 deletions(-) (limited to 'pkg/commands') diff --git a/pkg/commands/git.go b/pkg/commands/git.go index 26f8aae32..65e17a3a1 100644 --- a/pkg/commands/git.go +++ b/pkg/commands/git.go @@ -6,6 +6,7 @@ import ( "os" "os/exec" "path/filepath" + "regexp" "strings" "time" @@ -21,6 +22,13 @@ import ( gogit "gopkg.in/src-d/go-git.v4" ) +// this takes something like: +// * (HEAD detached at 264fc6f5) +// remotes +// and returns '264fc6f5' as the second match + +const CurrentBranchNameRegex = `(?m)^\*.*?([^ ]*?)\)?$` + func verifyInGitRepo(runCmd func(string) error) error { return runCmd("git status") } @@ -325,8 +333,11 @@ func (c *GitCommand) NewBranch(name string) error { // CurrentBranchName is a function. func (c *GitCommand) CurrentBranchName() (string, error) { branchName, err := c.OSCommand.RunCommandWithOutput("git symbolic-ref --short HEAD") - if err != nil { - branchName, err = c.OSCommand.RunCommandWithOutput("git rev-parse --short HEAD") + if err != nil || branchName == "HEAD\n" { + output, err := c.OSCommand.RunCommandWithOutput("git branch --contains") + re := regexp.MustCompile(CurrentBranchNameRegex) + match := re.FindStringSubmatch(output) + branchName = match[1] if err != nil { return "", err } diff --git a/pkg/commands/loading_remotes.go b/pkg/commands/loading_remotes.go index dc5dcac44..c33eb1d37 100644 --- a/pkg/commands/loading_remotes.go +++ b/pkg/commands/loading_remotes.go @@ -22,14 +22,15 @@ func (c *GitCommand) GetRemotes() ([]*Remote, error) { // first step is to get our remotes from go-git remotes := make([]*Remote, len(goGitRemotes)) for i, goGitRemote := range goGitRemotes { - name := goGitRemote.Config().Name + remoteName := goGitRemote.Config().Name - re := regexp.MustCompile(fmt.Sprintf("%s\\/(.*)", name)) + re := regexp.MustCompile(fmt.Sprintf("%s\\/(.*)", remoteName)) matches := re.FindAllStringSubmatch(remoteBranchesStr, -1) branches := make([]*RemoteBranch, len(matches)) for j, match := range matches { branches[j] = &RemoteBranch{ - Name: match[1], + Name: match[1], + RemoteName: remoteName, } } diff --git a/pkg/commands/remote_branch.go b/pkg/commands/remote_branch.go index 18e58fa85..5016dc5bd 100644 --- a/pkg/commands/remote_branch.go +++ b/pkg/commands/remote_branch.go @@ -6,8 +6,9 @@ import ( // Remote Branch : A git remote branch type RemoteBranch struct { - Name string - Selected bool + Name string + Selected bool + RemoteName string } // GetDisplayStrings returns the display string of branch -- cgit v1.2.3