Fixed gh pr checkout on detached HEAD

This commit is contained in:
Martín Montes 2020-09-22 00:25:49 +02:00
parent e3f21a58cc
commit bb1005be51
2 changed files with 46 additions and 9 deletions

View file

@ -3,6 +3,11 @@ package checkout
import (
"errors"
"fmt"
"net/http"
"os"
"os/exec"
"strings"
"github.com/cli/cli/api"
"github.com/cli/cli/context"
"github.com/cli/cli/git"
@ -13,10 +18,6 @@ import (
"github.com/cli/cli/pkg/cmdutil"
"github.com/cli/cli/pkg/iostreams"
"github.com/spf13/cobra"
"net/http"
"os"
"os/exec"
"strings"
)
type CheckoutOptions struct {
@ -70,11 +71,6 @@ func NewCmdCheckout(f *cmdutil.Factory, runF func(*CheckoutOptions) error) *cobr
}
func checkoutRun(opts *CheckoutOptions) error {
currentBranch, err := opts.Branch()
if err != nil {
return err
}
remotes, err := opts.Remotes()
if err != nil {
return err
@ -133,6 +129,7 @@ func checkoutRun(opts *CheckoutOptions) error {
}
} else {
// no git remote for PR head
currentBranch, _ := opts.Branch()
defaultBranchName, err := api.RepoDefaultBranch(apiClient, baseRepo)
if err != nil {

View file

@ -448,6 +448,46 @@ func TestPRCheckout_differentRepo_existingBranch(t *testing.T) {
eq(t, strings.Join(ranCommands[1], " "), "git checkout feature")
}
func TestPRCheckout_detachedHead(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
http.Register(httpmock.GraphQL(`query PullRequestByNumber\b`), httpmock.StringResponse(`
{ "data": { "repository": { "pullRequest": {
"number": 123,
"headRefName": "feature",
"headRepositoryOwner": {
"login": "hubot"
},
"headRepository": {
"name": "REPO"
},
"isCrossRepository": true,
"maintainerCanModify": true
} } } }
`))
ranCommands := [][]string{}
restoreCmd := run.SetPrepareCmd(func(cmd *exec.Cmd) run.Runnable {
switch strings.Join(cmd.Args, " ") {
case "git config branch.feature.merge":
return &test.OutputStub{Out: []byte("refs/heads/feature\n")}
default:
ranCommands = append(ranCommands, cmd.Args)
return &test.OutputStub{}
}
})
defer restoreCmd()
output, err := runCommand(http, nil, "", `123`)
eq(t, err, nil)
eq(t, output.String(), "")
eq(t, len(ranCommands), 2)
eq(t, strings.Join(ranCommands[0], " "), "git fetch origin refs/pull/123/head:feature")
eq(t, strings.Join(ranCommands[1], " "), "git checkout feature")
}
func TestPRCheckout_differentRepo_currentBranch(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)