diff --git a/command/pr.go b/command/pr.go index e92fa7cf0..f1c1eb101 100644 --- a/command/pr.go +++ b/command/pr.go @@ -116,7 +116,7 @@ func prStatus(cmd *cobra.Command, args []string) error { repoOverride, _ := cmd.Flags().GetString("repo") currentPRNumber, currentPRHeadRef, err := prSelectorForCurrentBranch(ctx, baseRepo) - if err != nil && repoOverride == "" && err.Error() != "git: not on any branch" { + if err != nil && repoOverride == "" && err != git.ErrNotOnAnyBranch { return fmt.Errorf("could not query for pull request for current branch: %w", err) } diff --git a/context/context.go b/context/context.go index 236f9e722..4f1aa10ba 100644 --- a/context/context.go +++ b/context/context.go @@ -207,7 +207,11 @@ func (c *fsContext) Branch() (string, error) { } currentBranch, err := git.CurrentBranch() - if err != nil { + switch err { + case nil: + case git.ErrNotOnAnyBranch: + return "", err + default: return "", fmt.Errorf("could not determine current branch: %w", err) } diff --git a/git/git.go b/git/git.go index 355f905f0..ff40adde3 100644 --- a/git/git.go +++ b/git/git.go @@ -13,6 +13,9 @@ import ( "github.com/cli/cli/internal/run" ) +// ErrNotOnAnyBranch indicates that the users is in detached HEAD state +var ErrNotOnAnyBranch = errors.New("git: not on any branch") + // Ref represents a git commit reference type Ref struct { Hash string @@ -64,7 +67,7 @@ func CurrentBranch() (string, error) { if errors.As(err, &cmdErr) { if cmdErr.Stderr.Len() == 0 { // Detached head - return "", errors.New("git: not on any branch") + return "", ErrNotOnAnyBranch } } diff --git a/git/git_test.go b/git/git_test.go index c84023e40..1a8f32677 100644 --- a/git/git_test.go +++ b/git/git_test.go @@ -67,9 +67,8 @@ func Test_CurrentBranch_detached_head(t *testing.T) { if err == nil { t.Errorf("expected an error") } - expectedError := "git: not on any branch" - if err.Error() != expectedError { - t.Errorf("got unexpected error: %s instead of %s", err.Error(), expectedError) + if err != ErrNotOnAnyBranch { + t.Errorf("got unexpected error: %s instead of %s", err, ErrNotOnAnyBranch) } if len(cs.Calls) != 1 { t.Errorf("expected 1 git call, saw %d", len(cs.Calls))