pr.go 1.6 KB
Newer Older
J
Johan Walles 已提交
1 2 3 4 5 6 7 8 9 10
package commands

import (
	"fmt"
	"strconv"

	"github.com/github/hub/github"
	"github.com/github/hub/utils"
)

11 12
var (
	cmdPr = &Command{
J
Johan Walles 已提交
13 14 15
		Run:          checkoutPr,
		GitExtension: false,
		Usage:        "pr checkout <PULLREQ-NUMBER> [<BRANCH>]",
16
		Long: `Check out the head of a pull request as a local branch.
J
Johan Walles 已提交
17 18

## Examples:
19
		$ hub pr checkout 73
J
Johan Walles 已提交
20 21 22 23 24
		> git fetch origin pull/73/head:jingweno-feature
		> git checkout jingweno-feature

## See also:

J
Johan Walles 已提交
25
hub-merge(1), hub(1), hub-checkout(1)
J
Johan Walles 已提交
26
`,
27 28 29 30
	}

	cmdCheckoutPr = &Command{
		Key: "checkout",
J
Johan Walles 已提交
31
		Run: checkoutPr,
32 33
	}
)
J
Johan Walles 已提交
34 35

func init() {
J
Johan Walles 已提交
36
	cmdPr.Use(cmdCheckoutPr)
J
Johan Walles 已提交
37
	CmdRunner.Use(cmdPr)
J
Johan Walles 已提交
38 39
}

J
Johan Walles 已提交
40
func checkoutPr(command *Command, args *Args) {
J
Johan Walles 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
	if args.ParamsSize() < 1 || args.ParamsSize() > 2 {
		utils.Check(fmt.Errorf("Error: Expected one or two arguments, got %d", args.ParamsSize()))
	}

	prNumberString := args.GetParam(0)
	_, err := strconv.Atoi(prNumberString)
	utils.Check(err)

	// Figure out the PR URL
	localRepo, err := github.LocalRepo()
	utils.Check(err)
	baseProject, err := localRepo.MainProject()
	utils.Check(err)
	host, err := github.CurrentConfig().PromptForHost(baseProject.Host)
	utils.Check(err)
	client := github.NewClientWithHost(host)
	pr, err := client.PullRequest(baseProject, prNumberString)
	utils.Check(err)

	if args.ParamsSize() == 1 {
		args.Replace(args.Executable, "checkout", pr.HtmlUrl)
	} else {
		args.Replace(args.Executable, "checkout", pr.HtmlUrl, args.GetParam(1))
	}

	// Call into the checkout code which already provides the functionality we're
	// after
	err = transformCheckoutArgs(args)
	utils.Check(err)
}