Merge pull request #129 from github/pr-arg-selector

Support issue/PR URLs & PR branch names passed as arguments
This commit is contained in:
Mislav Marohnić 2019-12-04 22:03:07 +01:00 committed by GitHub
commit 551f365bfc
8 changed files with 363 additions and 69 deletions

View file

@ -202,3 +202,35 @@ func IssueList(client *Client, ghRepo Repo, state string, labels []string, assig
return resp.Repository.Issues.Nodes, nil
}
func IssueByNumber(client *Client, ghRepo Repo, number int) (*Issue, error) {
type response struct {
Repository struct {
Issue Issue
}
}
query := `
query($owner: String!, $repo: String!, $issue_number: Int!) {
repository(owner: $owner, name: $repo) {
issue(number: $issue_number) {
number
url
}
}
}`
variables := map[string]interface{}{
"owner": ghRepo.RepoOwner(),
"repo": ghRepo.RepoName(),
"issue_number": number,
}
var resp response
err := client.GraphQL(query, variables, &resp)
if err != nil {
return nil, err
}
return &resp.Repository.Issue, nil
}

View file

@ -285,6 +285,7 @@ func PullRequestByNumber(client *Client, ghRepo Repo, number int) (*PullRequest,
query($owner: String!, $repo: String!, $pr_number: Int!) {
repository(owner: $owner, name: $repo) {
pullRequest(number: $pr_number) {
number
headRefName
headRepositoryOwner {
login

View file

@ -4,10 +4,12 @@ import (
"fmt"
"io"
"os"
"regexp"
"strconv"
"strings"
"github.com/github/gh-cli/api"
"github.com/github/gh-cli/context"
"github.com/github/gh-cli/utils"
"github.com/pkg/errors"
"github.com/spf13/cobra"
@ -183,19 +185,36 @@ func issueView(cmd *cobra.Command, args []string) error {
if err != nil {
return err
}
var openURL string
if number, err := strconv.Atoi(args[0]); err == nil {
// TODO: move URL generation into GitHubRepository
openURL = fmt.Sprintf("https://github.com/%s/%s/issues/%d", baseRepo.RepoOwner(), baseRepo.RepoName(), number)
} else {
return fmt.Errorf("invalid issue number: '%s'", args[0])
apiClient, err := apiClientForContext(ctx)
if err != nil {
return err
}
issue, err := issueFromArg(apiClient, baseRepo, args[0])
if err != nil {
return err
}
openURL := issue.URL
cmd.Printf("Opening %s in your browser.\n", openURL)
return utils.OpenInBrowser(openURL)
}
var issueURLRE = regexp.MustCompile(`^https://github\.com/([^/]+)/([^/]+)/issues/(\d+)`)
func issueFromArg(apiClient *api.Client, baseRepo context.GitHubRepository, arg string) (*api.Issue, error) {
if issueNumber, err := strconv.Atoi(arg); err == nil {
return api.IssueByNumber(apiClient, baseRepo, issueNumber)
}
if m := issueURLRE.FindStringSubmatch(arg); m != nil {
issueNumber, _ := strconv.Atoi(m[3])
return api.IssueByNumber(apiClient, baseRepo, issueNumber)
}
return nil, fmt.Errorf("invalid issue format: %q", arg)
}
func issueCreate(cmd *cobra.Command, args []string) error {
ctx := contextForCommand(cmd)

View file

@ -96,9 +96,12 @@ func TestIssueView(t *testing.T) {
initBlankContext("OWNER/REPO", "master")
http := initFakeHTTP()
jsonFile, _ := os.Open("../test/fixtures/issueView.json")
defer jsonFile.Close()
http.StubResponse(200, jsonFile)
http.StubResponse(200, bytes.NewBufferString(`
{ "data": { "repository": { "issue": {
"number": 123,
"url": "https://github.com/OWNER/REPO/issues/123"
} } } }
`))
var seenCmd *exec.Cmd
restoreCmd := utils.SetPrepareCmd(func(cmd *exec.Cmd) utils.Runnable {
@ -107,7 +110,7 @@ func TestIssueView(t *testing.T) {
})
defer restoreCmd()
output, err := RunCommand(issueViewCmd, "issue view 8")
output, err := RunCommand(issueViewCmd, "issue view 123")
if err != nil {
t.Errorf("error running command `issue view`: %v", err)
}
@ -120,9 +123,68 @@ func TestIssueView(t *testing.T) {
t.Fatal("expected a command to run")
}
url := seenCmd.Args[len(seenCmd.Args)-1]
if url != "https://github.com/OWNER/REPO/issues/8" {
t.Errorf("got: %q", url)
eq(t, url, "https://github.com/OWNER/REPO/issues/123")
}
func TestIssueView_notFound(t *testing.T) {
initBlankContext("OWNER/REPO", "master")
http := initFakeHTTP()
http.StubResponse(200, bytes.NewBufferString(`
{ "errors": [
{ "message": "Could not resolve to an Issue with the number of 9999." }
] }
`))
var seenCmd *exec.Cmd
restoreCmd := utils.SetPrepareCmd(func(cmd *exec.Cmd) utils.Runnable {
seenCmd = cmd
return &outputStub{}
})
defer restoreCmd()
_, err := RunCommand(issueViewCmd, "issue view 9999")
if err == nil || err.Error() != "graphql error: 'Could not resolve to an Issue with the number of 9999.'" {
t.Errorf("error running command `issue view`: %v", err)
}
if seenCmd != nil {
t.Fatal("did not expect any command to run")
}
}
func TestIssueView_urlArg(t *testing.T) {
initBlankContext("OWNER/REPO", "master")
http := initFakeHTTP()
http.StubResponse(200, bytes.NewBufferString(`
{ "data": { "repository": { "issue": {
"number": 123,
"url": "https://github.com/OWNER/REPO/issues/123"
} } } }
`))
var seenCmd *exec.Cmd
restoreCmd := utils.SetPrepareCmd(func(cmd *exec.Cmd) utils.Runnable {
seenCmd = cmd
return &outputStub{}
})
defer restoreCmd()
output, err := RunCommand(issueViewCmd, "issue view https://github.com/OWNER/REPO/issues/123")
if err != nil {
t.Errorf("error running command `issue view`: %v", err)
}
if output == "" {
t.Errorf("command output expected got an empty string")
}
if seenCmd == nil {
t.Fatal("expected a command to run")
}
url := seenCmd.Args[len(seenCmd.Args)-1]
eq(t, url, "https://github.com/OWNER/REPO/issues/123")
}
func TestIssueCreate(t *testing.T) {

View file

@ -219,14 +219,18 @@ func prView(cmd *cobra.Command, args []string) error {
return err
}
apiClient, err := apiClientForContext(ctx)
if err != nil {
return err
}
var openURL string
if len(args) > 0 {
if prNumber, err := strconv.Atoi(args[0]); err == nil {
// TODO: move URL generation into GitHubRepository
openURL = fmt.Sprintf("https://github.com/%s/%s/pull/%d", baseRepo.RepoOwner(), baseRepo.RepoName(), prNumber)
} else {
return fmt.Errorf("invalid pull request number: '%s'", args[0])
pr, err := prFromArg(apiClient, baseRepo, args[0])
if err != nil {
return err
}
openURL = pr.URL
} else {
prNumber, branchWithOwner, err := prSelectorForCurrentBranch(ctx)
if err != nil {
@ -236,11 +240,6 @@ func prView(cmd *cobra.Command, args []string) error {
if prNumber > 0 {
openURL = fmt.Sprintf("https://github.com/%s/%s/pull/%d", baseRepo.RepoOwner(), baseRepo.RepoName(), prNumber)
} else {
apiClient, err := apiClientForContext(ctx)
if err != nil {
return err
}
pr, err := api.PullRequestForBranch(apiClient, baseRepo, branchWithOwner)
if err != nil {
return err
@ -253,6 +252,21 @@ func prView(cmd *cobra.Command, args []string) error {
return utils.OpenInBrowser(openURL)
}
var prURLRE = regexp.MustCompile(`^https://github\.com/([^/]+)/([^/]+)/pull/(\d+)`)
func prFromArg(apiClient *api.Client, baseRepo context.GitHubRepository, arg string) (*api.PullRequest, error) {
if prNumber, err := strconv.Atoi(arg); err == nil {
return api.PullRequestByNumber(apiClient, baseRepo, prNumber)
}
if m := prURLRE.FindStringSubmatch(arg); m != nil {
prNumber, _ := strconv.Atoi(m[3])
return api.PullRequestByNumber(apiClient, baseRepo, prNumber)
}
return api.PullRequestForBranch(apiClient, baseRepo, arg)
}
func prSelectorForCurrentBranch(ctx context.Context) (prNumber int, prHeadRef string, err error) {
baseRepo, err := ctx.BaseRepo()
if err != nil {
@ -299,11 +313,6 @@ func prSelectorForCurrentBranch(ctx context.Context) (prNumber int, prHeadRef st
}
func prCheckout(cmd *cobra.Command, args []string) error {
prNumber, err := strconv.Atoi(args[0])
if err != nil {
return err
}
ctx := contextForCommand(cmd)
currentBranch, _ := ctx.Branch()
remotes, err := ctx.Remotes()
@ -320,7 +329,7 @@ func prCheckout(cmd *cobra.Command, args []string) error {
return err
}
pr, err := api.PullRequestByNumber(apiClient, baseRemote, prNumber)
pr, err := prFromArg(apiClient, baseRemote, args[0])
if err != nil {
return err
}
@ -357,7 +366,7 @@ func prCheckout(cmd *cobra.Command, args []string) error {
newBranchName = fmt.Sprintf("%s/%s", pr.HeadRepositoryOwner.Login, newBranchName)
}
ref := fmt.Sprintf("refs/pull/%d/head", prNumber)
ref := fmt.Sprintf("refs/pull/%d/head", pr.Number)
if newBranchName == currentBranch {
// PR head matches currently checked out branch
cmdQueue = append(cmdQueue, []string{"git", "fetch", baseRemote.Name, ref})

View file

@ -23,6 +23,7 @@ func TestPRCheckout_sameRepo(t *testing.T) {
http.StubResponse(200, bytes.NewBufferString(`
{ "data": { "repository": { "pullRequest": {
"number": 123,
"headRefName": "feature",
"headRepositoryOwner": {
"login": "hubot"
@ -61,6 +62,104 @@ func TestPRCheckout_sameRepo(t *testing.T) {
eq(t, strings.Join(ranCommands[3], " "), "git config branch.feature.merge refs/heads/feature")
}
func TestPRCheckout_urlArg(t *testing.T) {
ctx := context.NewBlank()
ctx.SetBranch("master")
ctx.SetRemotes(map[string]string{
"origin": "OWNER/REPO",
})
initContext = func() context.Context {
return ctx
}
http := initFakeHTTP()
http.StubResponse(200, bytes.NewBufferString(`
{ "data": { "repository": { "pullRequest": {
"number": 123,
"headRefName": "feature",
"headRepositoryOwner": {
"login": "hubot"
},
"headRepository": {
"name": "REPO",
"defaultBranchRef": {
"name": "master"
}
},
"isCrossRepository": false,
"maintainerCanModify": false
} } } }
`))
ranCommands := [][]string{}
restoreCmd := utils.SetPrepareCmd(func(cmd *exec.Cmd) utils.Runnable {
switch strings.Join(cmd.Args, " ") {
case "git show-ref --verify --quiet refs/heads/feature":
return &errorStub{"exit status: 1"}
default:
ranCommands = append(ranCommands, cmd.Args)
return &outputStub{}
}
})
defer restoreCmd()
output, err := RunCommand(prCheckoutCmd, `pr checkout https://github.com/OWNER/REPO/pull/123/files`)
eq(t, err, nil)
eq(t, output, "")
eq(t, len(ranCommands), 4)
eq(t, strings.Join(ranCommands[1], " "), "git checkout -b feature --no-track origin/feature")
}
func TestPRCheckout_branchArg(t *testing.T) {
ctx := context.NewBlank()
ctx.SetBranch("master")
ctx.SetRemotes(map[string]string{
"origin": "OWNER/REPO",
})
initContext = func() context.Context {
return ctx
}
http := initFakeHTTP()
http.StubResponse(200, bytes.NewBufferString(`
{ "data": { "repository": { "pullRequests": { "nodes": [
{ "number": 123,
"headRefName": "feature",
"headRepositoryOwner": {
"login": "hubot"
},
"headRepository": {
"name": "REPO",
"defaultBranchRef": {
"name": "master"
}
},
"isCrossRepository": true,
"maintainerCanModify": false }
] } } } }
`))
ranCommands := [][]string{}
restoreCmd := utils.SetPrepareCmd(func(cmd *exec.Cmd) utils.Runnable {
switch strings.Join(cmd.Args, " ") {
case "git show-ref --verify --quiet refs/heads/feature":
return &errorStub{"exit status: 1"}
default:
ranCommands = append(ranCommands, cmd.Args)
return &outputStub{}
}
})
defer restoreCmd()
output, err := RunCommand(prCheckoutCmd, `pr checkout hubot:feature`)
eq(t, err, nil)
eq(t, output, "")
eq(t, len(ranCommands), 5)
eq(t, strings.Join(ranCommands[1], " "), "git fetch origin refs/pull/123/head:feature")
}
func TestPRCheckout_existingBranch(t *testing.T) {
ctx := context.NewBlank()
ctx.SetBranch("master")
@ -74,6 +173,7 @@ func TestPRCheckout_existingBranch(t *testing.T) {
http.StubResponse(200, bytes.NewBufferString(`
{ "data": { "repository": { "pullRequest": {
"number": 123,
"headRefName": "feature",
"headRepositoryOwner": {
"login": "hubot"
@ -125,6 +225,7 @@ func TestPRCheckout_differentRepo_remoteExists(t *testing.T) {
http.StubResponse(200, bytes.NewBufferString(`
{ "data": { "repository": { "pullRequest": {
"number": 123,
"headRefName": "feature",
"headRepositoryOwner": {
"login": "hubot"
@ -176,6 +277,7 @@ func TestPRCheckout_differentRepo(t *testing.T) {
http.StubResponse(200, bytes.NewBufferString(`
{ "data": { "repository": { "pullRequest": {
"number": 123,
"headRefName": "feature",
"headRepositoryOwner": {
"login": "hubot"
@ -227,6 +329,7 @@ func TestPRCheckout_differentRepo_existingBranch(t *testing.T) {
http.StubResponse(200, bytes.NewBufferString(`
{ "data": { "repository": { "pullRequest": {
"number": 123,
"headRefName": "feature",
"headRepositoryOwner": {
"login": "hubot"
@ -276,6 +379,7 @@ func TestPRCheckout_differentRepo_currentBranch(t *testing.T) {
http.StubResponse(200, bytes.NewBufferString(`
{ "data": { "repository": { "pullRequest": {
"number": 123,
"headRefName": "feature",
"headRepositoryOwner": {
"login": "hubot"
@ -325,6 +429,7 @@ func TestPRCheckout_maintainerCanModify(t *testing.T) {
http.StubResponse(200, bytes.NewBufferString(`
{ "data": { "repository": { "pullRequest": {
"number": 123,
"headRefName": "feature",
"headRepositoryOwner": {
"login": "hubot"

View file

@ -251,7 +251,109 @@ func TestPRView_numberArg(t *testing.T) {
t.Fatal("expected a command to run")
}
url := seenCmd.Args[len(seenCmd.Args)-1]
if url != "https://github.com/OWNER/REPO/pull/23" {
t.Errorf("got: %q", url)
}
eq(t, url, "https://github.com/OWNER/REPO/pull/23")
}
func TestPRView_urlArg(t *testing.T) {
initBlankContext("OWNER/REPO", "master")
http := initFakeHTTP()
http.StubResponse(200, bytes.NewBufferString(`
{ "data": { "repository": { "pullRequest": {
"url": "https://github.com/OWNER/REPO/pull/23"
} } } }
`))
var seenCmd *exec.Cmd
restoreCmd := utils.SetPrepareCmd(func(cmd *exec.Cmd) utils.Runnable {
seenCmd = cmd
return &outputStub{}
})
defer restoreCmd()
output, err := RunCommand(prViewCmd, "pr view https://github.com/OWNER/REPO/pull/23/files")
if err != nil {
t.Errorf("error running command `pr view`: %v", err)
}
if output == "" {
t.Errorf("command output expected got an empty string")
}
if seenCmd == nil {
t.Fatal("expected a command to run")
}
url := seenCmd.Args[len(seenCmd.Args)-1]
eq(t, url, "https://github.com/OWNER/REPO/pull/23")
}
func TestPRView_branchArg(t *testing.T) {
initBlankContext("OWNER/REPO", "master")
http := initFakeHTTP()
http.StubResponse(200, bytes.NewBufferString(`
{ "data": { "repository": { "pullRequests": { "nodes": [
{ "headRefName": "blueberries",
"isCrossRepository": false,
"url": "https://github.com/OWNER/REPO/pull/23" }
] } } } }
`))
var seenCmd *exec.Cmd
restoreCmd := utils.SetPrepareCmd(func(cmd *exec.Cmd) utils.Runnable {
seenCmd = cmd
return &outputStub{}
})
defer restoreCmd()
output, err := RunCommand(prViewCmd, "pr view blueberries")
if err != nil {
t.Errorf("error running command `pr view`: %v", err)
}
if output == "" {
t.Errorf("command output expected got an empty string")
}
if seenCmd == nil {
t.Fatal("expected a command to run")
}
url := seenCmd.Args[len(seenCmd.Args)-1]
eq(t, url, "https://github.com/OWNER/REPO/pull/23")
}
func TestPRView_branchWithOwnerArg(t *testing.T) {
initBlankContext("OWNER/REPO", "master")
http := initFakeHTTP()
http.StubResponse(200, bytes.NewBufferString(`
{ "data": { "repository": { "pullRequests": { "nodes": [
{ "headRefName": "blueberries",
"isCrossRepository": true,
"headRepositoryOwner": { "login": "hubot" },
"url": "https://github.com/hubot/REPO/pull/23" }
] } } } }
`))
var seenCmd *exec.Cmd
restoreCmd := utils.SetPrepareCmd(func(cmd *exec.Cmd) utils.Runnable {
seenCmd = cmd
return &outputStub{}
})
defer restoreCmd()
output, err := RunCommand(prViewCmd, "pr view hubot:blueberries")
if err != nil {
t.Errorf("error running command `pr view`: %v", err)
}
if output == "" {
t.Errorf("command output expected got an empty string")
}
if seenCmd == nil {
t.Fatal("expected a command to run")
}
url := seenCmd.Args[len(seenCmd.Args)-1]
eq(t, url, "https://github.com/hubot/REPO/pull/23")
}

View file

@ -1,36 +0,0 @@
{
"data": {
"repository": {
"issues": {
"edges": [
{
"node": {
"number": 8,
"title": "rabbits eat carrots",
"url": "https://github.com/github/gh-cli/pull/10"
}
},
{
"node": {
"number": 9,
"title": "corey thinks squash tastes bad"
}
},
{
"node": {
"number": 10,
"title": "broccoli is a superfood"
}
},
{
"node": {
"number": 11,
"title": "swiss chard is neutral"
}
}
]
}
},
"pageInfo": { "hasNextPage": false }
}
}