diff --git a/pkg/cmd/pr/checkout/checkout.go b/pkg/cmd/pr/checkout/checkout.go index d4249740e..30a59a7ca 100644 --- a/pkg/cmd/pr/checkout/checkout.go +++ b/pkg/cmd/pr/checkout/checkout.go @@ -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 { diff --git a/pkg/cmd/pr/checkout/checkout_test.go b/pkg/cmd/pr/checkout/checkout_test.go index ea9926018..2ca060587 100644 --- a/pkg/cmd/pr/checkout/checkout_test.go +++ b/pkg/cmd/pr/checkout/checkout_test.go @@ -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)