repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/status/status_test.go | pkg/cmd/pr/status/status_test.go | package status
import (
"bytes"
"io"
"net/http"
"regexp"
"strings"
"testing"
"github.com/cli/cli/v2/context"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/config"
fd "github.com/cli/cli/v2/internal/featuredetection"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/run"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/test"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
)
func runCommand(rt http.RoundTripper, branch string, isTTY bool, cli string) (*test.CmdOut, error) {
return runCommandWithDetector(rt, branch, isTTY, cli, &fd.DisabledDetectorMock{})
}
func runCommandWithDetector(rt http.RoundTripper, branch string, isTTY bool, cli string, detector fd.Detector) (*test.CmdOut, error) {
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdoutTTY(isTTY)
ios.SetStdinTTY(isTTY)
ios.SetStderrTTY(isTTY)
factory := &cmdutil.Factory{
IOStreams: ios,
HttpClient: func() (*http.Client, error) {
return &http.Client{Transport: rt}, nil
},
Config: func() (gh.Config, error) {
return config.NewBlankConfig(), nil
},
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.New("OWNER", "REPO"), nil
},
Remotes: func() (context.Remotes, error) {
return context.Remotes{
{
Remote: &git.Remote{Name: "origin"},
Repo: ghrepo.New("OWNER", "REPO"),
},
}, nil
},
Branch: func() (string, error) {
if branch == "" {
return "", git.ErrNotOnAnyBranch
}
return branch, nil
},
GitClient: &git.Client{GitPath: "some/path/git"},
}
withProvidedDetector := func(opts *StatusOptions) error {
opts.Detector = detector
return statusRun(opts)
}
cmd := NewCmdStatus(factory, withProvidedDetector)
cmd.PersistentFlags().StringP("repo", "R", "", "")
argv, err := shlex.Split(cli)
if err != nil {
return nil, err
}
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
_, err = cmd.ExecuteC()
return &test.CmdOut{
OutBuf: stdout,
ErrBuf: stderr,
}, err
}
func initFakeHTTP() *httpmock.Registry {
return &httpmock.Registry{}
}
func TestPRStatus(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(httpmock.GraphQL(`query PullRequestStatus\b`), httpmock.FileResponse("./fixtures/prStatus.json"))
// stub successful git commands
rs, cleanup := run.Stub()
defer cleanup(t)
rs.Register(`git rev-parse --symbolic-full-name blueberries@{push}`, 128, "")
rs.Register(`git config --get-regexp \^branch\\.`, 0, "")
rs.Register(`git config remote.pushDefault`, 0, "")
rs.Register(`git config push.default`, 1, "")
output, err := runCommand(http, "blueberries", true, "")
if err != nil {
t.Errorf("error running command `pr status`: %v", err)
}
expectedPrs := []*regexp.Regexp{
regexp.MustCompile(`#8.*\[strawberries\]`),
regexp.MustCompile(`#9.*\[apples\].*β Auto-merge enabled`),
regexp.MustCompile(`#10.*\[blueberries\]`),
regexp.MustCompile(`#11.*\[figs\]`),
}
for _, r := range expectedPrs {
if !r.MatchString(output.String()) {
t.Errorf("output did not match regexp /%s/", r)
}
}
}
func TestPRStatus_reviewsAndChecks(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
// status,conclusion matches the old StatusContextRollup query
http.Register(httpmock.GraphQL(`status,conclusion`), httpmock.FileResponse("./fixtures/prStatusChecks.json"))
// stub successful git command
rs, cleanup := run.Stub()
defer cleanup(t)
rs.Register(`git config --get-regexp \^branch\\.`, 0, "")
rs.Register(`git config remote.pushDefault`, 0, "")
rs.Register(`git rev-parse --symbolic-full-name blueberries@{push}`, 128, "")
rs.Register(`git config push.default`, 1, "")
output, err := runCommand(http, "blueberries", true, "")
if err != nil {
t.Errorf("error running command `pr status`: %v", err)
}
expected := []string{
"β Checks passing + Changes requested ! Merge conflict status unknown",
"- Checks pending β 2 Approved",
"Γ 1/3 checks failing - Review required β No merge conflicts",
"β Checks passing Γ Merge conflicts",
}
for _, line := range expected {
if !strings.Contains(output.String(), line) {
t.Errorf("output did not contain %q: %q", line, output.String())
}
}
}
func TestPRStatus_reviewsAndChecksWithStatesByCount(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
// checkRunCount,checkRunCountsByState matches the new StatusContextRollup query
http.Register(httpmock.GraphQL(`checkRunCount,checkRunCountsByState`), httpmock.FileResponse("./fixtures/prStatusChecksWithStatesByCount.json"))
// stub successful git command
rs, cleanup := run.Stub()
defer cleanup(t)
rs.Register(`git config --get-regexp \^branch\\.`, 0, "")
rs.Register(`git config remote.pushDefault`, 0, "")
rs.Register(`git rev-parse --symbolic-full-name blueberries@{push}`, 128, "")
rs.Register(`git config push.default`, 1, "")
output, err := runCommandWithDetector(http, "blueberries", true, "", &fd.EnabledDetectorMock{})
if err != nil {
t.Errorf("error running command `pr status`: %v", err)
}
expected := []string{
"β Checks passing + Changes requested ! Merge conflict status unknown",
"- Checks pending β 2 Approved",
"Γ 1/3 checks failing - Review required β No merge conflicts",
"β Checks passing Γ Merge conflicts",
}
for _, line := range expected {
if !strings.Contains(output.String(), line) {
t.Errorf("output did not contain %q: %q", line, output.String())
}
}
}
func TestPRStatus_currentBranch_showTheMostRecentPR(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(httpmock.GraphQL(`query PullRequestStatus\b`), httpmock.FileResponse("./fixtures/prStatusCurrentBranch.json"))
// stub successful git command
rs, cleanup := run.Stub()
defer cleanup(t)
rs.Register(`git config --get-regexp \^branch\\.`, 0, "")
rs.Register(`git config remote.pushDefault`, 0, "")
rs.Register(`git rev-parse --symbolic-full-name blueberries@{push}`, 128, "")
rs.Register(`git config push.default`, 1, "")
output, err := runCommand(http, "blueberries", true, "")
if err != nil {
t.Errorf("error running command `pr status`: %v", err)
}
expectedLine := regexp.MustCompile(`#10 Blueberries are certainly a good fruit \[blueberries\]`)
if !expectedLine.MatchString(output.String()) {
t.Errorf("output did not match regexp /%s/\n> output\n%s\n", expectedLine, output)
return
}
unexpectedLines := []*regexp.Regexp{
regexp.MustCompile(`#9 Blueberries are a good fruit \[blueberries\] - Merged`),
regexp.MustCompile(`#8 Blueberries are probably a good fruit \[blueberries\] - Closed`),
}
for _, r := range unexpectedLines {
if r.MatchString(output.String()) {
t.Errorf("output unexpectedly match regexp /%s/\n> output\n%s\n", r, output)
return
}
}
}
func TestPRStatus_currentBranch_defaultBranch(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(httpmock.GraphQL(`query PullRequestStatus\b`), httpmock.FileResponse("./fixtures/prStatusCurrentBranch.json"))
// stub successful git command
rs, cleanup := run.Stub()
defer cleanup(t)
rs.Register(`git config --get-regexp \^branch\\.`, 0, "")
rs.Register(`git config remote.pushDefault`, 0, "")
rs.Register(`git rev-parse --symbolic-full-name blueberries@{push}`, 128, "")
rs.Register(`git config push.default`, 1, "")
output, err := runCommand(http, "blueberries", true, "")
if err != nil {
t.Errorf("error running command `pr status`: %v", err)
}
expectedLine := regexp.MustCompile(`#10 Blueberries are certainly a good fruit \[blueberries\]`)
if !expectedLine.MatchString(output.String()) {
t.Errorf("output did not match regexp /%s/\n> output\n%s\n", expectedLine, output)
return
}
}
func TestPRStatus_currentBranch_defaultBranch_repoFlag(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(httpmock.GraphQL(`query PullRequestStatus\b`), httpmock.FileResponse("./fixtures/prStatusCurrentBranchClosedOnDefaultBranch.json"))
output, err := runCommand(http, "blueberries", true, "-R OWNER/REPO")
if err != nil {
t.Errorf("error running command `pr status`: %v", err)
}
expectedLine := regexp.MustCompile(`#8 Blueberries are a good fruit \[blueberries\]`)
if expectedLine.MatchString(output.String()) {
t.Errorf("output not expected to match regexp /%s/\n> output\n%s\n", expectedLine, output)
return
}
}
func TestPRStatus_currentBranch_Closed(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(httpmock.GraphQL(`query PullRequestStatus\b`), httpmock.FileResponse("./fixtures/prStatusCurrentBranchClosed.json"))
// stub successful git command
rs, cleanup := run.Stub()
defer cleanup(t)
rs.Register(`git config --get-regexp \^branch\\.`, 0, "")
rs.Register(`git config remote.pushDefault`, 0, "")
rs.Register(`git rev-parse --symbolic-full-name blueberries@{push}`, 128, "")
rs.Register(`git config push.default`, 1, "")
output, err := runCommand(http, "blueberries", true, "")
if err != nil {
t.Errorf("error running command `pr status`: %v", err)
}
expectedLine := regexp.MustCompile(`#8 Blueberries are a good fruit \[blueberries\] - Closed`)
if !expectedLine.MatchString(output.String()) {
t.Errorf("output did not match regexp /%s/\n> output\n%s\n", expectedLine, output)
return
}
}
func TestPRStatus_currentBranch_Closed_defaultBranch(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(httpmock.GraphQL(`query PullRequestStatus\b`), httpmock.FileResponse("./fixtures/prStatusCurrentBranchClosedOnDefaultBranch.json"))
// stub successful git command
rs, cleanup := run.Stub()
defer cleanup(t)
rs.Register(`git config --get-regexp \^branch\\.`, 0, "")
rs.Register(`git config remote.pushDefault`, 0, "")
rs.Register(`git rev-parse --symbolic-full-name blueberries@{push}`, 128, "")
rs.Register(`git config push.default`, 1, "")
output, err := runCommand(http, "blueberries", true, "")
if err != nil {
t.Errorf("error running command `pr status`: %v", err)
}
expectedLine := regexp.MustCompile(`There is no pull request associated with \[blueberries\]`)
if !expectedLine.MatchString(output.String()) {
t.Errorf("output did not match regexp /%s/\n> output\n%s\n", expectedLine, output)
return
}
}
func TestPRStatus_currentBranch_Merged(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(httpmock.GraphQL(`query PullRequestStatus\b`), httpmock.FileResponse("./fixtures/prStatusCurrentBranchMerged.json"))
// stub successful git command
rs, cleanup := run.Stub()
defer cleanup(t)
rs.Register(`git config --get-regexp \^branch\\.`, 0, "")
rs.Register(`git config remote.pushDefault`, 0, "")
rs.Register(`git rev-parse --symbolic-full-name blueberries@{push}`, 128, "")
rs.Register(`git config push.default`, 1, "")
output, err := runCommand(http, "blueberries", true, "")
if err != nil {
t.Errorf("error running command `pr status`: %v", err)
}
expectedLine := regexp.MustCompile(`#8 Blueberries are a good fruit \[blueberries\] - Merged`)
if !expectedLine.MatchString(output.String()) {
t.Errorf("output did not match regexp /%s/\n> output\n%s\n", expectedLine, output)
return
}
}
func TestPRStatus_currentBranch_Merged_defaultBranch(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(httpmock.GraphQL(`query PullRequestStatus\b`), httpmock.FileResponse("./fixtures/prStatusCurrentBranchMergedOnDefaultBranch.json"))
// stub successful git command
rs, cleanup := run.Stub()
defer cleanup(t)
rs.Register(`git config --get-regexp \^branch\\.`, 0, "")
rs.Register(`git config remote.pushDefault`, 0, "")
rs.Register(`git rev-parse --symbolic-full-name blueberries@{push}`, 128, "")
rs.Register(`git config push.default`, 1, "")
output, err := runCommand(http, "blueberries", true, "")
if err != nil {
t.Errorf("error running command `pr status`: %v", err)
}
expectedLine := regexp.MustCompile(`There is no pull request associated with \[blueberries\]`)
if !expectedLine.MatchString(output.String()) {
t.Errorf("output did not match regexp /%s/\n> output\n%s\n", expectedLine, output)
return
}
}
func TestPRStatus_blankSlate(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(httpmock.GraphQL(`query PullRequestStatus\b`), httpmock.StringResponse(`{"data": {}}`))
// stub successful git command
rs, cleanup := run.Stub()
defer cleanup(t)
rs.Register(`git config --get-regexp \^branch\\.`, 0, "")
rs.Register(`git config remote.pushDefault`, 0, "")
rs.Register(`git rev-parse --symbolic-full-name blueberries@{push}`, 128, "")
rs.Register(`git config push.default`, 1, "")
output, err := runCommand(http, "blueberries", true, "")
if err != nil {
t.Errorf("error running command `pr status`: %v", err)
}
expected := `
Relevant pull requests in OWNER/REPO
Current branch
There is no pull request associated with [blueberries]
Created by you
You have no open pull requests
Requesting a code review from you
You have no pull requests to review
`
if output.String() != expected {
t.Errorf("expected %q, got %q", expected, output.String())
}
}
func TestPRStatus_blankSlateRepoOverride(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(httpmock.GraphQL(`query PullRequestStatus\b`), httpmock.StringResponse(`{"data": {}}`))
output, err := runCommand(http, "blueberries", true, "--repo OWNER/REPO")
if err != nil {
t.Errorf("error running command `pr status`: %v", err)
}
expected := `
Relevant pull requests in OWNER/REPO
Created by you
You have no open pull requests
Requesting a code review from you
You have no pull requests to review
`
if output.String() != expected {
t.Errorf("expected %q, got %q", expected, output.String())
}
}
func TestPRStatus_detachedHead(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(httpmock.GraphQL(`query PullRequestStatus\b`), httpmock.StringResponse(`{"data": {}}`))
output, err := runCommand(http, "", true, "")
if err != nil {
t.Errorf("error running command `pr status`: %v", err)
}
expected := `
Relevant pull requests in OWNER/REPO
Current branch
There is no current branch
Created by you
You have no open pull requests
Requesting a code review from you
You have no pull requests to review
`
if output.String() != expected {
t.Errorf("expected %q, got %q", expected, output.String())
}
}
func TestPRStatus_error_ReadBranchConfig(t *testing.T) {
rs, cleanup := run.Stub()
defer cleanup(t)
// We only need the one stub because this fails early
rs.Register(`git config --get-regexp \^branch\\.`, 2, "")
_, err := runCommand(initFakeHTTP(), "blueberries", true, "")
assert.Error(t, err)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/status/http_test.go | pkg/cmd/pr/status/http_test.go | package status
import (
"net/http"
"testing"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/stretchr/testify/assert"
)
func Test_getCurrentUsername(t *testing.T) {
tests := []struct {
name string
username string
hostname string
serverUsername string
currentUsername string
}{
{
name: "dotcom",
username: "@me",
hostname: "github.com",
currentUsername: "@me",
},
{
name: "ghec data residency (ghe.com)",
username: "@me",
hostname: "stampname.ghe.com",
currentUsername: "@me",
},
{
name: "ghes",
username: "@me",
hostname: "my.server.com",
serverUsername: "@serverUserName",
currentUsername: "@serverUserName",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
clientStub := &http.Client{}
if tt.serverUsername != "" {
reg := &httpmock.Registry{}
defer reg.Verify(t)
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data":{"viewer":{"login":"`+tt.serverUsername+`"}}}`),
)
clientStub.Transport = reg
}
apiClientStub := api.NewClientFromHTTP(clientStub)
currentUsername, err := getCurrentUsername(tt.username, tt.hostname, apiClientStub)
assert.NoError(t, err)
assert.Equal(t, tt.currentUsername, currentUsername)
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/status/http.go | pkg/cmd/pr/status/http.go | package status
import (
"fmt"
"net/http"
"strings"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/set"
ghauth "github.com/cli/go-gh/v2/pkg/auth"
)
type requestOptions struct {
CurrentPR int
HeadRef string
Username string
Fields []string
ConflictStatus bool
CheckRunAndStatusContextCountsSupported bool
}
type pullRequestsPayload struct {
ViewerCreated api.PullRequestAndTotalCount
ReviewRequested api.PullRequestAndTotalCount
CurrentPR *api.PullRequest
DefaultBranch string
}
func pullRequestStatus(httpClient *http.Client, repo ghrepo.Interface, options requestOptions) (*pullRequestsPayload, error) {
apiClient := api.NewClientFromHTTP(httpClient)
type edges struct {
TotalCount int
Edges []struct {
Node api.PullRequest
}
}
type response struct {
Repository struct {
DefaultBranchRef struct {
Name string
}
PullRequests edges
PullRequest *api.PullRequest
}
ViewerCreated edges
ReviewRequested edges
}
var fragments string
if len(options.Fields) > 0 {
fields := set.NewStringSet()
fields.AddValues(options.Fields)
// these are always necessary to find the PR for the current branch
fields.AddValues([]string{"isCrossRepository", "headRepositoryOwner", "headRefName"})
gr := api.PullRequestGraphQL(fields.ToSlice())
fragments = fmt.Sprintf("fragment pr on PullRequest{%s}fragment prWithReviews on PullRequest{...pr}", gr)
} else {
var err error
fragments, err = pullRequestFragment(options.ConflictStatus, options.CheckRunAndStatusContextCountsSupported)
if err != nil {
return nil, err
}
}
queryPrefix := `
query PullRequestStatus($owner: String!, $repo: String!, $headRefName: String!, $viewerQuery: String!, $reviewerQuery: String!, $per_page: Int = 10) {
repository(owner: $owner, name: $repo) {
defaultBranchRef {
name
}
pullRequests(headRefName: $headRefName, first: $per_page, orderBy: { field: CREATED_AT, direction: DESC }) {
totalCount
edges {
node {
...prWithReviews
}
}
}
}
`
if options.CurrentPR > 0 {
queryPrefix = `
query PullRequestStatus($owner: String!, $repo: String!, $number: Int!, $viewerQuery: String!, $reviewerQuery: String!, $per_page: Int = 10) {
repository(owner: $owner, name: $repo) {
defaultBranchRef {
name
}
pullRequest(number: $number) {
...prWithReviews
baseRef {
branchProtectionRule {
requiredApprovingReviewCount
}
}
}
}
`
}
query := fragments + queryPrefix + `
viewerCreated: search(query: $viewerQuery, type: ISSUE, first: $per_page) {
totalCount: issueCount
edges {
node {
...prWithReviews
}
}
}
reviewRequested: search(query: $reviewerQuery, type: ISSUE, first: $per_page) {
totalCount: issueCount
edges {
node {
...pr
}
}
}
}
`
currentUsername, err := getCurrentUsername(options.Username, repo.RepoHost(), apiClient)
if err != nil {
return nil, err
}
viewerQuery := fmt.Sprintf("repo:%s state:open is:pr author:%s", ghrepo.FullName(repo), currentUsername)
reviewerQuery := fmt.Sprintf("repo:%s state:open review-requested:%s", ghrepo.FullName(repo), currentUsername)
currentPRHeadRef := options.HeadRef
branchWithoutOwner := currentPRHeadRef
if idx := strings.Index(currentPRHeadRef, ":"); idx >= 0 {
branchWithoutOwner = currentPRHeadRef[idx+1:]
}
variables := map[string]interface{}{
"viewerQuery": viewerQuery,
"reviewerQuery": reviewerQuery,
"owner": repo.RepoOwner(),
"repo": repo.RepoName(),
"headRefName": branchWithoutOwner,
"number": options.CurrentPR,
}
var resp response
if err := apiClient.GraphQL(repo.RepoHost(), query, variables, &resp); err != nil {
return nil, err
}
var viewerCreated []api.PullRequest
for _, edge := range resp.ViewerCreated.Edges {
viewerCreated = append(viewerCreated, edge.Node)
}
var reviewRequested []api.PullRequest
for _, edge := range resp.ReviewRequested.Edges {
reviewRequested = append(reviewRequested, edge.Node)
}
var currentPR = resp.Repository.PullRequest
if currentPR == nil {
for _, edge := range resp.Repository.PullRequests.Edges {
if edge.Node.HeadLabel() == currentPRHeadRef {
currentPR = &edge.Node
break // Take the most recent PR for the current branch
}
}
}
payload := pullRequestsPayload{
ViewerCreated: api.PullRequestAndTotalCount{
PullRequests: viewerCreated,
TotalCount: resp.ViewerCreated.TotalCount,
},
ReviewRequested: api.PullRequestAndTotalCount{
PullRequests: reviewRequested,
TotalCount: resp.ReviewRequested.TotalCount,
},
CurrentPR: currentPR,
DefaultBranch: resp.Repository.DefaultBranchRef.Name,
}
return &payload, nil
}
func getCurrentUsername(username string, hostname string, apiClient *api.Client) (string, error) {
if username == "@me" && ghauth.IsEnterprise(hostname) {
var err error
username, err = api.CurrentLoginName(apiClient, hostname)
if err != nil {
return "", err
}
}
return username, nil
}
func pullRequestFragment(conflictStatus bool, statusCheckRollupWithCountByState bool) (string, error) {
fields := []string{
"number", "title", "state", "url", "isDraft", "isCrossRepository",
"headRefName", "headRepositoryOwner", "mergeStateStatus",
"requiresStrictStatusChecks", "autoMergeRequest",
}
if conflictStatus {
fields = append(fields, "mergeable")
}
if statusCheckRollupWithCountByState {
fields = append(fields, "statusCheckRollupWithCountByState")
} else {
fields = append(fields, "statusCheckRollup")
}
reviewFields := []string{"reviewDecision", "latestReviews"}
fragments := fmt.Sprintf(`
fragment pr on PullRequest {%s}
fragment prWithReviews on PullRequest {...pr,%s}
`, api.PullRequestGraphQL(fields), api.PullRequestGraphQL(reviewFields))
return fragments, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/create/regexp_writer.go | pkg/cmd/pr/create/regexp_writer.go | package create
import (
"bytes"
"io"
"regexp"
)
func NewRegexpWriter(out io.Writer, re *regexp.Regexp, repl string) *RegexpWriter {
return &RegexpWriter{out: out, re: *re, repl: repl}
}
type RegexpWriter struct {
out io.Writer
re regexp.Regexp
repl string
buf []byte
}
func (s *RegexpWriter) Write(data []byte) (int, error) {
if len(data) == 0 {
return 0, nil
}
filtered := []byte{}
repl := []byte(s.repl)
lines := bytes.SplitAfter(data, []byte("\n"))
if len(s.buf) > 0 {
lines[0] = append(s.buf, lines[0]...)
}
for i, line := range lines {
if i == len(lines) {
s.buf = line
} else {
f := s.re.ReplaceAll(line, repl)
if len(f) > 0 {
filtered = append(filtered, f...)
}
}
}
if len(filtered) != 0 {
_, err := s.out.Write(filtered)
if err != nil {
return 0, err
}
}
return len(data), nil
}
func (s *RegexpWriter) Flush() (int, error) {
if len(s.buf) > 0 {
repl := []byte(s.repl)
filtered := s.re.ReplaceAll(s.buf, repl)
if len(filtered) > 0 {
return s.out.Write(filtered)
}
}
return 0, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/create/create.go | pkg/cmd/pr/create/create.go | package create
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"regexp"
"strings"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/cenkalti/backoff/v4"
"github.com/cli/cli/v2/api"
ghContext "github.com/cli/cli/v2/context"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/browser"
fd "github.com/cli/cli/v2/internal/featuredetection"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/cmd/pr/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/pkg/markdown"
o "github.com/cli/cli/v2/pkg/option"
"github.com/spf13/cobra"
)
type CreateOptions struct {
// This struct stores user input and factory functions
Detector fd.Detector
HttpClient func() (*http.Client, error)
GitClient *git.Client
Config func() (gh.Config, error)
IO *iostreams.IOStreams
Remotes func() (ghContext.Remotes, error)
Branch func() (string, error)
Browser browser.Browser
Prompter shared.Prompt
Finder shared.PRFinder
TitledEditSurvey func(string, string) (string, string, error)
TitleProvided bool
BodyProvided bool
RootDirOverride string
RepoOverride string
Autofill bool
FillVerbose bool
FillFirst bool
EditorMode bool
WebMode bool
RecoverFile string
IsDraft bool
Title string
Body string
BaseBranch string
HeadBranch string
Reviewers []string
Assignees []string
Labels []string
Projects []string
Milestone string
MaintainerCanModify bool
Template string
DryRun bool
}
// creationRefs is an interface that provides the necessary information for creating a pull request in the API.
// Upcasting to concrete implementations can provide further context on other operations (forking and pushing).
type creationRefs interface {
// QualifiedHeadRef returns a stringified form of the head ref, varying depending
// on whether the head ref is in the same repository as the base ref. If they are
// the same repository, we return the branch name only. If they are different repositories,
// we return the owner and branch name in the form <owner>:<branch>.
QualifiedHeadRef() string
// UnqualifiedHeadRef returns a head ref in the form of the branch name only.
UnqualifiedHeadRef() string
//BaseRef returns the base branch name.
BaseRef() string
// While the only thing really required from an api.Repository is the repository ID, changing that
// would require changing the API function signatures, and the refactor that introduced this refs
// type is already large enough.
BaseRepo() *api.Repository
}
type baseRefs struct {
baseRepo *api.Repository
baseBranchName string
}
func (r baseRefs) BaseRef() string {
return r.baseBranchName
}
func (r baseRefs) BaseRepo() *api.Repository {
return r.baseRepo
}
// skipPushRefs indicate to handlePush that no pushing is required.
type skipPushRefs struct {
baseRefs
qualifiedHeadRef shared.QualifiedHeadRef
}
func (r skipPushRefs) QualifiedHeadRef() string {
return r.qualifiedHeadRef.String()
}
func (r skipPushRefs) UnqualifiedHeadRef() string {
return r.qualifiedHeadRef.BranchName()
}
// pushableRefs indicate to handlePush that pushing is required,
// and provide further information (HeadRepo) on where that push
// should go.
type pushableRefs struct {
baseRefs
headRepo ghrepo.Interface
headBranchName string
}
func (r pushableRefs) QualifiedHeadRef() string {
if ghrepo.IsSame(r.headRepo, r.baseRepo) {
return r.headBranchName
}
return fmt.Sprintf("%s:%s", r.headRepo.RepoOwner(), r.headBranchName)
}
func (r pushableRefs) UnqualifiedHeadRef() string {
return r.headBranchName
}
func (r pushableRefs) HeadRepo() ghrepo.Interface {
return r.headRepo
}
// forkableRefs indicate to handlePush that forking is required before
// pushing. The expectation is that after forking, this is converted to
// pushableRefs. We could go very OOP and have a Fork method on this
// struct that returns a pushableRefs but then we'd need to embed an API client
// and it just seems nice that it is a simple bag of data.
type forkableRefs struct {
baseRefs
qualifiedHeadRef shared.QualifiedHeadRef
}
func (r forkableRefs) QualifiedHeadRef() string {
return r.qualifiedHeadRef.String()
}
func (r forkableRefs) UnqualifiedHeadRef() string {
return r.qualifiedHeadRef.BranchName()
}
// CreateContext stores contextual data about the creation process and is for building up enough
// data to create a pull request.
type CreateContext struct {
ResolvedRemotes *ghContext.ResolvedRemotes
PRRefs creationRefs
// BaseTrackingBranch is perhaps a slightly leaky abstraction in the presence
// of PRRefs, but a huge amount of refactoring was done to introduce that struct,
// and this is a small price to pay for the convenience of not having to do a lot
// more design.
BaseTrackingBranch string
Client *api.Client
GitClient *git.Client
}
func NewCmdCreate(f *cmdutil.Factory, runF func(*CreateOptions) error) *cobra.Command {
opts := &CreateOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
GitClient: f.GitClient,
Config: f.Config,
Remotes: f.Remotes,
Branch: f.Branch,
Browser: f.Browser,
Prompter: f.Prompter,
TitledEditSurvey: shared.TitledEditSurvey(&shared.UserEditor{Config: f.Config, IO: f.IOStreams}),
}
var bodyFile string
cmd := &cobra.Command{
Use: "create",
Short: "Create a pull request",
Long: heredoc.Docf(`
Create a pull request on GitHub.
Upon success, the URL of the created pull request will be printed.
When the current branch isn't fully pushed to a git remote, a prompt will ask where
to push the branch and offer an option to fork the base repository. Use %[1]s--head%[1]s to
explicitly skip any forking or pushing behavior.
%[1]s--head%[1]s supports %[1]s<user>:<branch>%[1]s syntax to select a head repo owned by %[1]s<user>%[1]s.
Using an organization as the %[1]s<user>%[1]s is currently not supported.
For more information, see <https://github.com/cli/cli/issues/10093>
A prompt will also ask for the title and the body of the pull request. Use %[1]s--title%[1]s and
%[1]s--body%[1]s to skip this, or use %[1]s--fill%[1]s to autofill these values from git commits.
It's important to notice that if the %[1]s--title%[1]s and/or %[1]s--body%[1]s are also provided
alongside %[1]s--fill%[1]s, the values specified by %[1]s--title%[1]s and/or %[1]s--body%[1]s will
take precedence and overwrite any autofilled content.
The base branch for the created PR can be specified using the %[1]s--base%[1]s flag. If not provided,
the value of %[1]sgh-merge-base%[1]s git branch config will be used. If not configured, the repository's
default branch will be used. Run %[1]sgit config branch.{current}.gh-merge-base {base}%[1]s to configure
the current branch to use the specified merge base.
Link an issue to the pull request by referencing the issue in the body of the pull
request. If the body text mentions %[1]sFixes #123%[1]s or %[1]sCloses #123%[1]s, the referenced issue
will automatically get closed when the pull request gets merged.
By default, users with write access to the base repository can push new commits to the
head branch of the pull request. Disable this with %[1]s--no-maintainer-edit%[1]s.
Adding a pull request to projects requires authorization with the %[1]sproject%[1]s scope.
To authorize, run %[1]sgh auth refresh -s project%[1]s.
`, "`"),
Example: heredoc.Doc(`
$ gh pr create --title "The bug is fixed" --body "Everything works again"
$ gh pr create --reviewer monalisa,hubot --reviewer myorg/team-name
$ gh pr create --project "Roadmap"
$ gh pr create --base develop --head monalisa:feature
$ gh pr create --template "pull_request_template.md"
`),
Args: cmdutil.NoArgsQuoteReminder,
Aliases: []string{"new"},
RunE: func(cmd *cobra.Command, args []string) error {
opts.Finder = shared.NewFinder(f)
opts.TitleProvided = cmd.Flags().Changed("title")
opts.RepoOverride, _ = cmd.Flags().GetString("repo")
// Workaround: Due to the way this command is implemented, we need to manually check GH_REPO.
// Commands should use the standard BaseRepoOverride functionality to handle this behavior instead.
if opts.RepoOverride == "" {
opts.RepoOverride = os.Getenv("GH_REPO")
}
noMaintainerEdit, _ := cmd.Flags().GetBool("no-maintainer-edit")
opts.MaintainerCanModify = !noMaintainerEdit
if !opts.IO.CanPrompt() && opts.RecoverFile != "" {
return cmdutil.FlagErrorf("`--recover` only supported when running interactively")
}
if opts.IsDraft && opts.WebMode {
return cmdutil.FlagErrorf("the `--draft` flag is not supported with `--web`")
}
if len(opts.Reviewers) > 0 && opts.WebMode {
return cmdutil.FlagErrorf("the `--reviewer` flag is not supported with `--web`")
}
if cmd.Flags().Changed("no-maintainer-edit") && opts.WebMode {
return cmdutil.FlagErrorf("the `--no-maintainer-edit` flag is not supported with `--web`")
}
if opts.Autofill && opts.FillFirst {
return cmdutil.FlagErrorf("`--fill` is not supported with `--fill-first`")
}
if opts.FillVerbose && opts.FillFirst {
return cmdutil.FlagErrorf("`--fill-verbose` is not supported with `--fill-first`")
}
if opts.FillVerbose && opts.Autofill {
return cmdutil.FlagErrorf("`--fill-verbose` is not supported with `--fill`")
}
if err := cmdutil.MutuallyExclusive(
"specify only one of `--editor` or `--web`",
opts.EditorMode,
opts.WebMode,
); err != nil {
return err
}
var err error
opts.EditorMode, err = shared.InitEditorMode(f, opts.EditorMode, opts.WebMode, opts.IO.CanPrompt())
if err != nil {
return err
}
opts.BodyProvided = cmd.Flags().Changed("body")
if bodyFile != "" {
b, err := cmdutil.ReadFile(bodyFile, opts.IO.In)
if err != nil {
return err
}
opts.Body = string(b)
opts.BodyProvided = true
}
if opts.Template != "" && opts.BodyProvided {
return cmdutil.FlagErrorf("`--template` is not supported when using `--body` or `--body-file`")
}
if !opts.IO.CanPrompt() && !opts.WebMode && !(opts.FillVerbose || opts.Autofill || opts.FillFirst) && (!opts.TitleProvided || !opts.BodyProvided) {
return cmdutil.FlagErrorf("must provide `--title` and `--body` (or `--fill` or `fill-first` or `--fillverbose`) when not running interactively")
}
if opts.DryRun && opts.WebMode {
return cmdutil.FlagErrorf("`--dry-run` is not supported when using `--web`")
}
if runF != nil {
return runF(opts)
}
return createRun(opts)
},
}
fl := cmd.Flags()
fl.BoolVarP(&opts.IsDraft, "draft", "d", false, "Mark pull request as a draft")
fl.StringVarP(&opts.Title, "title", "t", "", "Title for the pull request")
fl.StringVarP(&opts.Body, "body", "b", "", "Body for the pull request")
fl.StringVarP(&bodyFile, "body-file", "F", "", "Read body text from `file` (use \"-\" to read from standard input)")
fl.StringVarP(&opts.BaseBranch, "base", "B", "", "The `branch` into which you want your code merged")
fl.StringVarP(&opts.HeadBranch, "head", "H", "", "The `branch` that contains commits for your pull request (default [current branch])")
fl.BoolVarP(&opts.EditorMode, "editor", "e", false, "Skip prompts and open the text editor to write the title and body in. The first line is the title and the remaining text is the body.")
fl.BoolVarP(&opts.WebMode, "web", "w", false, "Open the web browser to create a pull request")
fl.BoolVarP(&opts.FillVerbose, "fill-verbose", "", false, "Use commits msg+body for description")
fl.BoolVarP(&opts.Autofill, "fill", "f", false, "Use commit info for title and body")
fl.BoolVar(&opts.FillFirst, "fill-first", false, "Use first commit info for title and body")
fl.StringSliceVarP(&opts.Reviewers, "reviewer", "r", nil, "Request reviews from people or teams by their `handle`")
fl.StringSliceVarP(&opts.Assignees, "assignee", "a", nil, "Assign people by their `login`. Use \"@me\" to self-assign.")
fl.StringSliceVarP(&opts.Labels, "label", "l", nil, "Add labels by `name`")
fl.StringSliceVarP(&opts.Projects, "project", "p", nil, "Add the pull request to projects by `title`")
fl.StringVarP(&opts.Milestone, "milestone", "m", "", "Add the pull request to a milestone by `name`")
fl.Bool("no-maintainer-edit", false, "Disable maintainer's ability to modify pull request")
fl.StringVar(&opts.RecoverFile, "recover", "", "Recover input from a failed run of create")
fl.StringVarP(&opts.Template, "template", "T", "", "Template `file` to use as starting body text")
fl.BoolVar(&opts.DryRun, "dry-run", false, "Print details instead of creating the PR. May still push git changes.")
_ = cmdutil.RegisterBranchCompletionFlags(f.GitClient, cmd, "base", "head")
_ = cmd.RegisterFlagCompletionFunc("reviewer", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
results, err := requestableReviewersForCompletion(opts)
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
return results, cobra.ShellCompDirectiveNoFileComp
})
return cmd
}
func createRun(opts *CreateOptions) error {
ctx, err := NewCreateContext(opts)
if err != nil {
return err
}
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
// TODO projectsV1Deprecation
// Remove this section as we should no longer need to detect
if opts.Detector == nil {
cachedClient := api.NewCachedHTTPClient(httpClient, time.Hour*24)
opts.Detector = fd.NewDetector(cachedClient, ctx.PRRefs.BaseRepo().RepoHost())
}
projectsV1Support := opts.Detector.ProjectsV1()
client := ctx.Client
state, err := NewIssueState(*ctx, *opts)
if err != nil {
return err
}
var openURL string
if opts.WebMode {
if !(opts.Autofill || opts.FillFirst) {
state.Title = opts.Title
state.Body = opts.Body
}
if opts.Template != "" {
state.Template = opts.Template
}
err = handlePush(*opts, *ctx)
if err != nil {
return err
}
openURL, err = generateCompareURL(*ctx, *state, projectsV1Support)
if err != nil {
return err
}
if !shared.ValidURL(openURL) {
err = fmt.Errorf("cannot open in browser: maximum URL length exceeded")
return err
}
return previewPR(*opts, openURL)
}
if opts.TitleProvided {
state.Title = opts.Title
}
if opts.BodyProvided {
state.Body = opts.Body
}
existingPR, _, err := opts.Finder.Find(shared.FindOptions{
Selector: ctx.PRRefs.QualifiedHeadRef(),
BaseBranch: ctx.PRRefs.BaseRef(),
States: []string{"OPEN"},
Fields: []string{"url"},
})
var notFound *shared.NotFoundError
if err != nil && !errors.As(err, ¬Found) {
return fmt.Errorf("error checking for existing pull request: %w", err)
}
if err == nil {
return fmt.Errorf("a pull request for branch %q into branch %q already exists:\n%s",
ctx.PRRefs.QualifiedHeadRef(), ctx.PRRefs.BaseRef(), existingPR.URL)
}
message := "\nCreating pull request for %s into %s in %s\n\n"
if state.Draft {
message = "\nCreating draft pull request for %s into %s in %s\n\n"
}
if opts.DryRun {
message = "\nDry Running pull request for %s into %s in %s\n\n"
}
cs := opts.IO.ColorScheme()
if opts.IO.CanPrompt() {
fmt.Fprintf(opts.IO.ErrOut, message,
cs.Cyan(ctx.PRRefs.QualifiedHeadRef()),
cs.Cyan(ctx.PRRefs.BaseRef()),
ghrepo.FullName(ctx.PRRefs.BaseRepo()))
}
if !opts.EditorMode && (opts.FillVerbose || opts.Autofill || opts.FillFirst || (opts.TitleProvided && opts.BodyProvided)) {
err = handlePush(*opts, *ctx)
if err != nil {
return err
}
return submitPR(*opts, *ctx, *state, projectsV1Support)
}
if opts.RecoverFile != "" {
err = shared.FillFromJSON(opts.IO, opts.RecoverFile, state)
if err != nil {
return fmt.Errorf("failed to recover input: %w", err)
}
}
action := shared.SubmitAction
if opts.IsDraft {
action = shared.SubmitDraftAction
}
tpl := shared.NewTemplateManager(client.HTTP(), ctx.PRRefs.BaseRepo(), opts.Prompter, opts.RootDirOverride, opts.RepoOverride == "", true)
if opts.EditorMode {
if opts.Template != "" {
var template shared.Template
template, err = tpl.Select(opts.Template)
if err != nil {
return err
}
if state.Title == "" {
state.Title = template.Title()
}
state.Body = string(template.Body())
}
state.Title, state.Body, err = opts.TitledEditSurvey(state.Title, state.Body)
if err != nil {
return err
}
if state.Title == "" {
err = fmt.Errorf("title can't be blank")
return err
}
} else {
if !opts.TitleProvided {
err = shared.TitleSurvey(opts.Prompter, opts.IO, state)
if err != nil {
return err
}
}
defer shared.PreserveInput(opts.IO, state, &err)()
if !opts.BodyProvided {
templateContent := ""
if opts.RecoverFile == "" {
var template shared.Template
if opts.Template != "" {
template, err = tpl.Select(opts.Template)
if err != nil {
return err
}
} else {
template, err = tpl.Choose()
if err != nil {
return err
}
}
if template != nil {
templateContent = string(template.Body())
}
}
err = shared.BodySurvey(opts.Prompter, state, templateContent)
if err != nil {
return err
}
}
openURL, err = generateCompareURL(*ctx, *state, projectsV1Support)
if err != nil {
return err
}
allowPreview := !state.HasMetadata() && shared.ValidURL(openURL) && !opts.DryRun
allowMetadata := ctx.PRRefs.BaseRepo().ViewerCanTriage()
action, err = shared.ConfirmPRSubmission(opts.Prompter, allowPreview, allowMetadata, state.Draft)
if err != nil {
return fmt.Errorf("unable to confirm: %w", err)
}
if action == shared.MetadataAction {
fetcher := &shared.MetadataFetcher{
IO: opts.IO,
APIClient: client,
Repo: ctx.PRRefs.BaseRepo(),
State: state,
}
err = shared.MetadataSurvey(opts.Prompter, opts.IO, ctx.PRRefs.BaseRepo(), fetcher, state, projectsV1Support)
if err != nil {
return err
}
action, err = shared.ConfirmPRSubmission(opts.Prompter, !state.HasMetadata() && !opts.DryRun, false, state.Draft)
if err != nil {
return err
}
}
}
if action == shared.CancelAction {
fmt.Fprintln(opts.IO.ErrOut, "Discarding.")
err = cmdutil.CancelError
return err
}
err = handlePush(*opts, *ctx)
if err != nil {
return err
}
if action == shared.PreviewAction {
return previewPR(*opts, openURL)
}
if action == shared.SubmitDraftAction {
state.Draft = true
return submitPR(*opts, *ctx, *state, projectsV1Support)
}
if action == shared.SubmitAction {
return submitPR(*opts, *ctx, *state, projectsV1Support)
}
err = errors.New("expected to cancel, preview, or submit")
return err
}
var regexPattern = regexp.MustCompile(`(?m)^`)
func initDefaultTitleBody(ctx CreateContext, state *shared.IssueMetadataState, useFirstCommit bool, addBody bool) error {
commits, err := ctx.GitClient.Commits(context.Background(), ctx.BaseTrackingBranch, ctx.PRRefs.UnqualifiedHeadRef())
if err != nil {
return err
}
if len(commits) == 1 || useFirstCommit {
state.Title = commits[len(commits)-1].Title
state.Body = commits[len(commits)-1].Body
} else {
state.Title = humanize(ctx.PRRefs.UnqualifiedHeadRef())
var body strings.Builder
for i := len(commits) - 1; i >= 0; i-- {
fmt.Fprintf(&body, "- **%s**\n", commits[i].Title)
if addBody {
x := regexPattern.ReplaceAllString(commits[i].Body, " ")
fmt.Fprintf(&body, "%s", x)
if i > 0 {
fmt.Fprintln(&body)
fmt.Fprintln(&body)
}
}
}
state.Body = body.String()
}
return nil
}
func NewIssueState(ctx CreateContext, opts CreateOptions) (*shared.IssueMetadataState, error) {
var milestoneTitles []string
if opts.Milestone != "" {
milestoneTitles = []string{opts.Milestone}
}
meReplacer := shared.NewMeReplacer(ctx.Client, ctx.PRRefs.BaseRepo().RepoHost())
assignees, err := meReplacer.ReplaceSlice(opts.Assignees)
if err != nil {
return nil, err
}
state := &shared.IssueMetadataState{
Type: shared.PRMetadata,
Reviewers: opts.Reviewers,
Assignees: assignees,
Labels: opts.Labels,
ProjectTitles: opts.Projects,
Milestones: milestoneTitles,
Draft: opts.IsDraft,
}
if opts.FillVerbose || opts.Autofill || opts.FillFirst || !opts.TitleProvided || !opts.BodyProvided {
err := initDefaultTitleBody(ctx, state, opts.FillFirst, opts.FillVerbose)
if err != nil && (opts.FillVerbose || opts.Autofill || opts.FillFirst) {
return nil, fmt.Errorf("could not compute title or body defaults: %w", err)
}
}
return state, nil
}
func NewCreateContext(opts *CreateOptions) (*CreateContext, error) {
httpClient, err := opts.HttpClient()
if err != nil {
return nil, err
}
client := api.NewClientFromHTTP(httpClient)
remotes, err := getRemotes(opts)
if err != nil {
return nil, err
}
resolvedRemotes, err := ghContext.ResolveRemotesToRepos(remotes, client, opts.RepoOverride)
if err != nil {
return nil, err
}
var baseRepo *api.Repository
if br, err := resolvedRemotes.BaseRepo(opts.IO); err == nil {
if r, ok := br.(*api.Repository); ok {
baseRepo = r
} else {
// TODO: if RepoNetwork is going to be requested anyway in `repoContext.HeadRepos()`,
// consider piggybacking on that result instead of performing a separate lookup
baseRepo, err = api.GitHubRepo(client, br)
if err != nil {
return nil, err
}
}
} else {
return nil, err
}
// This closure provides an easy way to instantiate a CreateContext with everything other than
// the refs. This probably indicates that CreateContext could do with some rework, but the refactor
// to introduce PRRefs is already large enough.
var newCreateContext = func(refs creationRefs) *CreateContext {
baseTrackingBranch := refs.BaseRef()
// The baseTrackingBranch is used later for a command like:
// `git commit upstream/main feature` in order to create a PR message showing the commits
// between these two refs. I'm not really sure what is expected to happen if we don't have a remote,
// which seems like it would be possible with a command `gh pr create --repo owner/repo-that-is-not-a-remote`.
// In that case, we might just have a mess? In any case, this is what the old code did, so I don't want to change
// it as part of an already large refactor.
baseRemote, _ := resolvedRemotes.RemoteForRepo(baseRepo)
if baseRemote != nil {
baseTrackingBranch = fmt.Sprintf("%s/%s", baseRemote.Name, baseTrackingBranch)
}
return &CreateContext{
ResolvedRemotes: resolvedRemotes,
Client: client,
GitClient: opts.GitClient,
PRRefs: refs,
BaseTrackingBranch: baseTrackingBranch,
}
}
// If the user provided a head branch we're going to use that without any interrogation
// of git. The value can take the form of <branch> or <user>:<branch>. In the former case, the
// PR base and head repos are the same. In the latter case we don't know the head repo
// (though we could look it up in the API) but fortunately we don't need to because the API
// will resolve this for us when we create the pull request. This is possible because
// users can only have a single fork in their namespace, and organizations don't work at all with this ref format.
//
// Note that providing the head branch in this way indicates that we shouldn't push the branch,
// and we indicate that via the returned type as well.
if opts.HeadBranch != "" {
qualifiedHeadRef, err := shared.ParseQualifiedHeadRef(opts.HeadBranch)
if err != nil {
return nil, err
}
branchConfig, err := opts.GitClient.ReadBranchConfig(context.Background(), qualifiedHeadRef.BranchName())
if err != nil {
return nil, err
}
baseBranch := opts.BaseBranch
if baseBranch == "" {
baseBranch = branchConfig.MergeBase
}
if baseBranch == "" {
baseBranch = baseRepo.DefaultBranchRef.Name
}
return newCreateContext(skipPushRefs{
qualifiedHeadRef: qualifiedHeadRef,
baseRefs: baseRefs{
baseRepo: baseRepo,
baseBranchName: baseBranch,
},
}), nil
}
if ucc, err := opts.GitClient.UncommittedChangeCount(context.Background()); err == nil && ucc > 0 {
fmt.Fprintf(opts.IO.ErrOut, "Warning: %s\n", text.Pluralize(ucc, "uncommitted change"))
}
// If the user didn't provide a head branch then we're gettin' real. We're going to interrogate git
// and try to create refs that are pushable.
currentBranch, err := opts.Branch()
if err != nil {
return nil, fmt.Errorf("could not determine the current branch: %w", err)
}
branchConfig, err := opts.GitClient.ReadBranchConfig(context.Background(), currentBranch)
if err != nil {
return nil, err
}
baseBranch := opts.BaseBranch
if baseBranch == "" {
baseBranch = branchConfig.MergeBase
}
if baseBranch == "" {
baseBranch = baseRepo.DefaultBranchRef.Name
}
// First we check with the git information we have to see if we can figure out the default
// head repo and remote branch name.
defaultPRHead, err := shared.TryDetermineDefaultPRHead(
// We requested the branch config already, so let's cache that
shared.CachedBranchConfigGitConfigClient{
CachedBranchConfig: branchConfig,
GitConfigClient: opts.GitClient,
},
shared.NewRemoteToRepoResolver(opts.Remotes),
currentBranch,
)
if err != nil {
return nil, err
}
// The baseRefs are always going to be the same from now on. If I could make this immutable I would!
baseRefs := baseRefs{
baseRepo: baseRepo,
baseBranchName: baseBranch,
}
// If we were able to determine a head repo, then let's check that the remote tracking ref matches the SHA of
// HEAD. If it does, then we don't need to push, otherwise we'll need to ask the user to tell us where to push.
if headRepo, present := defaultPRHead.Repo.Value(); present {
// We may not find a remote because the git branch config may have a URL rather than a remote name.
// Ideally, we would return a sentinel error from RemoteForRepo that we could compare to, but the
// refactor that introduced this code was already large enough.
headRemote, _ := resolvedRemotes.RemoteForRepo(headRepo)
if headRemote != nil {
resolvedRefs, _ := opts.GitClient.ShowRefs(
context.Background(),
[]string{
"HEAD",
fmt.Sprintf("refs/remotes/%s/%s", headRemote.Name, defaultPRHead.BranchName),
},
)
// Two refs returned means we can compare HEAD to the remote tracking branch.
// If we had a matching ref, then we can skip pushing.
refsMatch := len(resolvedRefs) == 2 && resolvedRefs[0].Hash == resolvedRefs[1].Hash
if refsMatch {
qualifiedHeadRef := shared.NewQualifiedHeadRefWithoutOwner(defaultPRHead.BranchName)
if headRepo.RepoOwner() != baseRepo.RepoOwner() {
qualifiedHeadRef = shared.NewQualifiedHeadRef(headRepo.RepoOwner(), defaultPRHead.BranchName)
}
return newCreateContext(skipPushRefs{
qualifiedHeadRef: qualifiedHeadRef,
baseRefs: baseRefs,
}), nil
}
}
}
// If we didn't determine that the git indicated repo had the correct ref, we'll take a look at the other
// remotes and see whether any of them have the same SHA as HEAD. Now, at this point, you might be asking yourself:
// "Why didn't we collect all the SHAs with a single ShowRefs command above, for use in both cases?"
// ...
// That's because the code below has a bug that I've ported from the old code, in order to preserve the existing
// behaviour, and to limit the scope of an already large refactor. The intention of the original code was to loop
// over all the returned refs. However, as it turns out, our implementation of ShowRefs doesn't do that correctly.
// Since it provides the --verify flag, git will return the SHAs for refs up until it hits a ref that doesn't exist,
// at which point it bails out.
//
// Imagine you have a remotes "upstream" and "origin", and you have pushed your branch "feature" to "origin". Since
// the order of remotes is always guaranteed "upstream", "github", "origin", and then everything else unstably sorted,
// we will never get a SHA for origin, as refs/remotes/upstream/feature doesn't exist.
//
// Furthermore, when you really think about it, this code is a bit eager. What happens if you have the same SHA on
// remotes "origin" and "colleague", this will always offer origin. If it were "colleague-a" and "colleague-b", no
// order would be guaranteed between different invocations of pr create, because the order of remotes after "origin"
// is unstable sorted.
//
// All that said, this has been the behaviour for a long, long time, and I do not want to make other behavioural changes
// in what is mostly a refactor.
refsToLookup := []string{"HEAD"}
for _, remote := range remotes {
refsToLookup = append(refsToLookup, fmt.Sprintf("refs/remotes/%s/%s", remote.Name, currentBranch))
}
// Ignoring the error in this case is allowed because we may get refs and an error (see: --verify flag above).
// Ideally there would be a typed error to allow us to distinguish between an execution error and some refs
// not existing. However, this is too much to take on in an already large refactor.
refs, _ := opts.GitClient.ShowRefs(context.Background(), refsToLookup)
if len(refs) > 1 {
headRef := refs[0]
var firstMatchingRef o.Option[git.RemoteTrackingRef]
// Loop over all the refs, trying to find one that matches the SHA of HEAD.
for _, r := range refs[1:] {
if r.Hash == headRef.Hash {
remoteTrackingRef, err := git.ParseRemoteTrackingRef(r.Name)
if err != nil {
return nil, err
}
firstMatchingRef = o.Some(remoteTrackingRef)
break
}
}
// If we found a matching ref, then we don't need to push.
if ref, present := firstMatchingRef.Value(); present {
remote, err := remotes.FindByName(ref.Remote)
if err != nil {
return nil, err
}
qualifiedHeadRef := shared.NewQualifiedHeadRefWithoutOwner(ref.Branch)
if baseRepo.RepoOwner() != remote.RepoOwner() {
qualifiedHeadRef = shared.NewQualifiedHeadRef(remote.RepoOwner(), ref.Branch)
}
return newCreateContext(skipPushRefs{
qualifiedHeadRef: qualifiedHeadRef,
baseRefs: baseRefs,
}), nil
}
}
// If we haven't got a repo by now, and we can't prompt then it's game over.
if !opts.IO.CanPrompt() {
fmt.Fprintln(opts.IO.ErrOut, "aborted: you must first push the current branch to a remote, or use the --head flag")
return nil, cmdutil.SilentError
}
// Otherwise, hooray, prompting!
// First, we're going to look at our remotes and decide whether there are any repos we can push to.
pushableRepos, err := resolvedRemotes.HeadRepos()
if err != nil {
return nil, err
}
// If we couldn't find any pushable repos, then find forks of the base repo.
if len(pushableRepos) == 0 {
pushableRepos, err = api.RepoFindForks(client, baseRepo, 3)
if err != nil {
return nil, err
}
}
currentLogin, err := api.CurrentLoginName(client, baseRepo.RepoHost())
if err != nil {
return nil, err
}
hasOwnFork := false
var pushOptions []string
for _, r := range pushableRepos {
pushOptions = append(pushOptions, ghrepo.FullName(r))
if r.RepoOwner() == currentLogin {
hasOwnFork = true
}
}
if !hasOwnFork {
pushOptions = append(pushOptions, fmt.Sprintf("Create a fork of %s", ghrepo.FullName(baseRepo)))
}
pushOptions = append(pushOptions, "Skip pushing the branch")
pushOptions = append(pushOptions, "Cancel")
selectedOption, err := opts.Prompter.Select(fmt.Sprintf("Where should we push the '%s' branch?", currentBranch), "", pushOptions)
if err != nil {
return nil, err
}
if selectedOption < len(pushableRepos) {
// A repository has been selected to push to.
return newCreateContext(pushableRefs{
headRepo: pushableRepos[selectedOption],
headBranchName: currentBranch,
baseRefs: baseRefs,
}), nil
} else if pushOptions[selectedOption] == "Skip pushing the branch" {
// We're going to skip pushing the branch altogether, meaning, use whatever SHA is already pushed.
// It's not exactly clear what repo the user expects to use here for the HEAD, and maybe we should
// make that clear in the UX somehow, but in the old implementation as far as I can tell, this
// always meant "use the base repo".
return newCreateContext(skipPushRefs{
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | true |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/create/regexp_writer_test.go | pkg/cmd/pr/create/regexp_writer_test.go | package create
import (
"bytes"
"regexp"
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/stretchr/testify/assert"
)
func Test_Write(t *testing.T) {
type input struct {
in []string
re *regexp.Regexp
repl string
}
type output struct {
wantsErr bool
out string
length int
}
tests := []struct {
name string
input input
output output
}{
{
name: "single line input",
input: input{
in: []string{"some input line that has wrong information"},
re: regexp.MustCompile("wrong"),
repl: "right",
},
output: output{
wantsErr: false,
out: "some input line that has right information",
length: 42,
},
},
{
name: "multiple line input",
input: input{
in: []string{"multiple lines\nin this\ninput lines"},
re: regexp.MustCompile("lines"),
repl: "tests",
},
output: output{
wantsErr: false,
out: "multiple tests\nin this\ninput tests",
length: 34,
},
},
{
name: "no matches",
input: input{
in: []string{"this line has no matches"},
re: regexp.MustCompile("wrong"),
repl: "right",
},
output: output{
wantsErr: false,
out: "this line has no matches",
length: 24,
},
},
{
name: "no output",
input: input{
in: []string{"remove this whole line"},
re: regexp.MustCompile("^remove.*$"),
repl: "",
},
output: output{
wantsErr: false,
out: "",
length: 22,
},
},
{
name: "no input",
input: input{
in: []string{""},
re: regexp.MustCompile("remove"),
repl: "",
},
output: output{
wantsErr: false,
out: "",
length: 0,
},
},
{
name: "multiple lines removed",
input: input{
in: []string{"beginning line\nremove this whole line\nremove this one also\nnot this one"},
re: regexp.MustCompile("(?s)^remove.*$"),
repl: "",
},
output: output{
wantsErr: false,
out: "beginning line\nnot this one",
length: 71,
},
},
{
name: "removes remote from git push output",
input: input{
in: []string{heredoc.Doc(`
output: some information
remote:
remote: Create a pull request for 'regex' on GitHub by visiting:
remote: https://github.com/owner/repo/pull/new/regex
remote:
output: more information
`)},
re: regexp.MustCompile("^remote: (Create a pull request.*by visiting|[[:space:]]*https://.*/pull/new/).*\n?$"),
repl: "",
},
output: output{
wantsErr: false,
out: "output: some information\nremote:\nremote:\noutput: more information\n",
length: 189,
},
},
{
name: "multiple writes",
input: input{
in: []string{"first write\n", "second write ", "third write"},
re: regexp.MustCompile("write"),
repl: "read",
},
output: output{
wantsErr: false,
out: "first read\nsecond read third read",
length: 36,
},
},
}
for _, tt := range tests {
out := &bytes.Buffer{}
writer := NewRegexpWriter(out, tt.input.re, tt.input.repl)
t.Run(tt.name, func(t *testing.T) {
length := 0
for _, in := range tt.input.in {
l, err := writer.Write([]byte(in))
length = length + l
if tt.output.wantsErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
}
writer.Flush()
assert.Equal(t, tt.output.out, out.String())
assert.Equal(t, tt.output.length, length)
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/create/create_test.go | pkg/cmd/pr/create/create_test.go | package create
import (
"encoding/json"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/context"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/browser"
"github.com/cli/cli/v2/internal/config"
fd "github.com/cli/cli/v2/internal/featuredetection"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/prompter"
"github.com/cli/cli/v2/internal/run"
"github.com/cli/cli/v2/pkg/cmd/pr/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/test"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewCmdCreate(t *testing.T) {
tmpFile := filepath.Join(t.TempDir(), "my-body.md")
err := os.WriteFile(tmpFile, []byte("a body from file"), 0600)
require.NoError(t, err)
tests := []struct {
name string
tty bool
stdin string
cli string
config string
wantsErr bool
wantsOpts CreateOptions
}{
{
name: "empty non-tty",
tty: false,
cli: "",
wantsErr: true,
},
{
name: "only title non-tty",
tty: false,
cli: "--title mytitle",
wantsErr: true,
},
{
name: "minimum non-tty",
tty: false,
cli: "--title mytitle --body ''",
wantsErr: false,
wantsOpts: CreateOptions{
Title: "mytitle",
TitleProvided: true,
Body: "",
BodyProvided: true,
Autofill: false,
RecoverFile: "",
WebMode: false,
IsDraft: false,
BaseBranch: "",
HeadBranch: "",
MaintainerCanModify: true,
},
},
{
name: "empty tty",
tty: true,
cli: "",
wantsErr: false,
wantsOpts: CreateOptions{
Title: "",
TitleProvided: false,
Body: "",
BodyProvided: false,
Autofill: false,
RecoverFile: "",
WebMode: false,
IsDraft: false,
BaseBranch: "",
HeadBranch: "",
MaintainerCanModify: true,
},
},
{
name: "body from stdin",
tty: false,
stdin: "this is on standard input",
cli: "-t mytitle -F -",
wantsErr: false,
wantsOpts: CreateOptions{
Title: "mytitle",
TitleProvided: true,
Body: "this is on standard input",
BodyProvided: true,
Autofill: false,
RecoverFile: "",
WebMode: false,
IsDraft: false,
BaseBranch: "",
HeadBranch: "",
MaintainerCanModify: true,
},
},
{
name: "body from file",
tty: false,
cli: fmt.Sprintf("-t mytitle -F '%s'", tmpFile),
wantsErr: false,
wantsOpts: CreateOptions{
Title: "mytitle",
TitleProvided: true,
Body: "a body from file",
BodyProvided: true,
Autofill: false,
RecoverFile: "",
WebMode: false,
IsDraft: false,
BaseBranch: "",
HeadBranch: "",
MaintainerCanModify: true,
},
},
{
name: "template from file name tty",
tty: true,
cli: "-t mytitle --template bug_fix.md",
wantsErr: false,
wantsOpts: CreateOptions{
Title: "mytitle",
TitleProvided: true,
Body: "",
BodyProvided: false,
Autofill: false,
RecoverFile: "",
WebMode: false,
IsDraft: false,
BaseBranch: "",
HeadBranch: "",
MaintainerCanModify: true,
Template: "bug_fix.md",
},
},
{
name: "template from file name non-tty",
tty: false,
cli: "-t mytitle --template bug_fix.md",
wantsErr: true,
},
{
name: "template and body",
tty: false,
cli: `-t mytitle --template bug_fix.md --body "pr body"`,
wantsErr: true,
},
{
name: "template and body file",
tty: false,
cli: "-t mytitle --template bug_fix.md --body-file body_file.md",
wantsErr: true,
},
{
name: "fill-first",
tty: false,
cli: "--fill-first",
wantsErr: false,
wantsOpts: CreateOptions{
Title: "",
TitleProvided: false,
Body: "",
BodyProvided: false,
Autofill: false,
FillFirst: true,
RecoverFile: "",
WebMode: false,
IsDraft: false,
BaseBranch: "",
HeadBranch: "",
MaintainerCanModify: true,
},
},
{
name: "fill and fill-first",
tty: false,
cli: "--fill --fill-first",
wantsErr: true,
},
{
name: "dry-run and web",
tty: false,
cli: "--web --dry-run",
wantsErr: true,
},
{
name: "editor by cli",
tty: true,
cli: "--editor",
wantsErr: false,
wantsOpts: CreateOptions{
Title: "",
Body: "",
RecoverFile: "",
WebMode: false,
EditorMode: true,
MaintainerCanModify: true,
},
},
{
name: "editor by config",
tty: true,
cli: "",
config: "prefer_editor_prompt: enabled",
wantsErr: false,
wantsOpts: CreateOptions{
Title: "",
Body: "",
RecoverFile: "",
WebMode: false,
EditorMode: true,
MaintainerCanModify: true,
},
},
{
name: "editor and web",
tty: true,
cli: "--editor --web",
wantsErr: true,
},
{
name: "can use web even though editor is enabled by config",
tty: true,
cli: `--web --title mytitle --body "issue body"`,
config: "prefer_editor_prompt: enabled",
wantsErr: false,
wantsOpts: CreateOptions{
Title: "mytitle",
Body: "issue body",
TitleProvided: true,
BodyProvided: true,
RecoverFile: "",
WebMode: true,
EditorMode: false,
MaintainerCanModify: true,
},
},
{
name: "editor with non-tty",
tty: false,
cli: "--editor",
wantsErr: true,
},
{
name: "fill and base",
cli: "--fill --base trunk",
wantsOpts: CreateOptions{
Autofill: true,
BaseBranch: "trunk",
MaintainerCanModify: true,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, stdin, stdout, stderr := iostreams.Test()
if tt.stdin != "" {
_, _ = stdin.WriteString(tt.stdin)
} else if tt.tty {
ios.SetStdinTTY(true)
ios.SetStdoutTTY(true)
}
f := &cmdutil.Factory{
IOStreams: ios,
Config: func() (gh.Config, error) {
if tt.config != "" {
return config.NewFromString(tt.config), nil
}
return config.NewBlankConfig(), nil
},
}
var opts *CreateOptions
cmd := NewCmdCreate(f, func(o *CreateOptions) error {
opts = o
return nil
})
args, err := shlex.Split(tt.cli)
require.NoError(t, err)
cmd.SetArgs(args)
cmd.SetOut(stderr)
cmd.SetErr(stderr)
_, err = cmd.ExecuteC()
if tt.wantsErr {
assert.Error(t, err)
return
} else {
require.NoError(t, err)
}
assert.Equal(t, "", stdout.String())
assert.Equal(t, "", stderr.String())
assert.Equal(t, tt.wantsOpts.Body, opts.Body)
assert.Equal(t, tt.wantsOpts.BodyProvided, opts.BodyProvided)
assert.Equal(t, tt.wantsOpts.Title, opts.Title)
assert.Equal(t, tt.wantsOpts.TitleProvided, opts.TitleProvided)
assert.Equal(t, tt.wantsOpts.Autofill, opts.Autofill)
assert.Equal(t, tt.wantsOpts.FillFirst, opts.FillFirst)
assert.Equal(t, tt.wantsOpts.WebMode, opts.WebMode)
assert.Equal(t, tt.wantsOpts.RecoverFile, opts.RecoverFile)
assert.Equal(t, tt.wantsOpts.IsDraft, opts.IsDraft)
assert.Equal(t, tt.wantsOpts.MaintainerCanModify, opts.MaintainerCanModify)
assert.Equal(t, tt.wantsOpts.BaseBranch, opts.BaseBranch)
assert.Equal(t, tt.wantsOpts.HeadBranch, opts.HeadBranch)
assert.Equal(t, tt.wantsOpts.Template, opts.Template)
})
}
}
func Test_createRun(t *testing.T) {
tests := []struct {
name string
setup func(*CreateOptions, *testing.T) func()
cmdStubs func(*run.CommandStubber)
promptStubs func(*prompter.PrompterMock)
httpStubs func(*httpmock.Registry, *testing.T)
expectedOutputs []string
expectedOut string
expectedErrOut string
expectedBrowse string
wantErr string
tty bool
customBranchConfig bool
}{
{
name: "nontty web",
setup: func(opts *CreateOptions, t *testing.T) func() {
opts.WebMode = true
opts.HeadBranch = "feature"
return func() {}
},
cmdStubs: func(cs *run.CommandStubber) {
cs.Register(`git( .+)? log( .+)? origin/master\.\.\.feature`, 0, "")
},
expectedBrowse: "https://github.com/OWNER/REPO/compare/master...feature?body=&expand=1",
},
{
name: "nontty",
httpStubs: func(reg *httpmock.Registry, t *testing.T) {
reg.Register(
httpmock.GraphQL(`mutation PullRequestCreate\b`),
httpmock.GraphQLMutation(`
{ "data": { "createPullRequest": { "pullRequest": {
"URL": "https://github.com/OWNER/REPO/pull/12"
} } } }`,
func(input map[string]interface{}) {
assert.Equal(t, "REPOID", input["repositoryId"])
assert.Equal(t, "my title", input["title"])
assert.Equal(t, "my body", input["body"])
assert.Equal(t, "master", input["baseRefName"])
assert.Equal(t, "feature", input["headRefName"])
}))
},
setup: func(opts *CreateOptions, t *testing.T) func() {
opts.TitleProvided = true
opts.BodyProvided = true
opts.Title = "my title"
opts.Body = "my body"
opts.HeadBranch = "feature"
return func() {}
},
expectedOut: "https://github.com/OWNER/REPO/pull/12\n",
},
{
name: "dry-run-nontty-with-default-base",
tty: false,
setup: func(opts *CreateOptions, t *testing.T) func() {
opts.TitleProvided = true
opts.BodyProvided = true
opts.Title = "my title"
opts.Body = "my body"
opts.HeadBranch = "feature"
opts.DryRun = true
return func() {}
},
expectedOutputs: []string{
"Would have created a Pull Request with:",
`title: my title`,
`draft: false`,
`base: master`,
`head: feature`,
`maintainerCanModify: false`,
`body:`,
`my body`,
``,
},
expectedErrOut: "",
},
{
name: "dry-run-nontty-with-all-opts",
tty: false,
setup: func(opts *CreateOptions, t *testing.T) func() {
opts.TitleProvided = true
opts.BodyProvided = true
opts.Title = "TITLE"
opts.Body = "BODY"
opts.BaseBranch = "trunk"
opts.HeadBranch = "feature"
opts.Assignees = []string{"monalisa"}
opts.Labels = []string{"bug", "todo"}
opts.Projects = []string{"roadmap"}
opts.Reviewers = []string{"hubot", "monalisa", "/core", "/robots"}
opts.Milestone = "big one.oh"
opts.DryRun = true
return func() {}
},
httpStubs: func(reg *httpmock.Registry, t *testing.T) {
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data": {"viewer": {"login": "OWNER"} } }`))
reg.Register(
httpmock.GraphQL(`query RepositoryAssignableUsers\b`),
httpmock.StringResponse(`
{ "data": { "repository": { "assignableUsers": {
"nodes": [
{ "login": "hubot", "id": "HUBOTID", "name": "" },
{ "login": "MonaLisa", "id": "MONAID", "name": "Mona Display Name" }
],
"pageInfo": { "hasNextPage": false }
} } } }
`))
reg.Register(
httpmock.GraphQL(`query RepositoryLabelList\b`),
httpmock.StringResponse(`
{ "data": { "repository": { "labels": {
"nodes": [
{ "name": "TODO", "id": "TODOID" },
{ "name": "bug", "id": "BUGID" }
],
"pageInfo": { "hasNextPage": false }
} } } }
`))
reg.Register(
httpmock.GraphQL(`query RepositoryMilestoneList\b`),
httpmock.StringResponse(`
{ "data": { "repository": { "milestones": {
"nodes": [
{ "title": "GA", "id": "GAID" },
{ "title": "Big One.oh", "id": "BIGONEID" }
],
"pageInfo": { "hasNextPage": false }
} } } }
`))
reg.Register(
httpmock.GraphQL(`query OrganizationTeamList\b`),
httpmock.StringResponse(`
{ "data": { "organization": { "teams": {
"nodes": [
{ "slug": "core", "id": "COREID" },
{ "slug": "robots", "id": "ROBOTID" }
],
"pageInfo": { "hasNextPage": false }
} } } }
`))
mockRetrieveProjects(t, reg)
},
expectedOutputs: []string{
"Would have created a Pull Request with:",
`title: TITLE`,
`draft: false`,
`base: trunk`,
`head: feature`,
`labels: bug, todo`,
`reviewers: hubot, monalisa, /core, /robots`,
`assignees: monalisa`,
`milestones: big one.oh`,
`projects: roadmap`,
`maintainerCanModify: false`,
`body:`,
`BODY`,
``,
},
expectedErrOut: "",
},
{
name: "dry-run-tty-with-default-base",
tty: true,
setup: func(opts *CreateOptions, t *testing.T) func() {
opts.TitleProvided = true
opts.BodyProvided = true
opts.Title = "my title"
opts.Body = "my body"
opts.HeadBranch = "feature"
opts.DryRun = true
return func() {}
},
expectedOutputs: []string{
`Would have created a Pull Request with:`,
`Title: my title`,
`Draft: false`,
`Base: master`,
`Head: feature`,
`MaintainerCanModify: false`,
`Body:`,
``,
` my body `,
``,
``,
},
expectedErrOut: heredoc.Doc(`
Dry Running pull request for feature into master in OWNER/REPO
`),
},
{
name: "dry-run-tty-with-all-opts",
tty: true,
setup: func(opts *CreateOptions, t *testing.T) func() {
opts.TitleProvided = true
opts.BodyProvided = true
opts.Title = "TITLE"
opts.Body = "BODY"
opts.BaseBranch = "trunk"
opts.HeadBranch = "feature"
opts.Assignees = []string{"monalisa"}
opts.Labels = []string{"bug", "todo"}
opts.Projects = []string{"roadmap"}
opts.Reviewers = []string{"hubot", "monalisa", "/core", "/robots"}
opts.Milestone = "big one.oh"
opts.DryRun = true
return func() {}
},
httpStubs: func(reg *httpmock.Registry, t *testing.T) {
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data": {"viewer": {"login": "OWNER"} } }`))
reg.Register(
httpmock.GraphQL(`query RepositoryAssignableUsers\b`),
httpmock.StringResponse(`
{ "data": { "repository": { "assignableUsers": {
"nodes": [
{ "login": "hubot", "id": "HUBOTID", "name": "" },
{ "login": "MonaLisa", "id": "MONAID", "name": "Mona Display Name" }
],
"pageInfo": { "hasNextPage": false }
} } } }
`))
reg.Register(
httpmock.GraphQL(`query RepositoryLabelList\b`),
httpmock.StringResponse(`
{ "data": { "repository": { "labels": {
"nodes": [
{ "name": "TODO", "id": "TODOID" },
{ "name": "bug", "id": "BUGID" }
],
"pageInfo": { "hasNextPage": false }
} } } }
`))
reg.Register(
httpmock.GraphQL(`query RepositoryMilestoneList\b`),
httpmock.StringResponse(`
{ "data": { "repository": { "milestones": {
"nodes": [
{ "title": "GA", "id": "GAID" },
{ "title": "Big One.oh", "id": "BIGONEID" }
],
"pageInfo": { "hasNextPage": false }
} } } }
`))
reg.Register(
httpmock.GraphQL(`query OrganizationTeamList\b`),
httpmock.StringResponse(`
{ "data": { "organization": { "teams": {
"nodes": [
{ "slug": "core", "id": "COREID" },
{ "slug": "robots", "id": "ROBOTID" }
],
"pageInfo": { "hasNextPage": false }
} } } }
`))
mockRetrieveProjects(t, reg)
},
expectedOutputs: []string{
`Would have created a Pull Request with:`,
`Title: TITLE`,
`Draft: false`,
`Base: trunk`,
`Head: feature`,
`Labels: bug, todo`,
`Reviewers: hubot, monalisa, /core, /robots`,
`Assignees: monalisa`,
`Milestones: big one.oh`,
`Projects: roadmap`,
`MaintainerCanModify: false`,
`Body:`,
``,
` BODY `,
``,
``,
},
expectedErrOut: heredoc.Doc(`
Dry Running pull request for feature into trunk in OWNER/REPO
`),
},
{
name: "dry-run-tty-with-empty-body",
tty: true,
setup: func(opts *CreateOptions, t *testing.T) func() {
opts.TitleProvided = true
opts.BodyProvided = true
opts.Title = "TITLE"
opts.Body = ""
opts.HeadBranch = "feature"
opts.DryRun = true
return func() {}
},
expectedOut: heredoc.Doc(`
Would have created a Pull Request with:
Title: TITLE
Draft: false
Base: master
Head: feature
MaintainerCanModify: false
Body:
No description provided
`),
expectedErrOut: heredoc.Doc(`
Dry Running pull request for feature into master in OWNER/REPO
`),
},
{
name: "select a specific branch to push to on prompt",
tty: true,
setup: func(opts *CreateOptions, t *testing.T) func() {
opts.TitleProvided = true
opts.BodyProvided = true
opts.Title = "my title"
opts.Body = "my body"
return func() {}
},
httpStubs: func(reg *httpmock.Registry, t *testing.T) {
reg.StubRepoResponse("OWNER", "REPO")
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data": {"viewer": {"login": "OWNER"} } }`))
reg.Register(
httpmock.GraphQL(`mutation PullRequestCreate\b`),
httpmock.GraphQLMutation(`
{ "data": { "createPullRequest": { "pullRequest": {
"URL": "https://github.com/OWNER/REPO/pull/12"
} } } }`, func(input map[string]interface{}) {
assert.Equal(t, "REPOID", input["repositoryId"].(string))
assert.Equal(t, "my title", input["title"].(string))
assert.Equal(t, "my body", input["body"].(string))
assert.Equal(t, "master", input["baseRefName"].(string))
assert.Equal(t, "feature", input["headRefName"].(string))
assert.Equal(t, false, input["draft"].(bool))
}))
},
cmdStubs: func(cs *run.CommandStubber) {
cs.Register("git rev-parse --symbolic-full-name feature@{push}", 0, "refs/remotes/origin/feature")
cs.Register(`git show-ref --verify -- HEAD refs/remotes/origin/feature`, 1, "")
cs.Register("git show-ref --verify -- HEAD refs/remotes/origin/feature", 1, "")
cs.Register(`git push --set-upstream origin HEAD:refs/heads/feature`, 0, "")
},
promptStubs: func(pm *prompter.PrompterMock) {
pm.SelectFunc = func(p, _ string, opts []string) (int, error) {
if p == "Where should we push the 'feature' branch?" {
return 0, nil
} else {
return -1, prompter.NoSuchPromptErr(p)
}
}
},
expectedOut: "https://github.com/OWNER/REPO/pull/12\n",
expectedErrOut: "\nCreating pull request for feature into master in OWNER/REPO\n\n",
},
{
name: "skip pushing to branch on prompt",
tty: true,
setup: func(opts *CreateOptions, t *testing.T) func() {
opts.TitleProvided = true
opts.BodyProvided = true
opts.Title = "my title"
opts.Body = "my body"
return func() {}
},
httpStubs: func(reg *httpmock.Registry, t *testing.T) {
reg.StubRepoResponse("OWNER", "REPO")
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data": {"viewer": {"login": "OWNER"} } }`))
reg.Register(
httpmock.GraphQL(`mutation PullRequestCreate\b`),
httpmock.GraphQLMutation(`
{ "data": { "createPullRequest": { "pullRequest": {
"URL": "https://github.com/OWNER/REPO/pull/12"
} } } }`, func(input map[string]interface{}) {
assert.Equal(t, "REPOID", input["repositoryId"].(string))
assert.Equal(t, "my title", input["title"].(string))
assert.Equal(t, "my body", input["body"].(string))
assert.Equal(t, "master", input["baseRefName"].(string))
assert.Equal(t, "feature", input["headRefName"].(string))
assert.Equal(t, false, input["draft"].(bool))
}))
},
cmdStubs: func(cs *run.CommandStubber) {
cs.Register("git rev-parse --symbolic-full-name feature@{push}", 0, "refs/remotes/origin/feature")
cs.Register(`git show-ref --verify -- HEAD refs/remotes/origin/feature`, 1, "")
cs.Register("git show-ref --verify -- HEAD refs/remotes/origin/feature", 1, "")
},
promptStubs: func(pm *prompter.PrompterMock) {
pm.SelectFunc = func(p, _ string, opts []string) (int, error) {
if p == "Where should we push the 'feature' branch?" {
return prompter.IndexFor(opts, "Skip pushing the branch")
} else {
return -1, prompter.NoSuchPromptErr(p)
}
}
},
expectedOut: "https://github.com/OWNER/REPO/pull/12\n",
expectedErrOut: "\nCreating pull request for feature into master in OWNER/REPO\n\n",
},
{
name: "project v2",
tty: true,
setup: func(opts *CreateOptions, t *testing.T) func() {
opts.TitleProvided = true
opts.BodyProvided = true
opts.Title = "my title"
opts.Body = "my body"
opts.Projects = []string{"RoadmapV2"}
return func() {}
},
httpStubs: func(reg *httpmock.Registry, t *testing.T) {
reg.StubRepoResponse("OWNER", "REPO")
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data": {"viewer": {"login": "OWNER"} } }`))
mockRetrieveProjects(t, reg)
reg.Register(
httpmock.GraphQL(`mutation PullRequestCreate\b`),
httpmock.GraphQLMutation(`
{ "data": { "createPullRequest": { "pullRequest": {
"id": "PullRequest#1",
"URL": "https://github.com/OWNER/REPO/pull/12"
} } } }
`, func(input map[string]interface{}) {
assert.Equal(t, "REPOID", input["repositoryId"].(string))
assert.Equal(t, "my title", input["title"].(string))
assert.Equal(t, "my body", input["body"].(string))
assert.Equal(t, "master", input["baseRefName"].(string))
assert.Equal(t, "feature", input["headRefName"].(string))
assert.Equal(t, false, input["draft"].(bool))
}))
reg.Register(
httpmock.GraphQL(`mutation UpdateProjectV2Items\b`),
httpmock.GraphQLQuery(`
{ "data": { "add_000": { "item": {
"id": "1"
} } } }
`, func(mutations string, inputs map[string]interface{}) {
variables, err := json.Marshal(inputs)
assert.NoError(t, err)
expectedMutations := "mutation UpdateProjectV2Items($input_000: AddProjectV2ItemByIdInput!) {add_000: addProjectV2ItemById(input: $input_000) { item { id } }}"
expectedVariables := `{"input_000":{"contentId":"PullRequest#1","projectId":"ROADMAPV2ID"}}`
assert.Equal(t, expectedMutations, mutations)
assert.Equal(t, expectedVariables, string(variables))
}))
},
cmdStubs: func(cs *run.CommandStubber) {
cs.Register("git rev-parse --symbolic-full-name feature@{push}", 0, "refs/remotes/origin/feature")
cs.Register(`git show-ref --verify -- HEAD refs/remotes/origin/feature`, 1, "")
cs.Register(`git show-ref --verify -- HEAD refs/remotes/origin/feature`, 1, "")
cs.Register(`git push --set-upstream origin HEAD:refs/heads/feature`, 0, "")
},
promptStubs: func(pm *prompter.PrompterMock) {
pm.SelectFunc = func(p, _ string, opts []string) (int, error) {
if p == "Where should we push the 'feature' branch?" {
return 0, nil
} else {
return -1, prompter.NoSuchPromptErr(p)
}
}
},
expectedOut: "https://github.com/OWNER/REPO/pull/12\n",
expectedErrOut: "\nCreating pull request for feature into master in OWNER/REPO\n\n",
},
{
name: "no maintainer modify",
tty: true,
setup: func(opts *CreateOptions, t *testing.T) func() {
opts.TitleProvided = true
opts.BodyProvided = true
opts.Title = "my title"
opts.Body = "my body"
return func() {}
},
httpStubs: func(reg *httpmock.Registry, t *testing.T) {
reg.StubRepoResponse("OWNER", "REPO")
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data": {"viewer": {"login": "OWNER"} } }`))
reg.Register(
httpmock.GraphQL(`mutation PullRequestCreate\b`),
httpmock.GraphQLMutation(`
{ "data": { "createPullRequest": { "pullRequest": {
"URL": "https://github.com/OWNER/REPO/pull/12"
} } } }
`, func(input map[string]interface{}) {
assert.Equal(t, false, input["maintainerCanModify"].(bool))
assert.Equal(t, "REPOID", input["repositoryId"].(string))
assert.Equal(t, "my title", input["title"].(string))
assert.Equal(t, "my body", input["body"].(string))
assert.Equal(t, "master", input["baseRefName"].(string))
assert.Equal(t, "feature", input["headRefName"].(string))
}))
},
cmdStubs: func(cs *run.CommandStubber) {
cs.Register("git rev-parse --symbolic-full-name feature@{push}", 0, "refs/remotes/origin/feature")
cs.Register(`git show-ref --verify -- HEAD refs/remotes/origin/feature`, 1, "")
cs.Register(`git show-ref --verify -- HEAD refs/remotes/origin/feature`, 1, "")
cs.Register(`git push --set-upstream origin HEAD:refs/heads/feature`, 0, "")
},
promptStubs: func(pm *prompter.PrompterMock) {
pm.SelectFunc = func(p, _ string, opts []string) (int, error) {
if p == "Where should we push the 'feature' branch?" {
return 0, nil
} else {
return -1, prompter.NoSuchPromptErr(p)
}
}
},
expectedOut: "https://github.com/OWNER/REPO/pull/12\n",
expectedErrOut: "\nCreating pull request for feature into master in OWNER/REPO\n\n",
},
{
name: "create fork",
tty: true,
setup: func(opts *CreateOptions, t *testing.T) func() {
opts.TitleProvided = true
opts.BodyProvided = true
opts.Title = "title"
opts.Body = "body"
return func() {}
},
httpStubs: func(reg *httpmock.Registry, t *testing.T) {
reg.StubRepoResponse("OWNER", "REPO")
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data": {"viewer": {"login": "monalisa"} } }`))
reg.Register(
httpmock.REST("POST", "repos/OWNER/REPO/forks"),
httpmock.StatusStringResponse(201, `
{ "node_id": "NODEID",
"name": "REPO",
"owner": {"login": "monalisa"}
}`))
reg.Register(
httpmock.GraphQL(`mutation PullRequestCreate\b`),
httpmock.GraphQLMutation(`
{ "data": { "createPullRequest": { "pullRequest": {
"URL": "https://github.com/OWNER/REPO/pull/12"
}}}}`, func(input map[string]interface{}) {
assert.Equal(t, "REPOID", input["repositoryId"].(string))
assert.Equal(t, "master", input["baseRefName"].(string))
assert.Equal(t, "monalisa:feature", input["headRefName"].(string))
}))
},
cmdStubs: func(cs *run.CommandStubber) {
cs.Register("git rev-parse --symbolic-full-name feature@{push}", 1, "")
cs.Register("git config remote.pushDefault", 1, "")
cs.Register("git config push.default", 1, "")
cs.Register(`git show-ref --verify -- HEAD refs/remotes/origin/feature`, 1, "")
cs.Register("git remote rename origin upstream", 0, "")
cs.Register(`git remote add origin https://github.com/monalisa/REPO.git`, 0, "")
cs.Register(`git push --set-upstream origin HEAD:refs/heads/feature`, 0, "")
cs.Register(`git config --add remote.upstream.gh-resolved base`, 0, "")
},
promptStubs: func(pm *prompter.PrompterMock) {
pm.SelectFunc = func(p, _ string, opts []string) (int, error) {
if p == "Where should we push the 'feature' branch?" {
return prompter.IndexFor(opts, "Create a fork of OWNER/REPO")
} else {
return -1, prompter.NoSuchPromptErr(p)
}
}
},
expectedOut: "https://github.com/OWNER/REPO/pull/12\n",
expectedErrOut: "\nCreating pull request for monalisa:feature into master in OWNER/REPO\n\nChanged OWNER/REPO remote to \"upstream\"\nAdded monalisa/REPO as remote \"origin\"\n! Repository monalisa/REPO set as the default repository. To learn more about the default repository, run: gh repo set-default --help\n",
},
{
name: "pushed to non base repo",
tty: true,
setup: func(opts *CreateOptions, t *testing.T) func() {
opts.TitleProvided = true
opts.BodyProvided = true
opts.Title = "title"
opts.Body = "body"
opts.Remotes = func() (context.Remotes, error) {
return context.Remotes{
{
Remote: &git.Remote{
Name: "upstream",
Resolved: "base",
},
Repo: ghrepo.New("OWNER", "REPO"),
},
{
Remote: &git.Remote{
Name: "origin",
Resolved: "base",
},
Repo: ghrepo.New("monalisa", "REPO"),
},
}, nil
}
return func() {}
},
httpStubs: func(reg *httpmock.Registry, t *testing.T) {
reg.Register(
httpmock.GraphQL(`mutation PullRequestCreate\b`),
httpmock.GraphQLMutation(`
{ "data": { "createPullRequest": { "pullRequest": {
"URL": "https://github.com/OWNER/REPO/pull/12"
} } } }`, func(input map[string]interface{}) {
assert.Equal(t, "REPOID", input["repositoryId"].(string))
assert.Equal(t, "master", input["baseRefName"].(string))
assert.Equal(t, "monalisa:feature", input["headRefName"].(string))
}))
},
cmdStubs: func(cs *run.CommandStubber) {
cs.Register("git rev-parse --symbolic-full-name feature@{push}", 0, "refs/remotes/origin/feature")
cs.Register("git show-ref --verify -- HEAD refs/remotes/origin/feature", 0, heredoc.Doc(`
deadbeef HEAD
deadbeef refs/remotes/origin/feature`))
},
expectedOut: "https://github.com/OWNER/REPO/pull/12\n",
expectedErrOut: "\nCreating pull request for monalisa:feature into master in OWNER/REPO\n\n",
},
{
name: "pushed to different branch name",
tty: true,
setup: func(opts *CreateOptions, t *testing.T) func() {
opts.TitleProvided = true
opts.BodyProvided = true
opts.Title = "title"
opts.Body = "body"
return func() {}
},
httpStubs: func(reg *httpmock.Registry, t *testing.T) {
reg.Register(
httpmock.GraphQL(`mutation PullRequestCreate\b`),
httpmock.GraphQLMutation(`
{ "data": { "createPullRequest": { "pullRequest": {
"URL": "https://github.com/OWNER/REPO/pull/12"
} } } }
`, func(input map[string]interface{}) {
assert.Equal(t, "REPOID", input["repositoryId"].(string))
assert.Equal(t, "master", input["baseRefName"].(string))
assert.Equal(t, "my-feat2", input["headRefName"].(string))
}))
},
customBranchConfig: true,
cmdStubs: func(cs *run.CommandStubber) {
cs.Register(`git config --get-regexp \^branch\\\.feature\\\.`, 0, heredoc.Doc(`
branch.feature.remote origin
branch.feature.merge refs/heads/my-feat2
`))
cs.Register("git rev-parse --symbolic-full-name feature@{push}", 0, "refs/remotes/origin/my-feat2")
cs.Register("git show-ref --verify -- HEAD refs/remotes/origin/my-feat2", 0, heredoc.Doc(`
deadbeef HEAD
deadbeef refs/remotes/origin/my-feat2
`))
},
expectedOut: "https://github.com/OWNER/REPO/pull/12\n",
expectedErrOut: "\nCreating pull request for my-feat2 into master in OWNER/REPO\n\n",
},
{
name: "non legacy template",
tty: true,
setup: func(opts *CreateOptions, t *testing.T) func() {
opts.TitleProvided = true
opts.Title = "my title"
opts.HeadBranch = "feature"
opts.RootDirOverride = "./fixtures/repoWithNonLegacyPRTemplates"
return func() {}
},
httpStubs: func(reg *httpmock.Registry, t *testing.T) {
reg.Register(
httpmock.GraphQL(`query PullRequestTemplates\b`),
httpmock.StringResponse(`
{ "data": { "repository": { "pullRequestTemplates": [
{ "filename": "template1",
"body": "this is a bug" },
{ "filename": "template2",
"body": "this is a enhancement" }
] } } }`))
reg.Register(
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | true |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/merge/merge.go | pkg/cmd/pr/merge/merge.go | package merge
import (
"context"
"errors"
"fmt"
"net/http"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
ghContext "github.com/cli/cli/v2/context"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmd/pr/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/pkg/surveyext"
"github.com/spf13/cobra"
)
type editor interface {
Edit(string, string) (string, error)
}
type MergeOptions struct {
HttpClient func() (*http.Client, error)
GitClient *git.Client
IO *iostreams.IOStreams
Branch func() (string, error)
Remotes func() (ghContext.Remotes, error)
Prompter shared.Prompt
Finder shared.PRFinder
SelectorArg string
DeleteBranch bool
MergeMethod PullRequestMergeMethod
AutoMergeEnable bool
AutoMergeDisable bool
AuthorEmail string
Body string
BodySet bool
Subject string
Editor editor
UseAdmin bool
IsDeleteBranchIndicated bool
CanDeleteLocalBranch bool
MergeStrategyEmpty bool
MatchHeadCommit string
}
// ErrAlreadyInMergeQueue indicates that the pull request is already in a merge queue
var ErrAlreadyInMergeQueue = errors.New("already in merge queue")
func NewCmdMerge(f *cmdutil.Factory, runF func(*MergeOptions) error) *cobra.Command {
opts := &MergeOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
GitClient: f.GitClient,
Branch: f.Branch,
Remotes: f.Remotes,
Prompter: f.Prompter,
}
var (
flagMerge bool
flagSquash bool
flagRebase bool
)
var bodyFile string
cmd := &cobra.Command{
Use: "merge [<number> | <url> | <branch>]",
Short: "Merge a pull request",
Long: heredoc.Docf(`
Merge a pull request on GitHub.
Without an argument, the pull request that belongs to the current branch
is selected.
When targeting a branch that requires a merge queue, no merge strategy is required.
If required checks have not yet passed, auto-merge will be enabled.
If required checks have passed, the pull request will be added to the merge queue.
To bypass a merge queue and merge directly, pass the %[1]s--admin%[1]s flag.
`, "`"),
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
opts.Finder = shared.NewFinder(f)
if repoOverride, _ := cmd.Flags().GetString("repo"); repoOverride != "" && len(args) == 0 {
return cmdutil.FlagErrorf("argument required when using the --repo flag")
}
if len(args) > 0 {
opts.SelectorArg = args[0]
}
methodFlags := 0
if flagMerge {
opts.MergeMethod = PullRequestMergeMethodMerge
methodFlags++
}
if flagRebase {
opts.MergeMethod = PullRequestMergeMethodRebase
methodFlags++
}
if flagSquash {
opts.MergeMethod = PullRequestMergeMethodSquash
methodFlags++
}
if methodFlags == 0 {
opts.MergeStrategyEmpty = true
} else if methodFlags > 1 {
return cmdutil.FlagErrorf("only one of --merge, --rebase, or --squash can be enabled")
}
opts.IsDeleteBranchIndicated = cmd.Flags().Changed("delete-branch")
opts.CanDeleteLocalBranch = !cmd.Flags().Changed("repo")
bodyProvided := cmd.Flags().Changed("body")
bodyFileProvided := bodyFile != ""
if err := cmdutil.MutuallyExclusive(
"specify only one of `--auto`, `--disable-auto`, or `--admin`",
opts.AutoMergeEnable,
opts.AutoMergeDisable,
opts.UseAdmin,
); err != nil {
return err
}
if err := cmdutil.MutuallyExclusive(
"specify only one of `--body` or `--body-file`",
bodyProvided,
bodyFileProvided,
); err != nil {
return err
}
if bodyProvided || bodyFileProvided {
opts.BodySet = true
if bodyFileProvided {
b, err := cmdutil.ReadFile(bodyFile, opts.IO.In)
if err != nil {
return err
}
opts.Body = string(b)
}
}
opts.Editor = &userEditor{
io: opts.IO,
config: f.Config,
}
if runF != nil {
return runF(opts)
}
err := mergeRun(opts)
if errors.Is(err, ErrAlreadyInMergeQueue) {
return nil
}
return err
},
}
cmd.Flags().BoolVar(&opts.UseAdmin, "admin", false, "Use administrator privileges to merge a pull request that does not meet requirements")
cmd.Flags().BoolVarP(&opts.DeleteBranch, "delete-branch", "d", false, "Delete the local and remote branch after merge")
cmd.Flags().StringVarP(&opts.Body, "body", "b", "", "Body `text` for the merge commit")
cmd.Flags().StringVarP(&bodyFile, "body-file", "F", "", "Read body text from `file` (use \"-\" to read from standard input)")
cmd.Flags().StringVarP(&opts.Subject, "subject", "t", "", "Subject `text` for the merge commit")
cmd.Flags().BoolVarP(&flagMerge, "merge", "m", false, "Merge the commits with the base branch")
cmd.Flags().BoolVarP(&flagRebase, "rebase", "r", false, "Rebase the commits onto the base branch")
cmd.Flags().BoolVarP(&flagSquash, "squash", "s", false, "Squash the commits into one commit and merge it into the base branch")
cmd.Flags().BoolVar(&opts.AutoMergeEnable, "auto", false, "Automatically merge only after necessary requirements are met")
cmd.Flags().BoolVar(&opts.AutoMergeDisable, "disable-auto", false, "Disable auto-merge for this pull request")
cmd.Flags().StringVar(&opts.MatchHeadCommit, "match-head-commit", "", "Commit `SHA` that the pull request head must match to allow merge")
cmd.Flags().StringVarP(&opts.AuthorEmail, "author-email", "A", "", "Email `text` for merge commit author")
return cmd
}
// mergeContext contains state and dependencies to merge a pull request.
type mergeContext struct {
pr *api.PullRequest
baseRepo ghrepo.Interface
httpClient *http.Client
opts *MergeOptions
cs *iostreams.ColorScheme
isTerminal bool
merged bool
localBranchExists bool
autoMerge bool
crossRepoPR bool
deleteBranch bool
mergeQueueRequired bool
}
// Attempt to disable auto merge on the pull request.
func (m *mergeContext) disableAutoMerge() error {
if err := disableAutoMerge(m.httpClient, m.baseRepo, m.pr.ID); err != nil {
return err
}
return m.infof("%s Auto-merge disabled for pull request %s#%d\n", m.cs.SuccessIconWithColor(m.cs.Green), ghrepo.FullName(m.baseRepo), m.pr.Number)
}
// Check if this pull request is in a merge queue
func (m *mergeContext) inMergeQueue() error {
// if the pull request is in a merge queue no further action is possible
if m.pr.IsInMergeQueue {
_ = m.warnf("%s Pull request %s#%d is already queued to merge\n", m.cs.WarningIcon(), ghrepo.FullName(m.baseRepo), m.pr.Number)
return ErrAlreadyInMergeQueue
}
return nil
}
// Warn if the pull request and the remote branch have diverged.
func (m *mergeContext) warnIfDiverged() {
if m.opts.SelectorArg != "" || len(m.pr.Commits.Nodes) == 0 {
return
}
localBranchLastCommit, err := m.opts.GitClient.LastCommit(context.Background())
if err != nil {
return
}
if localBranchLastCommit.Sha == m.pr.Commits.Nodes[len(m.pr.Commits.Nodes)-1].Commit.OID {
return
}
_ = m.warnf("%s Pull request %s#%d (%s) has diverged from local branch\n", m.cs.Yellow("!"), ghrepo.FullName(m.baseRepo), m.pr.Number, m.pr.Title)
}
// Check if the current state of the pull request allows for merging
func (m *mergeContext) canMerge() error {
if m.mergeQueueRequired {
// Requesting branch deletion on a PR with a merge queue
// policy is not allowed. Doing so can unexpectedly
// delete branches before merging, close the PR, and remove
// the PR from the merge queue.
if m.opts.DeleteBranch {
return fmt.Errorf("%s Cannot use `-d` or `--delete-branch` when merge queue enabled", m.cs.FailureIcon())
}
// Otherwise, a pull request can always be added to the merge queue
return nil
}
reason := blockedReason(m.pr.MergeStateStatus, m.opts.UseAdmin)
if reason == "" || m.autoMerge || m.merged {
return nil
}
_ = m.warnf("%s Pull request %s#%d is not mergeable: %s.\n", m.cs.FailureIcon(), ghrepo.FullName(m.baseRepo), m.pr.Number, reason)
_ = m.warnf("To have the pull request merged after all the requirements have been met, add the `--auto` flag.\n")
if remote := remoteForMergeConflictResolution(m.baseRepo, m.pr, m.opts); remote != nil {
mergeOrRebase := "merge"
if m.opts.MergeMethod == PullRequestMergeMethodRebase {
mergeOrRebase = "rebase"
}
fetchBranch := fmt.Sprintf("%s %s", remote.Name, m.pr.BaseRefName)
mergeBranch := fmt.Sprintf("%s %s/%s", mergeOrRebase, remote.Name, m.pr.BaseRefName)
cmd := fmt.Sprintf("gh pr checkout %d && git fetch %s && git %s", m.pr.Number, fetchBranch, mergeBranch)
_ = m.warnf("Run the following to resolve the merge conflicts locally:\n %s\n", m.cs.Bold(cmd))
}
if !m.opts.UseAdmin && allowsAdminOverride(m.pr.MergeStateStatus) {
// TODO: show this flag only to repo admins
_ = m.warnf("To use administrator privileges to immediately merge the pull request, add the `--admin` flag.\n")
}
return cmdutil.SilentError
}
// Merge the pull request. May prompt the user for input parameters for the merge.
func (m *mergeContext) merge() error {
if m.merged {
return nil
}
payload := mergePayload{
repo: m.baseRepo,
pullRequestID: m.pr.ID,
method: m.opts.MergeMethod,
auto: m.autoMerge,
commitSubject: m.opts.Subject,
commitBody: m.opts.Body,
setCommitBody: m.opts.BodySet,
expectedHeadOid: m.opts.MatchHeadCommit,
authorEmail: m.opts.AuthorEmail,
}
if m.shouldAddToMergeQueue() {
if !m.opts.MergeStrategyEmpty {
// only warn for now
_ = m.warnf("%s The merge strategy for %s is set by the merge queue\n", m.cs.Yellow("!"), m.pr.BaseRefName)
}
// auto merge will either enable auto merge or add to the merge queue
payload.auto = true
} else {
// get user input if not already given
if m.opts.MergeStrategyEmpty {
if !m.opts.IO.CanPrompt() {
return cmdutil.FlagErrorf("--merge, --rebase, or --squash required when not running interactively")
}
_ = m.infof("Merging pull request %s#%d (%s)\n", ghrepo.FullName(m.baseRepo), m.pr.Number, m.pr.Title)
apiClient := api.NewClientFromHTTP(m.httpClient)
r, err := api.GitHubRepo(apiClient, m.baseRepo)
if err != nil {
return err
}
payload.method, err = mergeMethodSurvey(m.opts.Prompter, r)
if err != nil {
return err
}
m.deleteBranch, err = deleteBranchSurvey(m.opts, m.crossRepoPR, m.localBranchExists)
if err != nil {
return err
}
allowEditMsg := payload.method != PullRequestMergeMethodRebase
for {
action, err := confirmSurvey(m.opts.Prompter, allowEditMsg)
if err != nil {
return fmt.Errorf("unable to confirm: %w", err)
}
submit, err := confirmSubmission(m.httpClient, m.opts, action, &payload)
if err != nil {
return err
}
if submit {
break
}
}
}
}
err := mergePullRequest(m.httpClient, payload)
if err != nil {
return err
}
if m.shouldAddToMergeQueue() {
_ = m.infof("%s Pull request %s#%d will be added to the merge queue for %s when ready\n", m.cs.SuccessIconWithColor(m.cs.Green), ghrepo.FullName(m.baseRepo), m.pr.Number, m.pr.BaseRefName)
return nil
}
if payload.auto {
method := ""
switch payload.method {
case PullRequestMergeMethodRebase:
method = " via rebase"
case PullRequestMergeMethodSquash:
method = " via squash"
}
return m.infof("%s Pull request %s#%d will be automatically merged%s when all requirements are met\n", m.cs.SuccessIconWithColor(m.cs.Green), ghrepo.FullName(m.baseRepo), m.pr.Number, method)
}
action := "Merged"
switch payload.method {
case PullRequestMergeMethodRebase:
action = "Rebased and merged"
case PullRequestMergeMethodSquash:
action = "Squashed and merged"
}
return m.infof("%s %s pull request %s#%d (%s)\n", m.cs.SuccessIconWithColor(m.cs.Magenta), action, ghrepo.FullName(m.baseRepo), m.pr.Number, m.pr.Title)
}
// Delete local branch if requested and if allowed.
func (m *mergeContext) deleteLocalBranch() error {
if m.autoMerge {
return nil
}
if m.merged {
if m.opts.IO.CanPrompt() && !m.opts.IsDeleteBranchIndicated {
message := fmt.Sprintf("Pull request %s#%d was already merged. Delete the branch locally?", ghrepo.FullName(m.baseRepo), m.pr.Number)
confirmed, err := m.opts.Prompter.Confirm(message, false)
if err != nil {
return fmt.Errorf("could not prompt: %w", err)
}
m.deleteBranch = confirmed
} else {
_ = m.warnf("%s Pull request %s#%d was already merged\n", m.cs.WarningIcon(), ghrepo.FullName(m.baseRepo), m.pr.Number)
}
}
if !m.deleteBranch || !m.opts.CanDeleteLocalBranch || !m.localBranchExists {
return nil
}
currentBranch, err := m.opts.Branch()
if err != nil {
return err
}
switchedToBranch := ""
ctx := context.Background()
// branch the command was run on is the same as the pull request branch
if currentBranch == m.pr.HeadRefName {
remotes, err := m.opts.Remotes()
if err != nil {
return err
}
baseRemote, err := remotes.FindByRepo(m.baseRepo.RepoOwner(), m.baseRepo.RepoName())
if err != nil {
return err
}
targetBranch := m.pr.BaseRefName
if m.opts.GitClient.HasLocalBranch(ctx, targetBranch) {
if err := m.opts.GitClient.CheckoutBranch(ctx, targetBranch); err != nil {
return err
}
} else {
if err := m.opts.GitClient.CheckoutNewBranch(ctx, baseRemote.Name, targetBranch); err != nil {
return err
}
}
if err := m.opts.GitClient.Pull(ctx, baseRemote.Name, targetBranch); err != nil {
_ = m.warnf("%s warning: not possible to fast-forward to: %q\n", m.cs.WarningIcon(), targetBranch)
}
switchedToBranch = targetBranch
}
if err := m.opts.GitClient.DeleteLocalBranch(ctx, m.pr.HeadRefName); err != nil {
return fmt.Errorf("failed to delete local branch %s: %w", m.cs.Cyan(m.pr.HeadRefName), err)
}
switchedStatement := ""
if switchedToBranch != "" {
switchedStatement = fmt.Sprintf(" and switched to branch %s", m.cs.Cyan(switchedToBranch))
}
return m.infof("%s Deleted local branch %s%s\n", m.cs.SuccessIconWithColor(m.cs.Red), m.cs.Cyan(m.pr.HeadRefName), switchedStatement)
}
// Delete the remote branch if requested and if allowed.
func (m *mergeContext) deleteRemoteBranch() error {
// the user was already asked if they want to delete the branch if they didn't provide the flag
if !m.deleteBranch || m.crossRepoPR || m.autoMerge {
return nil
}
if !m.merged {
apiClient := api.NewClientFromHTTP(m.httpClient)
err := api.BranchDeleteRemote(apiClient, m.baseRepo, m.pr.HeadRefName)
if err != nil {
// Normally, the API returns 422, with the message "Reference does not exist"
// when the branch has already been deleted. It also returns 404 with the same
// message, but that rarely happens. In both cases, we should not return an
// error because the goal is already achieved.
var isAlreadyDeletedError bool
if httpErr := (api.HTTPError{}); errors.As(err, &httpErr) {
// TODO: since the API returns 422 for a couple of other reasons, for more accuracy
// we might want to check the error message against "Reference does not exist".
isAlreadyDeletedError = httpErr.StatusCode == http.StatusUnprocessableEntity || httpErr.StatusCode == http.StatusNotFound
}
if !isAlreadyDeletedError {
return fmt.Errorf("failed to delete remote branch %s: %w", m.cs.Cyan(m.pr.HeadRefName), err)
}
}
}
return m.infof("%s Deleted remote branch %s\n", m.cs.SuccessIconWithColor(m.cs.Red), m.cs.Cyan(m.pr.HeadRefName))
}
// Add the Pull Request to a merge queue
// Admins can bypass the queue and merge directly
func (m *mergeContext) shouldAddToMergeQueue() bool {
return m.mergeQueueRequired && !m.opts.UseAdmin
}
func (m *mergeContext) warnf(format string, args ...interface{}) error {
_, err := fmt.Fprintf(m.opts.IO.ErrOut, format, args...)
return err
}
func (m *mergeContext) infof(format string, args ...interface{}) error {
if !m.isTerminal {
return nil
}
_, err := fmt.Fprintf(m.opts.IO.ErrOut, format, args...)
return err
}
// Creates a new MergeContext from MergeOptions.
func NewMergeContext(opts *MergeOptions) (*mergeContext, error) {
findOptions := shared.FindOptions{
Selector: opts.SelectorArg,
Fields: []string{"id", "number", "state", "title", "lastCommit", "mergeStateStatus", "headRepositoryOwner", "headRefName", "baseRefName", "headRefOid", "isInMergeQueue", "isMergeQueueEnabled"},
}
pr, baseRepo, err := opts.Finder.Find(findOptions)
if err != nil {
return nil, err
}
httpClient, err := opts.HttpClient()
if err != nil {
return nil, err
}
return &mergeContext{
opts: opts,
pr: pr,
cs: opts.IO.ColorScheme(),
baseRepo: baseRepo,
isTerminal: opts.IO.IsStdoutTTY(),
httpClient: httpClient,
merged: pr.State == MergeStateStatusMerged,
deleteBranch: opts.DeleteBranch,
crossRepoPR: pr.HeadRepositoryOwner.Login != baseRepo.RepoOwner(),
autoMerge: opts.AutoMergeEnable && !isImmediatelyMergeable(pr.MergeStateStatus),
localBranchExists: opts.CanDeleteLocalBranch && opts.GitClient.HasLocalBranch(context.Background(), pr.HeadRefName),
mergeQueueRequired: pr.IsMergeQueueEnabled,
}, nil
}
// Run the merge command.
func mergeRun(opts *MergeOptions) error {
ctx, err := NewMergeContext(opts)
if err != nil {
return err
}
if err := ctx.inMergeQueue(); err != nil {
return err
}
// no further action is possible when disabling auto merge
if opts.AutoMergeDisable {
return ctx.disableAutoMerge()
}
ctx.warnIfDiverged()
if err := ctx.canMerge(); err != nil {
return err
}
if err := ctx.merge(); err != nil {
return err
}
if err := ctx.deleteLocalBranch(); err != nil {
return err
}
if err := ctx.deleteRemoteBranch(); err != nil {
return err
}
return nil
}
func mergeMethodSurvey(p shared.Prompt, baseRepo *api.Repository) (PullRequestMergeMethod, error) {
type mergeOption struct {
title string
method PullRequestMergeMethod
}
var mergeOpts []mergeOption
if baseRepo.MergeCommitAllowed {
opt := mergeOption{title: "Create a merge commit", method: PullRequestMergeMethodMerge}
mergeOpts = append(mergeOpts, opt)
}
if baseRepo.RebaseMergeAllowed {
opt := mergeOption{title: "Rebase and merge", method: PullRequestMergeMethodRebase}
mergeOpts = append(mergeOpts, opt)
}
if baseRepo.SquashMergeAllowed {
opt := mergeOption{title: "Squash and merge", method: PullRequestMergeMethodSquash}
mergeOpts = append(mergeOpts, opt)
}
var surveyOpts []string
for _, v := range mergeOpts {
surveyOpts = append(surveyOpts, v.title)
}
result, err := p.Select("What merge method would you like to use?", "", surveyOpts)
return mergeOpts[result].method, err
}
func deleteBranchSurvey(opts *MergeOptions, crossRepoPR, localBranchExists bool) (bool, error) {
if !opts.IsDeleteBranchIndicated {
var message string
if opts.CanDeleteLocalBranch && localBranchExists {
if crossRepoPR {
message = "Delete the branch locally?"
} else {
message = "Delete the branch locally and on GitHub?"
}
} else if !crossRepoPR {
message = "Delete the branch on GitHub?"
}
return opts.Prompter.Confirm(message, false)
}
return opts.DeleteBranch, nil
}
func confirmSurvey(p shared.Prompt, allowEditMsg bool) (shared.Action, error) {
const (
submitLabel = "Submit"
editCommitSubjectLabel = "Edit commit subject"
editCommitMsgLabel = "Edit commit message"
cancelLabel = "Cancel"
)
options := []string{submitLabel}
if allowEditMsg {
options = append(options, editCommitSubjectLabel, editCommitMsgLabel)
}
options = append(options, cancelLabel)
selected, err := p.Select("What's next?", "", options)
if err != nil {
return shared.CancelAction, fmt.Errorf("could not prompt: %w", err)
}
switch options[selected] {
case submitLabel:
return shared.SubmitAction, nil
case editCommitSubjectLabel:
return shared.EditCommitSubjectAction, nil
case editCommitMsgLabel:
return shared.EditCommitMessageAction, nil
default:
return shared.CancelAction, nil
}
}
func confirmSubmission(client *http.Client, opts *MergeOptions, action shared.Action, payload *mergePayload) (bool, error) {
var err error
switch action {
case shared.EditCommitMessageAction:
if !payload.setCommitBody {
_, payload.commitBody, err = getMergeText(client, payload.repo, payload.pullRequestID, payload.method)
if err != nil {
return false, err
}
}
payload.commitBody, err = opts.Editor.Edit("*.md", payload.commitBody)
if err != nil {
return false, err
}
payload.setCommitBody = true
return false, nil
case shared.EditCommitSubjectAction:
if payload.commitSubject == "" {
payload.commitSubject, _, err = getMergeText(client, payload.repo, payload.pullRequestID, payload.method)
if err != nil {
return false, err
}
}
payload.commitSubject, err = opts.Editor.Edit("*.md", payload.commitSubject)
if err != nil {
return false, err
}
return false, nil
case shared.CancelAction:
fmt.Fprintln(opts.IO.ErrOut, "Cancelled.")
return false, cmdutil.CancelError
case shared.SubmitAction:
return true, nil
default:
return false, fmt.Errorf("unable to confirm: %w", err)
}
}
type userEditor struct {
io *iostreams.IOStreams
config func() (gh.Config, error)
}
func (e *userEditor) Edit(filename, startingText string) (string, error) {
editorCommand, err := cmdutil.DetermineEditor(e.config)
if err != nil {
return "", err
}
return surveyext.Edit(editorCommand, filename, startingText, e.io.In, e.io.Out, e.io.ErrOut)
}
// blockedReason translates various MergeStateStatus GraphQL values into human-readable reason
func blockedReason(status string, useAdmin bool) string {
switch status {
case MergeStateStatusBlocked:
if useAdmin {
return ""
}
return "the base branch policy prohibits the merge"
case MergeStateStatusBehind:
if useAdmin {
return ""
}
return "the head branch is not up to date with the base branch"
case MergeStateStatusDirty:
return "the merge commit cannot be cleanly created"
default:
return ""
}
}
func allowsAdminOverride(status string) bool {
switch status {
case MergeStateStatusBlocked, MergeStateStatusBehind:
return true
default:
return false
}
}
func remoteForMergeConflictResolution(baseRepo ghrepo.Interface, pr *api.PullRequest, opts *MergeOptions) *ghContext.Remote {
if !mergeConflictStatus(pr.MergeStateStatus) || !opts.CanDeleteLocalBranch {
return nil
}
remotes, err := opts.Remotes()
if err != nil {
return nil
}
remote, err := remotes.FindByRepo(baseRepo.RepoOwner(), baseRepo.RepoName())
if err != nil {
return nil
}
return remote
}
func mergeConflictStatus(status string) bool {
return status == MergeStateStatusDirty
}
func isImmediatelyMergeable(status string) bool {
switch status {
case MergeStateStatusClean, MergeStateStatusHasHooks, MergeStateStatusUnstable:
return true
default:
return false
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/merge/merge_test.go | pkg/cmd/pr/merge/merge_test.go | package merge
import (
"bytes"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/context"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/prompter"
"github.com/cli/cli/v2/internal/run"
"github.com/cli/cli/v2/pkg/cmd/pr/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/test"
ghapi "github.com/cli/go-gh/v2/pkg/api"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_NewCmdMerge(t *testing.T) {
tmpFile := filepath.Join(t.TempDir(), "my-body.md")
err := os.WriteFile(tmpFile, []byte("a body from file"), 0600)
require.NoError(t, err)
tests := []struct {
name string
args string
stdin string
isTTY bool
want MergeOptions
wantErr string
}{
{
name: "number argument",
args: "123",
isTTY: true,
want: MergeOptions{
SelectorArg: "123",
DeleteBranch: false,
IsDeleteBranchIndicated: false,
CanDeleteLocalBranch: true,
MergeMethod: PullRequestMergeMethodMerge,
MergeStrategyEmpty: true,
Body: "",
BodySet: false,
AuthorEmail: "",
},
},
{
name: "delete-branch specified",
args: "--delete-branch=false",
isTTY: true,
want: MergeOptions{
SelectorArg: "",
DeleteBranch: false,
IsDeleteBranchIndicated: true,
CanDeleteLocalBranch: true,
MergeMethod: PullRequestMergeMethodMerge,
MergeStrategyEmpty: true,
Body: "",
BodySet: false,
AuthorEmail: "",
},
},
{
name: "body from file",
args: fmt.Sprintf("123 --body-file '%s'", tmpFile),
isTTY: true,
want: MergeOptions{
SelectorArg: "123",
DeleteBranch: false,
IsDeleteBranchIndicated: false,
CanDeleteLocalBranch: true,
MergeMethod: PullRequestMergeMethodMerge,
MergeStrategyEmpty: true,
Body: "a body from file",
BodySet: true,
AuthorEmail: "",
},
},
{
name: "body from stdin",
args: "123 --body-file -",
stdin: "this is on standard input",
isTTY: true,
want: MergeOptions{
SelectorArg: "123",
DeleteBranch: false,
IsDeleteBranchIndicated: false,
CanDeleteLocalBranch: true,
MergeMethod: PullRequestMergeMethodMerge,
MergeStrategyEmpty: true,
Body: "this is on standard input",
BodySet: true,
AuthorEmail: "",
},
},
{
name: "body",
args: "123 -bcool",
isTTY: true,
want: MergeOptions{
SelectorArg: "123",
DeleteBranch: false,
IsDeleteBranchIndicated: false,
CanDeleteLocalBranch: true,
MergeMethod: PullRequestMergeMethodMerge,
MergeStrategyEmpty: true,
Body: "cool",
BodySet: true,
AuthorEmail: "",
},
},
{
name: "match-head-commit specified",
args: "123 --match-head-commit 555",
isTTY: true,
want: MergeOptions{
SelectorArg: "123",
DeleteBranch: false,
IsDeleteBranchIndicated: false,
CanDeleteLocalBranch: true,
MergeMethod: PullRequestMergeMethodMerge,
MergeStrategyEmpty: true,
Body: "",
BodySet: false,
MatchHeadCommit: "555",
AuthorEmail: "",
},
},
{
name: "author email",
args: "123 --author-email octocat@github.com",
isTTY: true,
want: MergeOptions{
SelectorArg: "123",
DeleteBranch: false,
IsDeleteBranchIndicated: false,
CanDeleteLocalBranch: true,
MergeMethod: PullRequestMergeMethodMerge,
MergeStrategyEmpty: true,
Body: "",
BodySet: false,
AuthorEmail: "octocat@github.com",
},
},
{
name: "body and body-file flags",
args: "123 --body 'test' --body-file 'test-file.txt'",
isTTY: true,
wantErr: "specify only one of `--body` or `--body-file`",
},
{
name: "no argument with --repo override",
args: "-R owner/repo",
isTTY: true,
wantErr: "argument required when using the --repo flag",
},
{
name: "multiple merge methods",
args: "123 --merge --rebase",
isTTY: true,
wantErr: "only one of --merge, --rebase, or --squash can be enabled",
},
{
name: "multiple merge methods, non-tty",
args: "123 --merge --rebase",
isTTY: false,
wantErr: "only one of --merge, --rebase, or --squash can be enabled",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, stdin, _, _ := iostreams.Test()
ios.SetStdoutTTY(tt.isTTY)
ios.SetStdinTTY(tt.isTTY)
ios.SetStderrTTY(tt.isTTY)
if tt.stdin != "" {
_, _ = stdin.WriteString(tt.stdin)
}
f := &cmdutil.Factory{
IOStreams: ios,
}
var opts *MergeOptions
cmd := NewCmdMerge(f, func(o *MergeOptions) error {
opts = o
return nil
})
cmd.PersistentFlags().StringP("repo", "R", "", "")
argv, err := shlex.Split(tt.args)
require.NoError(t, err)
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
_, err = cmd.ExecuteC()
if tt.wantErr != "" {
require.EqualError(t, err, tt.wantErr)
return
} else {
require.NoError(t, err)
}
assert.Equal(t, tt.want.SelectorArg, opts.SelectorArg)
assert.Equal(t, tt.want.DeleteBranch, opts.DeleteBranch)
assert.Equal(t, tt.want.CanDeleteLocalBranch, opts.CanDeleteLocalBranch)
assert.Equal(t, tt.want.MergeMethod, opts.MergeMethod)
assert.Equal(t, tt.want.MergeStrategyEmpty, opts.MergeStrategyEmpty)
assert.Equal(t, tt.want.Body, opts.Body)
assert.Equal(t, tt.want.BodySet, opts.BodySet)
assert.Equal(t, tt.want.MatchHeadCommit, opts.MatchHeadCommit)
assert.Equal(t, tt.want.AuthorEmail, opts.AuthorEmail)
})
}
}
func baseRepo(owner, repo, branch string) ghrepo.Interface {
return api.InitRepoHostname(&api.Repository{
Name: repo,
Owner: api.RepositoryOwner{Login: owner},
DefaultBranchRef: api.BranchRef{Name: branch},
}, "github.com")
}
func stubCommit(pr *api.PullRequest, oid string) {
pr.Commits.Nodes = append(pr.Commits.Nodes, api.PullRequestCommit{
Commit: api.PullRequestCommitCommit{OID: oid},
})
}
// TODO port to new style tests
func runCommand(rt http.RoundTripper, pm *prompter.PrompterMock, branch string, isTTY bool, cli string) (*test.CmdOut, error) {
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdoutTTY(isTTY)
ios.SetStdinTTY(isTTY)
ios.SetStderrTTY(isTTY)
factory := &cmdutil.Factory{
IOStreams: ios,
HttpClient: func() (*http.Client, error) {
return &http.Client{Transport: rt}, nil
},
Branch: func() (string, error) {
return branch, nil
},
Remotes: func() (context.Remotes, error) {
return []*context.Remote{
{
Remote: &git.Remote{
Name: "origin",
},
Repo: ghrepo.New("OWNER", "REPO"),
},
}, nil
},
GitClient: &git.Client{
GhPath: "some/path/gh",
GitPath: "some/path/git",
},
Prompter: pm,
}
cmd := NewCmdMerge(factory, nil)
cmd.PersistentFlags().StringP("repo", "R", "", "")
cli = strings.TrimPrefix(cli, "pr merge")
argv, err := shlex.Split(cli)
if err != nil {
return nil, err
}
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
_, err = cmd.ExecuteC()
return &test.CmdOut{
OutBuf: stdout,
ErrBuf: stderr,
}, err
}
func initFakeHTTP() *httpmock.Registry {
return &httpmock.Registry{}
}
func TestPrMerge(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t,
"1",
&api.PullRequest{
ID: "THE-ID",
Number: 1,
State: "OPEN",
Title: "The title of the PR",
MergeStateStatus: "CLEAN",
},
baseRepo("OWNER", "REPO", "main"),
)
http.Register(
httpmock.GraphQL(`mutation PullRequestMerge\b`),
httpmock.GraphQLMutation(`{}`, func(input map[string]interface{}) {
assert.Equal(t, "THE-ID", input["pullRequestId"].(string))
assert.Equal(t, "MERGE", input["mergeMethod"].(string))
assert.NotContains(t, input, "commitHeadline")
}),
)
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git rev-parse --verify refs/heads/`, 0, "")
output, err := runCommand(http, nil, "main", true, "pr merge 1 --merge")
if err != nil {
t.Fatalf("error running command `pr merge`: %v", err)
}
r := regexp.MustCompile(`Merged pull request OWNER/REPO#1 \(The title of the PR\)`)
if !r.MatchString(output.Stderr()) {
t.Fatalf("output did not match regexp /%s/\n> output\n%q\n", r, output.Stderr())
}
}
func TestPrMerge_blocked(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t,
"1",
&api.PullRequest{
ID: "THE-ID",
Number: 1,
State: "OPEN",
Title: "The title of the PR",
MergeStateStatus: "BLOCKED",
},
baseRepo("OWNER", "REPO", "main"),
)
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git rev-parse --verify refs/heads/`, 0, "")
output, err := runCommand(http, nil, "main", true, "pr merge 1 --merge")
assert.EqualError(t, err, "SilentError")
assert.Equal(t, "", output.String())
assert.Equal(t, heredoc.Docf(`
X Pull request OWNER/REPO#1 is not mergeable: the base branch policy prohibits the merge.
To have the pull request merged after all the requirements have been met, add the %[1]s--auto%[1]s flag.
To use administrator privileges to immediately merge the pull request, add the %[1]s--admin%[1]s flag.
`, "`"), output.Stderr())
}
func TestPrMerge_dirty(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t,
"1",
&api.PullRequest{
ID: "THE-ID",
Number: 123,
State: "OPEN",
Title: "The title of the PR",
MergeStateStatus: "DIRTY",
BaseRefName: "trunk",
HeadRefName: "feature",
},
baseRepo("OWNER", "REPO", "main"),
)
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git rev-parse --verify refs/heads/`, 0, "")
output, err := runCommand(http, nil, "main", true, "pr merge 1 --merge")
assert.EqualError(t, err, "SilentError")
assert.Equal(t, "", output.String())
assert.Equal(t, heredoc.Docf(`
X Pull request OWNER/REPO#123 is not mergeable: the merge commit cannot be cleanly created.
To have the pull request merged after all the requirements have been met, add the %[1]s--auto%[1]s flag.
Run the following to resolve the merge conflicts locally:
gh pr checkout 123 && git fetch origin trunk && git merge origin/trunk
`, "`"), output.Stderr())
}
func TestPrMerge_nontty(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t,
"1",
&api.PullRequest{
ID: "THE-ID",
Number: 1,
State: "OPEN",
Title: "The title of the PR",
MergeStateStatus: "CLEAN",
},
baseRepo("OWNER", "REPO", "main"),
)
http.Register(
httpmock.GraphQL(`mutation PullRequestMerge\b`),
httpmock.GraphQLMutation(`{}`, func(input map[string]interface{}) {
assert.Equal(t, "THE-ID", input["pullRequestId"].(string))
assert.Equal(t, "MERGE", input["mergeMethod"].(string))
assert.NotContains(t, input, "commitHeadline")
}))
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git rev-parse --verify refs/heads/`, 0, "")
output, err := runCommand(http, nil, "main", false, "pr merge 1 --merge")
if err != nil {
t.Fatalf("error running command `pr merge`: %v", err)
}
assert.Equal(t, "", output.String())
assert.Equal(t, "", output.Stderr())
}
func TestPrMerge_editMessage_nontty(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t,
"1",
&api.PullRequest{
ID: "THE-ID",
Number: 1,
State: "OPEN",
Title: "The title of the PR",
MergeStateStatus: "CLEAN",
},
baseRepo("OWNER", "REPO", "main"),
)
http.Register(
httpmock.GraphQL(`mutation PullRequestMerge\b`),
httpmock.GraphQLMutation(`{}`, func(input map[string]interface{}) {
assert.Equal(t, "THE-ID", input["pullRequestId"].(string))
assert.Equal(t, "MERGE", input["mergeMethod"].(string))
assert.Equal(t, "mytitle", input["commitHeadline"].(string))
assert.Equal(t, "mybody", input["commitBody"].(string))
}))
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git rev-parse --verify refs/heads/`, 0, "")
output, err := runCommand(http, nil, "main", false, "pr merge 1 --merge -t mytitle -b mybody")
if err != nil {
t.Fatalf("error running command `pr merge`: %v", err)
}
assert.Equal(t, "", output.String())
assert.Equal(t, "", output.Stderr())
}
func TestPrMerge_withRepoFlag(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t,
"1",
&api.PullRequest{
ID: "THE-ID",
Number: 1,
State: "OPEN",
Title: "The title of the PR",
MergeStateStatus: "CLEAN",
},
baseRepo("OWNER", "REPO", "main"),
)
http.Register(
httpmock.GraphQL(`mutation PullRequestMerge\b`),
httpmock.GraphQLMutation(`{}`, func(input map[string]interface{}) {
assert.Equal(t, "THE-ID", input["pullRequestId"].(string))
assert.Equal(t, "MERGE", input["mergeMethod"].(string))
assert.NotContains(t, input, "commitHeadline")
}))
_, cmdTeardown := run.Stub()
defer cmdTeardown(t)
output, err := runCommand(http, nil, "main", true, "pr merge 1 --merge -R OWNER/REPO")
if err != nil {
t.Fatalf("error running command `pr merge`: %v", err)
}
r := regexp.MustCompile(`Merged pull request OWNER/REPO#1 \(The title of the PR\)`)
if !r.MatchString(output.Stderr()) {
t.Fatalf("output did not match regexp /%s/\n> output\n%q\n", r, output.Stderr())
}
}
func TestPrMerge_withMatchCommitHeadFlag(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t,
"1",
&api.PullRequest{
ID: "THE-ID",
Number: 1,
State: "OPEN",
Title: "The title of the PR",
MergeStateStatus: "CLEAN",
},
baseRepo("OWNER", "REPO", "main"),
)
http.Register(
httpmock.GraphQL(`mutation PullRequestMerge\b`),
httpmock.GraphQLMutation(`{}`, func(input map[string]interface{}) {
assert.Equal(t, 3, len(input))
assert.Equal(t, "THE-ID", input["pullRequestId"].(string))
assert.Equal(t, "MERGE", input["mergeMethod"].(string))
assert.Equal(t, "285ed5ab740f53ff6b0b4b629c59a9df23b9c6db", input["expectedHeadOid"].(string))
}))
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git rev-parse --verify refs/heads/`, 0, "")
output, err := runCommand(http, nil, "main", true, "pr merge 1 --merge --match-head-commit 285ed5ab740f53ff6b0b4b629c59a9df23b9c6db")
if err != nil {
t.Fatalf("error running command `pr merge`: %v", err)
}
r := regexp.MustCompile(`Merged pull request OWNER/REPO#1 \(The title of the PR\)`)
if !r.MatchString(output.Stderr()) {
t.Fatalf("output did not match regexp /%s/\n> output\n%q\n", r, output.Stderr())
}
}
func TestPrMerge_withAuthorFlag(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t,
"1",
&api.PullRequest{
ID: "THE-ID",
Number: 1,
State: "OPEN",
Title: "The title of the PR",
MergeStateStatus: "CLEAN",
},
baseRepo("OWNER", "REPO", "main"),
)
http.Register(
httpmock.GraphQL(`mutation PullRequestMerge\b`),
httpmock.GraphQLMutation(`{}`, func(input map[string]interface{}) {
assert.Equal(t, "THE-ID", input["pullRequestId"].(string))
assert.Equal(t, "MERGE", input["mergeMethod"].(string))
assert.Equal(t, "octocat@github.com", input["authorEmail"].(string))
assert.NotContains(t, input, "commitHeadline")
}),
)
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git rev-parse --verify refs/heads/`, 0, "")
output, err := runCommand(http, nil, "main", true, "pr merge 1 --merge --author-email octocat@github.com")
if err != nil {
t.Fatalf("error running command `pr merge`: %v", err)
}
r := regexp.MustCompile(`Merged pull request OWNER/REPO#1 \(The title of the PR\)`)
if !r.MatchString(output.Stderr()) {
t.Fatalf("output did not match regexp /%s/\n> output\n%q\n", r, output.Stderr())
}
}
func TestPrMerge_deleteBranch(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t,
"",
&api.PullRequest{
ID: "PR_10",
Number: 10,
State: "OPEN",
Title: "Blueberries are a good fruit",
HeadRefName: "blueberries",
BaseRefName: "main",
MergeStateStatus: "CLEAN",
},
baseRepo("OWNER", "REPO", "main"),
)
http.Register(
httpmock.GraphQL(`mutation PullRequestMerge\b`),
httpmock.GraphQLMutation(`{}`, func(input map[string]interface{}) {
assert.Equal(t, "PR_10", input["pullRequestId"].(string))
assert.Equal(t, "MERGE", input["mergeMethod"].(string))
assert.NotContains(t, input, "commitHeadline")
}))
http.Register(
httpmock.REST("DELETE", "repos/OWNER/REPO/git/refs/heads/blueberries"),
httpmock.StringResponse(`{}`))
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git rev-parse --verify refs/heads/main`, 0, "")
cs.Register(`git checkout main`, 0, "")
cs.Register(`git rev-parse --verify refs/heads/blueberries`, 0, "")
cs.Register(`git branch -D blueberries`, 0, "")
cs.Register(`git pull --ff-only`, 0, "")
output, err := runCommand(http, nil, "blueberries", true, `pr merge --merge --delete-branch`)
if err != nil {
t.Fatalf("Got unexpected error running `pr merge` %s", err)
}
assert.Equal(t, "", output.String())
assert.Equal(t, heredoc.Doc(`
β Merged pull request OWNER/REPO#10 (Blueberries are a good fruit)
β Deleted local branch blueberries and switched to branch main
β Deleted remote branch blueberries
`), output.Stderr())
}
func TestPrMerge_deleteBranch_apiError(t *testing.T) {
tests := []struct {
name string
apiError ghapi.HTTPError
wantErr string
wantStderr string
}{
{
name: "branch already deleted (422: Reference does not exist)",
apiError: ghapi.HTTPError{
Message: "Reference does not exist",
StatusCode: http.StatusUnprocessableEntity, // 422
},
wantStderr: heredoc.Doc(`
β Merged pull request OWNER/REPO#10 (Blueberries are a good fruit)
β Deleted local branch blueberries and switched to branch main
β Deleted remote branch blueberries
`),
},
{
name: "branch already deleted (404: Reference does not exist) (#11187)",
apiError: ghapi.HTTPError{
Message: "Reference does not exist",
StatusCode: http.StatusNotFound, // 404
},
wantStderr: heredoc.Doc(`
β Merged pull request OWNER/REPO#10 (Blueberries are a good fruit)
β Deleted local branch blueberries and switched to branch main
β Deleted remote branch blueberries
`),
},
{
name: "unknown API error",
apiError: ghapi.HTTPError{
Message: "blah blah",
StatusCode: http.StatusInternalServerError, // 500
},
wantStderr: heredoc.Doc(`
β Merged pull request OWNER/REPO#10 (Blueberries are a good fruit)
β Deleted local branch blueberries and switched to branch main
`),
wantErr: "failed to delete remote branch blueberries: HTTP 500: blah blah (https://api.github.com/repos/OWNER/REPO/git/refs/heads/blueberries)",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t,
"",
&api.PullRequest{
ID: "PR_10",
Number: 10,
State: "OPEN",
Title: "Blueberries are a good fruit",
HeadRefName: "blueberries",
BaseRefName: "main",
MergeStateStatus: "CLEAN",
},
baseRepo("OWNER", "REPO", "main"),
)
http.Register(
httpmock.GraphQL(`mutation PullRequestMerge\b`),
httpmock.GraphQLMutation(`{}`, func(input map[string]interface{}) {
assert.Equal(t, "PR_10", input["pullRequestId"].(string))
assert.Equal(t, "MERGE", input["mergeMethod"].(string))
assert.NotContains(t, input, "commitHeadline")
}))
http.Register(
httpmock.REST("DELETE", "repos/OWNER/REPO/git/refs/heads/blueberries"),
httpmock.JSONErrorResponse(tt.apiError.StatusCode, tt.apiError))
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git rev-parse --verify refs/heads/main`, 0, "")
cs.Register(`git checkout main`, 0, "")
cs.Register(`git rev-parse --verify refs/heads/blueberries`, 0, "")
cs.Register(`git branch -D blueberries`, 0, "")
cs.Register(`git pull --ff-only`, 0, "")
output, err := runCommand(http, nil, "blueberries", true, `pr merge --merge --delete-branch`)
assert.Equal(t, "", output.String())
assert.Equal(t, tt.wantStderr, output.Stderr())
if tt.wantErr != "" {
assert.EqualError(t, err, tt.wantErr)
return
}
assert.NoError(t, err)
})
}
}
func TestPrMerge_deleteBranch_mergeQueue(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t,
"",
&api.PullRequest{
ID: "PR_10",
Number: 10,
State: "OPEN",
Title: "Blueberries are a good fruit",
HeadRefName: "blueberries",
BaseRefName: "main",
MergeStateStatus: "CLEAN",
IsMergeQueueEnabled: true,
},
baseRepo("OWNER", "REPO", "main"),
)
_, err := runCommand(http, nil, "blueberries", true, `pr merge --merge --delete-branch`)
assert.Contains(t, err.Error(), "X Cannot use `-d` or `--delete-branch` when merge queue enabled")
}
func TestPrMerge_deleteBranch_nonDefault(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t,
"",
&api.PullRequest{
ID: "PR_10",
Number: 10,
State: "OPEN",
Title: "Blueberries are a good fruit",
HeadRefName: "blueberries",
MergeStateStatus: "CLEAN",
BaseRefName: "fruit",
},
baseRepo("OWNER", "REPO", "main"),
)
http.Register(
httpmock.GraphQL(`mutation PullRequestMerge\b`),
httpmock.GraphQLMutation(`{}`, func(input map[string]interface{}) {
assert.Equal(t, "PR_10", input["pullRequestId"].(string))
assert.Equal(t, "MERGE", input["mergeMethod"].(string))
assert.NotContains(t, input, "commitHeadline")
}))
http.Register(
httpmock.REST("DELETE", "repos/OWNER/REPO/git/refs/heads/blueberries"),
httpmock.StringResponse(`{}`))
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git rev-parse --verify refs/heads/fruit`, 0, "")
cs.Register(`git checkout fruit`, 0, "")
cs.Register(`git rev-parse --verify refs/heads/blueberries`, 0, "")
cs.Register(`git branch -D blueberries`, 0, "")
cs.Register(`git pull --ff-only`, 0, "")
output, err := runCommand(http, nil, "blueberries", true, `pr merge --merge --delete-branch`)
if err != nil {
t.Fatalf("Got unexpected error running `pr merge` %s", err)
}
assert.Equal(t, "", output.String())
assert.Equal(t, heredoc.Doc(`
β Merged pull request OWNER/REPO#10 (Blueberries are a good fruit)
β Deleted local branch blueberries and switched to branch fruit
β Deleted remote branch blueberries
`), output.Stderr())
}
func TestPrMerge_deleteBranch_onlyLocally(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t,
"",
&api.PullRequest{
ID: "PR_10",
Number: 10,
State: "OPEN",
Title: "Blueberries are a good fruit",
HeadRefName: "blueberries",
BaseRefName: "main",
MergeStateStatus: "CLEAN",
HeadRepositoryOwner: api.Owner{Login: "HEAD"}, // Not the same owner as the base repo
},
baseRepo("OWNER", "REPO", "main"),
)
http.Register(
httpmock.GraphQL(`mutation PullRequestMerge\b`),
httpmock.GraphQLMutation(`{}`, func(input map[string]interface{}) {
assert.Equal(t, "PR_10", input["pullRequestId"].(string))
assert.Equal(t, "MERGE", input["mergeMethod"].(string))
assert.NotContains(t, input, "commitHeadline")
}))
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git rev-parse --verify refs/heads/main`, 0, "")
cs.Register(`git checkout main`, 0, "")
cs.Register(`git rev-parse --verify refs/heads/blueberries`, 0, "")
cs.Register(`git branch -D blueberries`, 0, "")
cs.Register(`git pull --ff-only`, 0, "")
output, err := runCommand(http, nil, "blueberries", true, `pr merge --merge --delete-branch`)
if err != nil {
t.Fatalf("Got unexpected error running `pr merge` %s", err)
}
assert.Equal(t, "", output.String())
assert.Equal(t, heredoc.Doc(`
β Merged pull request OWNER/REPO#10 (Blueberries are a good fruit)
β Deleted local branch blueberries and switched to branch main
`), output.Stderr())
}
func TestPrMerge_deleteBranch_checkoutNewBranch(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t,
"",
&api.PullRequest{
ID: "PR_10",
Number: 10,
State: "OPEN",
Title: "Blueberries are a good fruit",
HeadRefName: "blueberries",
MergeStateStatus: "CLEAN",
BaseRefName: "fruit",
},
baseRepo("OWNER", "REPO", "main"),
)
http.Register(
httpmock.GraphQL(`mutation PullRequestMerge\b`),
httpmock.GraphQLMutation(`{}`, func(input map[string]interface{}) {
assert.Equal(t, "PR_10", input["pullRequestId"].(string))
assert.Equal(t, "MERGE", input["mergeMethod"].(string))
assert.NotContains(t, input, "commitHeadline")
}))
http.Register(
httpmock.REST("DELETE", "repos/OWNER/REPO/git/refs/heads/blueberries"),
httpmock.StringResponse(`{}`))
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git rev-parse --verify refs/heads/fruit`, 1, "")
cs.Register(`git checkout -b fruit --track origin/fruit`, 0, "")
cs.Register(`git rev-parse --verify refs/heads/blueberries`, 0, "")
cs.Register(`git branch -D blueberries`, 0, "")
cs.Register(`git pull --ff-only`, 0, "")
output, err := runCommand(http, nil, "blueberries", true, `pr merge --merge --delete-branch`)
if err != nil {
t.Fatalf("Got unexpected error running `pr merge` %s", err)
}
assert.Equal(t, "", output.String())
assert.Equal(t, heredoc.Doc(`
β Merged pull request OWNER/REPO#10 (Blueberries are a good fruit)
β Deleted local branch blueberries and switched to branch fruit
β Deleted remote branch blueberries
`), output.Stderr())
}
func TestPrMerge_deleteNonCurrentBranch(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t,
"blueberries",
&api.PullRequest{
ID: "PR_10",
Number: 10,
State: "OPEN",
Title: "Blueberries are a good fruit",
HeadRefName: "blueberries",
MergeStateStatus: "CLEAN",
},
baseRepo("OWNER", "REPO", "main"),
)
http.Register(
httpmock.GraphQL(`mutation PullRequestMerge\b`),
httpmock.GraphQLMutation(`{}`, func(input map[string]interface{}) {
assert.Equal(t, "PR_10", input["pullRequestId"].(string))
assert.Equal(t, "MERGE", input["mergeMethod"].(string))
assert.NotContains(t, input, "commitHeadline")
}))
http.Register(
httpmock.REST("DELETE", "repos/OWNER/REPO/git/refs/heads/blueberries"),
httpmock.StringResponse(`{}`))
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git rev-parse --verify refs/heads/blueberries`, 0, "")
cs.Register(`git branch -D blueberries`, 0, "")
output, err := runCommand(http, nil, "main", true, `pr merge --merge --delete-branch blueberries`)
if err != nil {
t.Fatalf("Got unexpected error running `pr merge` %s", err)
}
assert.Equal(t, "", output.String())
assert.Equal(t, heredoc.Doc(`
β Merged pull request OWNER/REPO#10 (Blueberries are a good fruit)
β Deleted local branch blueberries
β Deleted remote branch blueberries
`), output.Stderr())
}
func Test_nonDivergingPullRequest(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
pr := &api.PullRequest{
ID: "PR_10",
Number: 10,
Title: "Blueberries are a good fruit",
State: "OPEN",
MergeStateStatus: "CLEAN",
BaseRefName: "main",
}
stubCommit(pr, "COMMITSHA1")
shared.StubFinderForRunCommandStyleTests(t, "", pr, baseRepo("OWNER", "REPO", "main"))
http.Register(
httpmock.GraphQL(`mutation PullRequestMerge\b`),
httpmock.GraphQLMutation(`{}`, func(input map[string]interface{}) {
assert.Equal(t, "PR_10", input["pullRequestId"].(string))
assert.Equal(t, "MERGE", input["mergeMethod"].(string))
assert.NotContains(t, input, "commitHeadline")
}))
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git .+ show .+ HEAD`, 0, "COMMITSHA1,title")
cs.Register(`git rev-parse --verify refs/heads/`, 0, "")
output, err := runCommand(http, nil, "blueberries", true, "pr merge --merge")
if err != nil {
t.Fatalf("error running command `pr merge`: %v", err)
}
assert.Equal(t, heredoc.Doc(`
β Merged pull request OWNER/REPO#10 (Blueberries are a good fruit)
`), output.Stderr())
}
func Test_divergingPullRequestWarning(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
pr := &api.PullRequest{
ID: "PR_10",
Number: 10,
Title: "Blueberries are a good fruit",
State: "OPEN",
MergeStateStatus: "CLEAN",
BaseRefName: "main",
}
stubCommit(pr, "COMMITSHA1")
shared.StubFinderForRunCommandStyleTests(t, "", pr, baseRepo("OWNER", "REPO", "main"))
http.Register(
httpmock.GraphQL(`mutation PullRequestMerge\b`),
httpmock.GraphQLMutation(`{}`, func(input map[string]interface{}) {
assert.Equal(t, "PR_10", input["pullRequestId"].(string))
assert.Equal(t, "MERGE", input["mergeMethod"].(string))
assert.NotContains(t, input, "commitHeadline")
}))
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git .+ show .+ HEAD`, 0, "COMMITSHA2,title")
cs.Register(`git rev-parse --verify refs/heads/`, 0, "")
output, err := runCommand(http, nil, "blueberries", true, "pr merge --merge")
if err != nil {
t.Fatalf("error running command `pr merge`: %v", err)
}
assert.Equal(t, heredoc.Doc(`
! Pull request OWNER/REPO#10 (Blueberries are a good fruit) has diverged from local branch
β Merged pull request OWNER/REPO#10 (Blueberries are a good fruit)
`), output.Stderr())
}
func Test_pullRequestWithoutCommits(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t,
"",
&api.PullRequest{
ID: "PR_10",
Number: 10,
Title: "Blueberries are a good fruit",
State: "OPEN",
MergeStateStatus: "CLEAN",
},
baseRepo("OWNER", "REPO", "main"),
)
http.Register(
httpmock.GraphQL(`mutation PullRequestMerge\b`),
httpmock.GraphQLMutation(`{}`, func(input map[string]interface{}) {
assert.Equal(t, "PR_10", input["pullRequestId"].(string))
assert.Equal(t, "MERGE", input["mergeMethod"].(string))
assert.NotContains(t, input, "commitHeadline")
}))
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git rev-parse --verify refs/heads/`, 0, "")
output, err := runCommand(http, nil, "blueberries", true, "pr merge --merge")
if err != nil {
t.Fatalf("error running command `pr merge`: %v", err)
}
assert.Equal(t, heredoc.Doc(`
β Merged pull request OWNER/REPO#10 (Blueberries are a good fruit)
`), output.Stderr())
}
func TestPrMerge_rebase(t *testing.T) {
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | true |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/merge/http.go | pkg/cmd/pr/merge/http.go | package merge
import (
"net/http"
"strings"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/shurcooL/githubv4"
)
type PullRequestMergeMethod int
const (
PullRequestMergeMethodMerge PullRequestMergeMethod = iota
PullRequestMergeMethodRebase
PullRequestMergeMethodSquash
)
const (
MergeStateStatusBehind = "BEHIND"
MergeStateStatusBlocked = "BLOCKED"
MergeStateStatusClean = "CLEAN"
MergeStateStatusDirty = "DIRTY"
MergeStateStatusHasHooks = "HAS_HOOKS"
MergeStateStatusMerged = "MERGED"
MergeStateStatusUnstable = "UNSTABLE"
)
type mergePayload struct {
repo ghrepo.Interface
pullRequestID string
method PullRequestMergeMethod
auto bool
commitSubject string
commitBody string
setCommitBody bool
expectedHeadOid string
authorEmail string
}
// TODO: drop after githubv4 gets updated
type EnablePullRequestAutoMergeInput struct {
githubv4.MergePullRequestInput
}
func mergePullRequest(client *http.Client, payload mergePayload) error {
input := githubv4.MergePullRequestInput{
PullRequestID: githubv4.ID(payload.pullRequestID),
}
switch payload.method {
case PullRequestMergeMethodMerge:
m := githubv4.PullRequestMergeMethodMerge
input.MergeMethod = &m
case PullRequestMergeMethodRebase:
m := githubv4.PullRequestMergeMethodRebase
input.MergeMethod = &m
case PullRequestMergeMethodSquash:
m := githubv4.PullRequestMergeMethodSquash
input.MergeMethod = &m
}
if payload.authorEmail != "" {
authorEmail := githubv4.String(payload.authorEmail)
input.AuthorEmail = &authorEmail
}
if payload.commitSubject != "" {
commitHeadline := githubv4.String(payload.commitSubject)
input.CommitHeadline = &commitHeadline
}
if payload.setCommitBody {
commitBody := githubv4.String(payload.commitBody)
input.CommitBody = &commitBody
}
if payload.expectedHeadOid != "" {
expectedHeadOid := githubv4.GitObjectID(payload.expectedHeadOid)
input.ExpectedHeadOid = &expectedHeadOid
}
variables := map[string]interface{}{
"input": input,
}
gql := api.NewClientFromHTTP(client)
if payload.auto {
var mutation struct {
EnablePullRequestAutoMerge struct {
ClientMutationId string
} `graphql:"enablePullRequestAutoMerge(input: $input)"`
}
variables["input"] = EnablePullRequestAutoMergeInput{input}
return gql.Mutate(payload.repo.RepoHost(), "PullRequestAutoMerge", &mutation, variables)
}
var mutation struct {
MergePullRequest struct {
ClientMutationId string
} `graphql:"mergePullRequest(input: $input)"`
}
return gql.Mutate(payload.repo.RepoHost(), "PullRequestMerge", &mutation, variables)
}
func disableAutoMerge(client *http.Client, repo ghrepo.Interface, prID string) error {
var mutation struct {
DisablePullRequestAutoMerge struct {
ClientMutationId string
} `graphql:"disablePullRequestAutoMerge(input: {pullRequestId: $prID})"`
}
variables := map[string]interface{}{
"prID": githubv4.ID(prID),
}
gql := api.NewClientFromHTTP(client)
return gql.Mutate(repo.RepoHost(), "PullRequestAutoMergeDisable", &mutation, variables)
}
func getMergeText(client *http.Client, repo ghrepo.Interface, prID string, mergeMethod PullRequestMergeMethod) (string, string, error) {
var method githubv4.PullRequestMergeMethod
switch mergeMethod {
case PullRequestMergeMethodMerge:
method = githubv4.PullRequestMergeMethodMerge
case PullRequestMergeMethodRebase:
method = githubv4.PullRequestMergeMethodRebase
case PullRequestMergeMethodSquash:
method = githubv4.PullRequestMergeMethodSquash
}
var query struct {
Node struct {
PullRequest struct {
ViewerMergeHeadlineText string `graphql:"viewerMergeHeadlineText(mergeType: $method)"`
ViewerMergeBodyText string `graphql:"viewerMergeBodyText(mergeType: $method)"`
} `graphql:"...on PullRequest"`
} `graphql:"node(id: $prID)"`
}
variables := map[string]interface{}{
"prID": githubv4.ID(prID),
"method": method,
}
gql := api.NewClientFromHTTP(client)
err := gql.Query(repo.RepoHost(), "PullRequestMergeText", &query, variables)
if err != nil {
// Tolerate this API missing in older GitHub Enterprise
if strings.Contains(err.Error(), "Field 'viewerMergeHeadlineText' doesn't exist") ||
strings.Contains(err.Error(), "Field 'viewerMergeBodyText' doesn't exist") {
return "", "", nil
}
return "", "", err
}
return query.Node.PullRequest.ViewerMergeHeadlineText, query.Node.PullRequest.ViewerMergeBodyText, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/shared/find_refs_resolution.go | pkg/cmd/pr/shared/find_refs_resolution.go | package shared
import (
"context"
"fmt"
"net/url"
"strings"
ghContext "github.com/cli/cli/v2/context"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/ghrepo"
o "github.com/cli/cli/v2/pkg/option"
)
// QualifiedHeadRef represents a git branch with an optional owner, used
// for the head of a pull request. For example, within a single repository,
// we would expect a PR to have a head ref of no owner, and a branch name.
// However, for cross-repository pull requests, we would expect a head ref
// with an owner and a branch name. In string form this is represented as
// <owner>:<branch>. The GitHub API is able to interpret this format in order
// to discover the correct fork repository.
//
// In other parts of the code, you may see this refered to as a HeadLabel.
type QualifiedHeadRef struct {
owner o.Option[string]
branchName string
}
// NewQualifiedHeadRef creates a QualifiedHeadRef. If the empty string is provided
// for the owner, it will be treated as None.
func NewQualifiedHeadRef(owner string, branchName string) QualifiedHeadRef {
return QualifiedHeadRef{
owner: o.SomeIfNonZero(owner),
branchName: branchName,
}
}
func NewQualifiedHeadRefWithoutOwner(branchName string) QualifiedHeadRef {
return QualifiedHeadRef{
owner: o.None[string](),
branchName: branchName,
}
}
// ParseQualifiedHeadRef takes strings of the form <owner>:<branch> or <branch>
// and returns a QualifiedHeadRef. If the form <owner>:<branch> is used,
// the owner is set to the value of <owner>, and the branch name is set to
// the value of <branch>. If the form <branch> is used, the owner is set to
// None, and the branch name is set to the value of <branch>.
//
// This does no further error checking about the validity of a ref, so
// it is not safe to assume the ref is truly a valid ref, e.g. "my~bad:ref?"
// is going to result in a nonsense result.
func ParseQualifiedHeadRef(ref string) (QualifiedHeadRef, error) {
if !strings.Contains(ref, ":") {
return NewQualifiedHeadRefWithoutOwner(ref), nil
}
parts := strings.Split(ref, ":")
if len(parts) != 2 {
return QualifiedHeadRef{}, fmt.Errorf("invalid qualified head ref format '%s'", ref)
}
return NewQualifiedHeadRef(parts[0], parts[1]), nil
}
// A QualifiedHeadRef without an owner returns <branch>, while a QualifiedHeadRef
// with an owner returns <owner>:<branch>.
func (r QualifiedHeadRef) String() string {
if owner, present := r.owner.Value(); present {
return fmt.Sprintf("%s:%s", owner, r.branchName)
}
return r.branchName
}
func (r QualifiedHeadRef) BranchName() string {
return r.branchName
}
// PRFindRefs represents the necessary data to find a pull request from the API.
type PRFindRefs struct {
qualifiedHeadRef QualifiedHeadRef
baseRepo ghrepo.Interface
// baseBranchName is an optional branch name, because it is not required for
// finding a pull request, only for disambiguation if multiple pull requests
// contain the same head ref.
baseBranchName o.Option[string]
}
// QualifiedHeadRef returns a stringified form of the head ref, varying depending
// on whether the head ref is in the same repository as the base ref. If they are
// the same repository, we return the branch name only. If they are different repositories,
// we return the owner and branch name in the form <owner>:<branch>.
func (r PRFindRefs) QualifiedHeadRef() string {
return r.qualifiedHeadRef.String()
}
func (r PRFindRefs) UnqualifiedHeadRef() string {
return r.qualifiedHeadRef.BranchName()
}
// Matches checks whether the provided baseBranchName and headRef match the refs.
// It is used to determine whether Pull Requests returned from the API
func (r PRFindRefs) Matches(baseBranchName, qualifiedHeadRef string) bool {
headMatches := qualifiedHeadRef == r.QualifiedHeadRef()
baseMatches := r.baseBranchName.IsNone() || baseBranchName == r.baseBranchName.Unwrap()
return headMatches && baseMatches
}
func (r PRFindRefs) BaseRepo() ghrepo.Interface {
return r.baseRepo
}
type RemoteNameToRepoFn func(remoteName string) (ghrepo.Interface, error)
// PullRequestFindRefsResolver interrogates git configuration to try and determine
// a head repository and a remote branch name, from a local branch name.
type PullRequestFindRefsResolver struct {
GitConfigClient GitConfigClient
RemoteNameToRepoFn RemoteNameToRepoFn
}
func NewPullRequestFindRefsResolver(gitConfigClient GitConfigClient, remotesFn func() (ghContext.Remotes, error)) PullRequestFindRefsResolver {
return PullRequestFindRefsResolver{
GitConfigClient: gitConfigClient,
RemoteNameToRepoFn: newRemoteNameToRepoFn(remotesFn),
}
}
// ResolvePullRequestRefs takes a base repository, a base branch name and a local branch name and uses the git configuration to
// determine the head repository and remote branch name. If we were unable to determine this from git, we default the head
// repository to the base repository.
func (r *PullRequestFindRefsResolver) ResolvePullRequestRefs(baseRepo ghrepo.Interface, baseBranchName, localBranchName string) (PRFindRefs, error) {
if baseRepo == nil {
return PRFindRefs{}, fmt.Errorf("find pull request ref resolution cannot be performed without a base repository")
}
if localBranchName == "" {
return PRFindRefs{}, fmt.Errorf("find pull request ref resolution cannot be performed without a local branch name")
}
headPRRef, err := TryDetermineDefaultPRHead(r.GitConfigClient, remoteToRepoResolver{r.RemoteNameToRepoFn}, localBranchName)
if err != nil {
return PRFindRefs{}, err
}
// If the headRepo was resolved, we can just convert the response
// to refs and return it.
if headRepo, present := headPRRef.Repo.Value(); present {
qualifiedHeadRef := NewQualifiedHeadRefWithoutOwner(headPRRef.BranchName)
if !ghrepo.IsSame(headRepo, baseRepo) {
qualifiedHeadRef = NewQualifiedHeadRef(headRepo.RepoOwner(), headPRRef.BranchName)
}
return PRFindRefs{
qualifiedHeadRef: qualifiedHeadRef,
baseRepo: baseRepo,
baseBranchName: o.SomeIfNonZero(baseBranchName),
}, nil
}
// If we didn't find a head repo, default to the base repo
return PRFindRefs{
qualifiedHeadRef: NewQualifiedHeadRefWithoutOwner(headPRRef.BranchName),
baseRepo: baseRepo,
baseBranchName: o.SomeIfNonZero(baseBranchName),
}, nil
}
// DefaultPRHead is a neighbour to defaultPushTarget, but instead of holding
// basic git remote information, it holds a resolved repository in `gh` terms.
//
// Since we may not be able to determine a default remote for a branch, this
// is also true of the resolved repository.
type DefaultPRHead struct {
Repo o.Option[ghrepo.Interface]
BranchName string
}
// TryDetermineDefaultPRHead is a thin wrapper around determineDefaultPushTarget, which attempts to convert
// a present remote into a resolved repository. If the remote is not present, we indicate that to the caller
// by returning a None value for the repo.
func TryDetermineDefaultPRHead(gitClient GitConfigClient, remoteToRepo remoteToRepoResolver, branch string) (DefaultPRHead, error) {
pushTarget, err := tryDetermineDefaultPushTarget(gitClient, branch)
if err != nil {
return DefaultPRHead{}, err
}
// If we have no remote, let the caller decide what to do by indicating that with a None.
if pushTarget.remote.IsNone() {
return DefaultPRHead{
Repo: o.None[ghrepo.Interface](),
BranchName: pushTarget.branchName,
}, nil
}
repo, err := remoteToRepo.resolve(pushTarget.remote.Unwrap())
if err != nil {
return DefaultPRHead{}, err
}
return DefaultPRHead{
Repo: o.Some(repo),
BranchName: pushTarget.branchName,
}, nil
}
// remote represents the value of the remote key in a branch's git configuration.
// This value may be a name or a URL, both of which are strings, but are unfortunately
// parsed by ReadBranchConfig into separate fields, allowing for illegal states to be
// created by accident. This is an attempt to indicate that they are mutally exclusive.
type remote interface{ sealedRemote() }
type remoteName struct{ name string }
func (rn remoteName) sealedRemote() {}
type remoteURL struct{ url *url.URL }
func (ru remoteURL) sealedRemote() {}
// newRemoteNameToRepoFn takes a function that returns a list of remotes and
// returns a function that takes a remote name and returns the corresponding
// repository. It is a convenience function to call sites having to duplicate
// the same logic.
func newRemoteNameToRepoFn(remotesFn func() (ghContext.Remotes, error)) RemoteNameToRepoFn {
return func(remoteName string) (ghrepo.Interface, error) {
remotes, err := remotesFn()
if err != nil {
return nil, err
}
repo, err := remotes.FindByName(remoteName)
if err != nil {
return nil, err
}
return repo, nil
}
}
// remoteToRepoResolver provides a utility method to resolve a remote (either name or URL)
// to a repo (ghrepo.Interface).
type remoteToRepoResolver struct {
remoteNameToRepo RemoteNameToRepoFn
}
func NewRemoteToRepoResolver(remotesFn func() (ghContext.Remotes, error)) remoteToRepoResolver {
return remoteToRepoResolver{
remoteNameToRepo: newRemoteNameToRepoFn(remotesFn),
}
}
// resolve takes a remote and returns a repository representing it.
func (r remoteToRepoResolver) resolve(remote remote) (ghrepo.Interface, error) {
switch v := remote.(type) {
case remoteName:
repo, err := r.remoteNameToRepo(v.name)
if err != nil {
return nil, fmt.Errorf("could not resolve remote %q: %w", v.name, err)
}
return repo, nil
case remoteURL:
repo, err := ghrepo.FromURL(v.url)
if err != nil {
return nil, fmt.Errorf("could not parse remote URL %q: %w", v.url, err)
}
return repo, nil
default:
return nil, fmt.Errorf("unsupported remote type %T, value: %v", v, remote)
}
}
// A defaultPushTarget represents the remote name or URL and a branch name
// that we would expect a branch to be pushed to if `git push` were run with
// no further arguments. This is the most likely place for the head of the PR
// to be, but it's not guaranteed. The user may have pushed to another branch
// directly via `git push <remote> <local>:<remote>` and not set up tracking information.
// A branch name is always present.
//
// It's possible that we're unable to determine a remote, if the user had pushed directly
// to a URL for example `git push <url> <branch>`, which is why it is optional. When present,
// the remote may either be a name or a URL.
type defaultPushTarget struct {
remote o.Option[remote]
branchName string
}
// newDefaultPushTarget is a thin wrapper over defaultPushTarget to help with
// generic type inference, to reduce verbosity in repeating the parametric type.
func newDefaultPushTarget(remote remote, branchName string) defaultPushTarget {
return defaultPushTarget{
remote: o.Some(remote),
branchName: branchName,
}
}
// tryDetermineDefaultPushTarget uses git configuration to make a best guess about where a branch
// is pushed to, and where it would be pushed to if the user ran `git push` with no additional
// arguments.
//
// Firstly, it attempts to resolve the @{push} ref, which is the most reliable method, as this
// is what git uses to determine the remote tracking branch
//
// If this fails, we go through a series of steps to determine the remote:
//
// 1. check branch configuration for `branch.<name>.pushRemote = <name> | <url>`
// 2. check remote configuration for `remote.pushDefault = <name>`
// 3. check branch configuration for `branch.<name>.remote = <name> | <url>`
//
// If none of these are set, we indicate that we were unable to determine the
// remote by returning a None value for the remote.
//
// The branch name is always set. The default configuration for push.default (current) indicates
// that a git push should use the same remote branch name as the local branch name. If push.default
// is set to upstream or tracking (deprecated form of upstream), then we use the branch name from the merge ref.
func tryDetermineDefaultPushTarget(gitClient GitConfigClient, localBranchName string) (defaultPushTarget, error) {
// If @{push} resolves, then we have the remote tracking branch already, no problem.
if pushRevisionRef, err := gitClient.PushRevision(context.Background(), localBranchName); err == nil {
return newDefaultPushTarget(remoteName{pushRevisionRef.Remote}, pushRevisionRef.Branch), nil
}
// But it doesn't always resolve, so we can suppress the error and move on to other means
// of determination. We'll first look at branch and remote configuration to make a determination.
branchConfig, err := gitClient.ReadBranchConfig(context.Background(), localBranchName)
if err != nil {
return defaultPushTarget{}, err
}
pushDefault, err := gitClient.PushDefault(context.Background())
if err != nil {
return defaultPushTarget{}, err
}
// We assume the PR's branch name is the same as whatever was provided, unless the user has specified
// push.default = upstream or tracking, then we use the branch name from the merge ref if it exists. Otherwise, we fall back to the local branch name
remoteBranch := localBranchName
if pushDefault == git.PushDefaultUpstream || pushDefault == git.PushDefaultTracking {
mergeRef := strings.TrimPrefix(branchConfig.MergeRef, "refs/heads/")
if mergeRef != "" {
remoteBranch = mergeRef
}
}
// To get the remote, we look to the git config. It comes from one of the following, in order of precedence:
// 1. branch.<name>.pushRemote (which may be a name or a URL)
// 2. remote.pushDefault (which is a remote name)
// 3. branch.<name>.remote (which may be a name or a URL)
if branchConfig.PushRemoteName != "" {
return newDefaultPushTarget(
remoteName{branchConfig.PushRemoteName},
remoteBranch,
), nil
}
if branchConfig.PushRemoteURL != nil {
return newDefaultPushTarget(
remoteURL{branchConfig.PushRemoteURL},
remoteBranch,
), nil
}
remotePushDefault, err := gitClient.RemotePushDefault(context.Background())
if err != nil {
return defaultPushTarget{}, err
}
if remotePushDefault != "" {
return newDefaultPushTarget(
remoteName{remotePushDefault},
remoteBranch,
), nil
}
if branchConfig.RemoteName != "" {
return newDefaultPushTarget(
remoteName{branchConfig.RemoteName},
remoteBranch,
), nil
}
if branchConfig.RemoteURL != nil {
return newDefaultPushTarget(
remoteURL{branchConfig.RemoteURL},
remoteBranch,
), nil
}
// If we couldn't find the remote, we'll indicate that to the caller via None.
return defaultPushTarget{
remote: o.None[remote](),
branchName: remoteBranch,
}, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/shared/templates.go | pkg/cmd/pr/shared/templates.go | package shared
import (
"context"
"errors"
"fmt"
"net/http"
"time"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/git"
fd "github.com/cli/cli/v2/internal/featuredetection"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/githubtemplate"
"github.com/shurcooL/githubv4"
)
type issueTemplate struct {
Gname string `graphql:"name"`
Gbody string `graphql:"body"`
Gtitle string `graphql:"title"`
}
type pullRequestTemplate struct {
Gname string `graphql:"filename"`
Gbody string `graphql:"body"`
}
func (t *issueTemplate) Name() string {
return t.Gname
}
func (t *issueTemplate) NameForSubmit() string {
return t.Gname
}
func (t *issueTemplate) Body() []byte {
return []byte(t.Gbody)
}
func (t *issueTemplate) Title() string {
return t.Gtitle
}
func (t *pullRequestTemplate) Name() string {
return t.Gname
}
func (t *pullRequestTemplate) NameForSubmit() string {
return ""
}
func (t *pullRequestTemplate) Body() []byte {
return []byte(t.Gbody)
}
func (t *pullRequestTemplate) Title() string {
return ""
}
func listIssueTemplates(httpClient *http.Client, repo ghrepo.Interface) ([]Template, error) {
var query struct {
Repository struct {
IssueTemplates []issueTemplate
} `graphql:"repository(owner: $owner, name: $name)"`
}
variables := map[string]interface{}{
"owner": githubv4.String(repo.RepoOwner()),
"name": githubv4.String(repo.RepoName()),
}
gql := api.NewClientFromHTTP(httpClient)
err := gql.Query(repo.RepoHost(), "IssueTemplates", &query, variables)
if err != nil {
return nil, err
}
ts := query.Repository.IssueTemplates
templates := make([]Template, len(ts))
for i := range templates {
templates[i] = &ts[i]
}
return templates, nil
}
func listPullRequestTemplates(httpClient *http.Client, repo ghrepo.Interface) ([]Template, error) {
var query struct {
Repository struct {
PullRequestTemplates []pullRequestTemplate
} `graphql:"repository(owner: $owner, name: $name)"`
}
variables := map[string]interface{}{
"owner": githubv4.String(repo.RepoOwner()),
"name": githubv4.String(repo.RepoName()),
}
gql := api.NewClientFromHTTP(httpClient)
err := gql.Query(repo.RepoHost(), "PullRequestTemplates", &query, variables)
if err != nil {
return nil, err
}
ts := query.Repository.PullRequestTemplates
templates := make([]Template, len(ts))
for i := range templates {
templates[i] = &ts[i]
}
return templates, nil
}
type Template interface {
Name() string
NameForSubmit() string
Body() []byte
Title() string
}
type iprompter interface {
Select(string, string, []string) (int, error)
}
type templateManager struct {
repo ghrepo.Interface
rootDir string
allowFS bool
isPR bool
httpClient *http.Client
detector fd.Detector
prompter iprompter
templates []Template
legacyTemplate Template
didFetch bool
fetchError error
}
func NewTemplateManager(httpClient *http.Client, repo ghrepo.Interface, p iprompter, dir string, allowFS bool, isPR bool) *templateManager {
cachedClient := api.NewCachedHTTPClient(httpClient, time.Hour*24)
return &templateManager{
repo: repo,
rootDir: dir,
allowFS: allowFS,
isPR: isPR,
httpClient: httpClient,
prompter: p,
detector: fd.NewDetector(cachedClient, repo.RepoHost()),
}
}
func (m *templateManager) hasAPI() (bool, error) {
if !m.isPR {
return true, nil
}
features, err := m.detector.RepositoryFeatures()
if err != nil {
return false, err
}
return features.PullRequestTemplateQuery, nil
}
func (m *templateManager) HasTemplates() (bool, error) {
if err := m.memoizedFetch(); err != nil {
return false, err
}
return len(m.templates) > 0, nil
}
func (m *templateManager) LegacyBody() []byte {
if m.legacyTemplate == nil {
return nil
}
return m.legacyTemplate.Body()
}
func (m *templateManager) Choose() (Template, error) {
if err := m.memoizedFetch(); err != nil {
return nil, err
}
if len(m.templates) == 0 {
return nil, nil
}
names := make([]string, len(m.templates))
for i, t := range m.templates {
names[i] = t.Name()
}
blankOption := "Open a blank issue"
if m.isPR {
blankOption = "Open a blank pull request"
}
selectedOption, err := m.prompter.Select("Choose a template", "", append(names, blankOption))
if err != nil {
return nil, fmt.Errorf("could not prompt: %w", err)
}
if selectedOption == len(names) {
return nil, nil
}
return m.templates[selectedOption], nil
}
func (m *templateManager) Select(name string) (Template, error) {
if err := m.memoizedFetch(); err != nil {
return nil, err
}
if len(m.templates) == 0 {
return nil, errors.New("no templates found")
}
for _, t := range m.templates {
if t.Name() == name {
return t, nil
}
}
return nil, fmt.Errorf("template %q not found", name)
}
func (m *templateManager) memoizedFetch() error {
if m.didFetch {
return m.fetchError
}
m.fetchError = m.fetch()
m.didFetch = true
return m.fetchError
}
func (m *templateManager) fetch() error {
hasAPI, err := m.hasAPI()
if err != nil {
return err
}
if hasAPI {
lister := listIssueTemplates
if m.isPR {
lister = listPullRequestTemplates
}
templates, err := lister(m.httpClient, m.repo)
if err != nil {
return err
}
m.templates = templates
}
if !m.allowFS {
return nil
}
dir := m.rootDir
if dir == "" {
var err error
gitClient := &git.Client{}
dir, err = gitClient.ToplevelDir(context.Background())
if err != nil {
//nolint:nilerr // intentional, abort silently
return nil
}
}
filePattern := "ISSUE_TEMPLATE"
if m.isPR {
filePattern = "PULL_REQUEST_TEMPLATE"
}
if !hasAPI {
issueTemplates := githubtemplate.FindNonLegacy(dir, filePattern)
m.templates = make([]Template, len(issueTemplates))
for i, t := range issueTemplates {
m.templates[i] = &filesystemTemplate{path: t}
}
}
if legacyTemplate := githubtemplate.FindLegacy(dir, filePattern); legacyTemplate != "" {
m.legacyTemplate = &filesystemTemplate{path: legacyTemplate}
}
return nil
}
type filesystemTemplate struct {
path string
}
func (t *filesystemTemplate) Name() string {
return githubtemplate.ExtractName(t.path)
}
func (t *filesystemTemplate) NameForSubmit() string {
return ""
}
func (t *filesystemTemplate) Body() []byte {
return githubtemplate.ExtractContents(t.path)
}
func (t *filesystemTemplate) Title() string {
return githubtemplate.ExtractTitle(t.path)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/shared/finder.go | pkg/cmd/pr/shared/finder.go | package shared
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"testing"
"time"
"github.com/cli/cli/v2/api"
ghContext "github.com/cli/cli/v2/context"
"github.com/cli/cli/v2/git"
fd "github.com/cli/cli/v2/internal/featuredetection"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmdutil"
o "github.com/cli/cli/v2/pkg/option"
"github.com/cli/cli/v2/pkg/set"
"github.com/shurcooL/githubv4"
"golang.org/x/sync/errgroup"
)
type PRFinder interface {
Find(opts FindOptions) (*api.PullRequest, ghrepo.Interface, error)
}
type progressIndicator interface {
StartProgressIndicator()
StopProgressIndicator()
}
type GitConfigClient interface {
ReadBranchConfig(ctx context.Context, branchName string) (git.BranchConfig, error)
PushDefault(ctx context.Context) (git.PushDefault, error)
RemotePushDefault(ctx context.Context) (string, error)
PushRevision(ctx context.Context, branchName string) (git.RemoteTrackingRef, error)
}
type finder struct {
baseRepoFn func() (ghrepo.Interface, error)
branchFn func() (string, error)
httpClient func() (*http.Client, error)
remotesFn func() (ghContext.Remotes, error)
gitConfigClient GitConfigClient
progress progressIndicator
baseRefRepo ghrepo.Interface
prNumber int
branchName string
}
func NewFinder(factory *cmdutil.Factory) PRFinder {
if finderForRunCommandStyleTests != nil {
f := finderForRunCommandStyleTests
finderForRunCommandStyleTests = &mockFinder{err: errors.New("you must use StubFinderForRunCommandStyleTests to stub PR lookups")}
return f
}
return &finder{
baseRepoFn: factory.BaseRepo,
branchFn: factory.Branch,
httpClient: factory.HttpClient,
gitConfigClient: factory.GitClient,
remotesFn: factory.Remotes,
progress: factory.IOStreams,
}
}
var finderForRunCommandStyleTests PRFinder
// StubFinderForRunCommandStyleTests is the NewMockFinder substitute to be used ONLY in runCommand-style tests.
func StubFinderForRunCommandStyleTests(t *testing.T, selector string, pr *api.PullRequest, repo ghrepo.Interface) *mockFinder {
// Create a new mock finder and override the "runCommandFinder" variable so that calls to
// NewFinder() will return this mock. This is a bad pattern, and a result of old style runCommand
// tests that would ideally be replaced. The reason we need to do this is that the runCommand style tests
// construct the cobra command via NewCmd* functions, and then Execute them directly, providing no opportunity
// to inject a test double unless it's on the factory, which finder never is, because only PR commands need it.
finder := NewMockFinder(selector, pr, repo)
finderForRunCommandStyleTests = finder
// Ensure that at the end of the test, we reset the "runCommandFinder" variable so that tests are isolated,
// at least if they are run sequentially.
t.Cleanup(func() {
finderForRunCommandStyleTests = nil
})
return finder
}
type FindOptions struct {
// Selector can be a number with optional `#` prefix, a branch name with optional `<owner>:` prefix, or
// a PR URL.
Selector string
// Fields lists the GraphQL fields to fetch for the PullRequest.
Fields []string
// BaseBranch is the name of the base branch to scope the PR-for-branch lookup to.
BaseBranch string
// States lists the possible PR states to scope the PR-for-branch lookup to.
States []string
DisableProgress bool
Detector fd.Detector
}
func (f *finder) Find(opts FindOptions) (*api.PullRequest, ghrepo.Interface, error) {
// If we have a URL, we don't need git stuff
if len(opts.Fields) == 0 {
return nil, nil, errors.New("Find error: no fields specified")
}
if repo, prNumber, _, err := ParseURL(opts.Selector); err == nil {
f.prNumber = prNumber
f.baseRefRepo = repo
}
if f.baseRefRepo == nil {
repo, err := f.baseRepoFn()
if err != nil {
return nil, nil, err
}
f.baseRefRepo = repo
}
var prRefs PRFindRefs
if opts.Selector == "" {
// You must be in a git repo for this case to work
currentBranchName, err := f.branchFn()
if err != nil {
return nil, nil, err
}
f.branchName = currentBranchName
// Get the branch config for the current branchName
branchConfig, err := f.gitConfigClient.ReadBranchConfig(context.Background(), f.branchName)
if err != nil {
return nil, nil, err
}
// Determine if the branch is configured to merge to a special PR ref
prHeadRE := regexp.MustCompile(`^refs/pull/(\d+)/head$`)
if m := prHeadRE.FindStringSubmatch(branchConfig.MergeRef); m != nil {
prNumber, _ := strconv.Atoi(m[1])
f.prNumber = prNumber
}
// Determine the PullRequestRefs from config
if f.prNumber == 0 {
prRefsResolver := NewPullRequestFindRefsResolver(
// We requested the branch config already, so let's cache that
CachedBranchConfigGitConfigClient{
CachedBranchConfig: branchConfig,
GitConfigClient: f.gitConfigClient,
},
f.remotesFn,
)
prRefs, err = prRefsResolver.ResolvePullRequestRefs(f.baseRefRepo, opts.BaseBranch, f.branchName)
if err != nil {
return nil, nil, err
}
}
} else if f.prNumber == 0 {
// You gave me a selector but I couldn't find a PR number (it wasn't a URL)
// Try to get a PR number from the selector
prNumber, err := strconv.Atoi(strings.TrimPrefix(opts.Selector, "#"))
// If opts.Selector is a valid number then assume it is the
// PR number unless opts.BaseBranch is specified. This is a
// special case for PR create command which will always want
// to assume that a numerical selector is a branch name rather
// than PR number.
if opts.BaseBranch == "" && err == nil {
f.prNumber = prNumber
} else {
f.branchName = opts.Selector
qualifiedHeadRef, err := ParseQualifiedHeadRef(f.branchName)
if err != nil {
return nil, nil, err
}
prRefs = PRFindRefs{
qualifiedHeadRef: qualifiedHeadRef,
baseRepo: f.baseRefRepo,
baseBranchName: o.SomeIfNonZero(opts.BaseBranch),
}
}
}
// Set up HTTP client
httpClient, err := f.httpClient()
if err != nil {
return nil, nil, err
}
// TODO: Decouple the PR finder from IO
// TODO(josebalius): Should we be guarding here?
if !opts.DisableProgress && f.progress != nil {
f.progress.StartProgressIndicator()
defer f.progress.StopProgressIndicator()
}
fields := set.NewStringSet()
fields.AddValues(opts.Fields)
numberFieldOnly := fields.Len() == 1 && fields.Contains("number")
fields.AddValues([]string{"id", "number"}) // for additional preload queries below
if fields.Contains("isInMergeQueue") || fields.Contains("isMergeQueueEnabled") {
if opts.Detector == nil {
cachedClient := api.NewCachedHTTPClient(httpClient, time.Hour*24)
opts.Detector = fd.NewDetector(cachedClient, f.baseRefRepo.RepoHost())
}
prFeatures, err := opts.Detector.PullRequestFeatures()
if err != nil {
return nil, nil, err
}
if !prFeatures.MergeQueue {
fields.Remove("isInMergeQueue")
fields.Remove("isMergeQueueEnabled")
}
}
var getProjectItems bool
if fields.Contains("projectItems") {
getProjectItems = true
fields.Remove("projectItems")
}
// TODO projectsV1Deprecation
// Remove this block
// When removing this, remember to remove `projectCards` from the list of default fields in pr/view.go
if fields.Contains("projectCards") {
if opts.Detector == nil {
cachedClient := api.NewCachedHTTPClient(httpClient, time.Hour*24)
opts.Detector = fd.NewDetector(cachedClient, f.baseRefRepo.RepoHost())
}
if opts.Detector.ProjectsV1() == gh.ProjectsV1Unsupported {
fields.Remove("projectCards")
}
}
var pr *api.PullRequest
if f.prNumber > 0 {
// If we have a PR number, let's look it up
if numberFieldOnly {
// avoid hitting the API if we already have all the information
return &api.PullRequest{Number: f.prNumber}, f.baseRefRepo, nil
}
pr, err = findByNumber(httpClient, f.baseRefRepo, f.prNumber, fields.ToSlice())
if err != nil {
return pr, f.baseRefRepo, err
}
} else if prRefs.BaseRepo() != nil && f.branchName != "" {
// No PR number, but we have a base repo and branch name.
pr, err = findForRefs(httpClient, prRefs, opts.States, fields.ToSlice())
if err != nil {
return pr, f.baseRefRepo, err
}
} else {
// If we don't have a PR number or a base repo and branch name,
// we can't do anything
return nil, f.baseRefRepo, &NotFoundError{fmt.Errorf("no pull requests found")}
}
g, _ := errgroup.WithContext(context.Background())
if fields.Contains("reviews") {
g.Go(func() error {
return preloadPrReviews(httpClient, f.baseRefRepo, pr)
})
}
if fields.Contains("comments") {
g.Go(func() error {
return preloadPrComments(httpClient, f.baseRefRepo, pr)
})
}
if fields.Contains("closingIssuesReferences") {
g.Go(func() error {
return preloadPrClosingIssuesReferences(httpClient, f.baseRefRepo, pr)
})
}
if fields.Contains("statusCheckRollup") {
g.Go(func() error {
return preloadPrChecks(httpClient, f.baseRefRepo, pr)
})
}
if getProjectItems {
g.Go(func() error {
apiClient := api.NewClientFromHTTP(httpClient)
err := api.ProjectsV2ItemsForPullRequest(apiClient, f.baseRefRepo, pr)
if err != nil && !api.ProjectsV2IgnorableError(err) {
return err
}
return nil
})
}
return pr, f.baseRefRepo, g.Wait()
}
var pullURLRE = regexp.MustCompile(`^/([^/]+)/([^/]+)/pull/(\d+)(.*$)`)
// ParseURL parses a pull request URL and returns the repository, pull request
// number, and any tailing path components. If there is no error, the returned
// repo is not nil and will have non-empty hostname.
func ParseURL(prURL string) (ghrepo.Interface, int, string, error) {
if prURL == "" {
return nil, 0, "", fmt.Errorf("invalid URL: %q", prURL)
}
u, err := url.Parse(prURL)
if err != nil {
return nil, 0, "", err
}
if u.Scheme != "https" && u.Scheme != "http" {
return nil, 0, "", fmt.Errorf("invalid scheme: %s", u.Scheme)
}
m := pullURLRE.FindStringSubmatch(u.Path)
if m == nil {
return nil, 0, "", fmt.Errorf("not a pull request URL: %s", prURL)
}
repo := ghrepo.NewWithHost(m[1], m[2], u.Hostname())
prNumber, _ := strconv.Atoi(m[3])
tail := m[4]
return repo, prNumber, tail, nil
}
var fullReferenceRE = regexp.MustCompile(`^(?:([^/]+)/([^/]+))#(\d+)$`)
// ParseFullReference parses a short issue/pull request reference of the form
// "owner/repo#number", where owner, repo and number are all required.
func ParseFullReference(s string) (ghrepo.Interface, int, error) {
if s == "" {
return nil, 0, errors.New("empty reference")
}
m := fullReferenceRE.FindStringSubmatch(s)
if m == nil {
return nil, 0, fmt.Errorf("invalid reference: %q", s)
}
number, err := strconv.Atoi(m[3])
if err != nil {
return nil, 0, fmt.Errorf("invalid reference: %q", number)
}
owner := m[1]
repo := m[2]
return ghrepo.New(owner, repo), number, nil
}
func findByNumber(httpClient *http.Client, repo ghrepo.Interface, number int, fields []string) (*api.PullRequest, error) {
type response struct {
Repository struct {
PullRequest api.PullRequest
}
}
query := fmt.Sprintf(`
query PullRequestByNumber($owner: String!, $repo: String!, $pr_number: Int!) {
repository(owner: $owner, name: $repo) {
pullRequest(number: $pr_number) {%s}
}
}`, api.PullRequestGraphQL(fields))
variables := map[string]interface{}{
"owner": repo.RepoOwner(),
"repo": repo.RepoName(),
"pr_number": number,
}
var resp response
client := api.NewClientFromHTTP(httpClient)
err := client.GraphQL(repo.RepoHost(), query, variables, &resp)
if err != nil {
return nil, err
}
return &resp.Repository.PullRequest, nil
}
func findForRefs(httpClient *http.Client, prRefs PRFindRefs, stateFilters, fields []string) (*api.PullRequest, error) {
type response struct {
Repository struct {
PullRequests struct {
Nodes []api.PullRequest
}
DefaultBranchRef struct {
Name string
}
}
}
fieldSet := set.NewStringSet()
fieldSet.AddValues(fields)
// these fields are required for filtering below
fieldSet.AddValues([]string{"state", "baseRefName", "headRefName", "isCrossRepository", "headRepositoryOwner"})
query := fmt.Sprintf(`
query PullRequestForBranch($owner: String!, $repo: String!, $headRefName: String!, $states: [PullRequestState!]) {
repository(owner: $owner, name: $repo) {
pullRequests(headRefName: $headRefName, states: $states, first: 30, orderBy: { field: CREATED_AT, direction: DESC }) {
nodes {%s}
}
defaultBranchRef { name }
}
}`, api.PullRequestGraphQL(fieldSet.ToSlice()))
variables := map[string]interface{}{
"owner": prRefs.BaseRepo().RepoOwner(),
"repo": prRefs.BaseRepo().RepoName(),
"headRefName": prRefs.UnqualifiedHeadRef(),
"states": stateFilters,
}
var resp response
client := api.NewClientFromHTTP(httpClient)
err := client.GraphQL(prRefs.BaseRepo().RepoHost(), query, variables, &resp)
if err != nil {
return nil, err
}
prs := resp.Repository.PullRequests.Nodes
sort.SliceStable(prs, func(a, b int) bool {
return prs[a].State == "OPEN" && prs[b].State != "OPEN"
})
for _, pr := range prs {
// When the head is the default branch, it doesn't really make sense to show merged or closed PRs.
// https://github.com/cli/cli/issues/4263
isNotClosedOrMergedWhenHeadIsDefault := pr.State == "OPEN" || resp.Repository.DefaultBranchRef.Name != prRefs.QualifiedHeadRef()
if prRefs.Matches(pr.BaseRefName, pr.HeadLabel()) && isNotClosedOrMergedWhenHeadIsDefault {
return &pr, nil
}
}
return nil, &NotFoundError{fmt.Errorf("no pull requests found for branch %q", prRefs.QualifiedHeadRef())}
}
func preloadPrReviews(httpClient *http.Client, repo ghrepo.Interface, pr *api.PullRequest) error {
if !pr.Reviews.PageInfo.HasNextPage {
return nil
}
type response struct {
Node struct {
PullRequest struct {
Reviews api.PullRequestReviews `graphql:"reviews(first: 100, after: $endCursor)"`
} `graphql:"...on PullRequest"`
} `graphql:"node(id: $id)"`
}
variables := map[string]interface{}{
"id": githubv4.ID(pr.ID),
"endCursor": githubv4.String(pr.Reviews.PageInfo.EndCursor),
}
gql := api.NewClientFromHTTP(httpClient)
for {
var query response
err := gql.Query(repo.RepoHost(), "ReviewsForPullRequest", &query, variables)
if err != nil {
return err
}
pr.Reviews.Nodes = append(pr.Reviews.Nodes, query.Node.PullRequest.Reviews.Nodes...)
pr.Reviews.TotalCount = len(pr.Reviews.Nodes)
if !query.Node.PullRequest.Reviews.PageInfo.HasNextPage {
break
}
variables["endCursor"] = githubv4.String(query.Node.PullRequest.Reviews.PageInfo.EndCursor)
}
pr.Reviews.PageInfo.HasNextPage = false
return nil
}
func preloadPrComments(client *http.Client, repo ghrepo.Interface, pr *api.PullRequest) error {
if !pr.Comments.PageInfo.HasNextPage {
return nil
}
type response struct {
Node struct {
PullRequest struct {
Comments api.Comments `graphql:"comments(first: 100, after: $endCursor)"`
} `graphql:"...on PullRequest"`
} `graphql:"node(id: $id)"`
}
variables := map[string]interface{}{
"id": githubv4.ID(pr.ID),
"endCursor": githubv4.String(pr.Comments.PageInfo.EndCursor),
}
gql := api.NewClientFromHTTP(client)
for {
var query response
err := gql.Query(repo.RepoHost(), "CommentsForPullRequest", &query, variables)
if err != nil {
return err
}
pr.Comments.Nodes = append(pr.Comments.Nodes, query.Node.PullRequest.Comments.Nodes...)
pr.Comments.TotalCount = len(pr.Comments.Nodes)
if !query.Node.PullRequest.Comments.PageInfo.HasNextPage {
break
}
variables["endCursor"] = githubv4.String(query.Node.PullRequest.Comments.PageInfo.EndCursor)
}
pr.Comments.PageInfo.HasNextPage = false
return nil
}
func preloadPrClosingIssuesReferences(client *http.Client, repo ghrepo.Interface, pr *api.PullRequest) error {
if !pr.ClosingIssuesReferences.PageInfo.HasNextPage {
return nil
}
type response struct {
Node struct {
PullRequest struct {
ClosingIssuesReferences api.ClosingIssuesReferences `graphql:"closingIssuesReferences(first: 100, after: $endCursor)"`
} `graphql:"...on PullRequest"`
} `graphql:"node(id: $id)"`
}
variables := map[string]interface{}{
"id": githubv4.ID(pr.ID),
"endCursor": githubv4.String(pr.ClosingIssuesReferences.PageInfo.EndCursor),
}
gql := api.NewClientFromHTTP(client)
for {
var query response
err := gql.Query(repo.RepoHost(), "closingIssuesReferences", &query, variables)
if err != nil {
return err
}
pr.ClosingIssuesReferences.Nodes = append(pr.ClosingIssuesReferences.Nodes, query.Node.PullRequest.ClosingIssuesReferences.Nodes...)
if !query.Node.PullRequest.ClosingIssuesReferences.PageInfo.HasNextPage {
break
}
variables["endCursor"] = githubv4.String(query.Node.PullRequest.ClosingIssuesReferences.PageInfo.EndCursor)
}
pr.ClosingIssuesReferences.PageInfo.HasNextPage = false
return nil
}
func preloadPrChecks(client *http.Client, repo ghrepo.Interface, pr *api.PullRequest) error {
if len(pr.StatusCheckRollup.Nodes) == 0 {
return nil
}
statusCheckRollup := &pr.StatusCheckRollup.Nodes[0].Commit.StatusCheckRollup.Contexts
if !statusCheckRollup.PageInfo.HasNextPage {
return nil
}
endCursor := statusCheckRollup.PageInfo.EndCursor
type response struct {
Node *api.PullRequest
}
query := fmt.Sprintf(`
query PullRequestStatusChecks($id: ID!, $endCursor: String!) {
node(id: $id) {
...on PullRequest {
%s
}
}
}`, api.StatusCheckRollupGraphQLWithoutCountByState("$endCursor"))
variables := map[string]interface{}{
"id": pr.ID,
}
apiClient := api.NewClientFromHTTP(client)
for {
variables["endCursor"] = endCursor
var resp response
err := apiClient.GraphQL(repo.RepoHost(), query, variables, &resp)
if err != nil {
return err
}
result := resp.Node.StatusCheckRollup.Nodes[0].Commit.StatusCheckRollup.Contexts
statusCheckRollup.Nodes = append(
statusCheckRollup.Nodes,
result.Nodes...,
)
if !result.PageInfo.HasNextPage {
break
}
endCursor = result.PageInfo.EndCursor
}
statusCheckRollup.PageInfo.HasNextPage = false
return nil
}
type NotFoundError struct {
error
}
func (err *NotFoundError) Unwrap() error {
return err.error
}
func NewMockFinder(selector string, pr *api.PullRequest, repo ghrepo.Interface) *mockFinder {
var err error
if pr == nil {
err = &NotFoundError{errors.New("no pull requests found")}
}
return &mockFinder{
expectSelector: selector,
pr: pr,
repo: repo,
err: err,
}
}
type mockFinder struct {
called bool
expectSelector string
expectFields []string
pr *api.PullRequest
repo ghrepo.Interface
err error
}
func (m *mockFinder) Find(opts FindOptions) (*api.PullRequest, ghrepo.Interface, error) {
if m.err != nil {
return nil, nil, m.err
}
if m.expectSelector != opts.Selector {
return nil, nil, fmt.Errorf("mockFinder: expected selector %q, got %q", m.expectSelector, opts.Selector)
}
if len(m.expectFields) > 0 && !isEqualSet(m.expectFields, opts.Fields) {
return nil, nil, fmt.Errorf("mockFinder: expected fields %v, got %v", m.expectFields, opts.Fields)
}
if m.called {
return nil, nil, errors.New("mockFinder used more than once")
}
m.called = true
if m.pr.HeadRepositoryOwner.Login == "" {
// pose as same-repo PR by default
m.pr.HeadRepositoryOwner.Login = m.repo.RepoOwner()
}
return m.pr, m.repo, nil
}
func (m *mockFinder) ExpectFields(fields []string) {
m.expectFields = fields
}
func isEqualSet(a, b []string) bool {
if len(a) != len(b) {
return false
}
aCopy := make([]string, len(a))
copy(aCopy, a)
bCopy := make([]string, len(b))
copy(bCopy, b)
sort.Strings(aCopy)
sort.Strings(bCopy)
for i := range aCopy {
if aCopy[i] != bCopy[i] {
return false
}
}
return true
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/shared/finder_test.go | pkg/cmd/pr/shared/finder_test.go | package shared
import (
"context"
"errors"
"net/http"
"net/url"
"testing"
ghContext "github.com/cli/cli/v2/context"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestParseURL(t *testing.T) {
tests := []struct {
name string
arg string
wantRepo ghrepo.Interface
wantNum int
wantRest string
wantErr string
}{
{
name: "valid HTTPS URL",
arg: "https://example.com/owner/repo/pull/123",
wantRepo: ghrepo.NewWithHost("owner", "repo", "example.com"),
wantNum: 123,
},
{
name: "valid HTTP URL",
arg: "http://example.com/owner/repo/pull/123",
wantRepo: ghrepo.NewWithHost("owner", "repo", "example.com"),
wantNum: 123,
},
{
name: "valid HTTP URL with rest",
arg: "http://example.com/owner/repo/pull/123/foo/bar",
wantRepo: ghrepo.NewWithHost("owner", "repo", "example.com"),
wantNum: 123,
wantRest: "/foo/bar",
},
{
name: "valid HTTP URL with .patch as rest",
arg: "http://example.com/owner/repo/pull/123.patch",
wantRepo: ghrepo.NewWithHost("owner", "repo", "example.com"),
wantNum: 123,
wantRest: ".patch",
},
{
name: "valid HTTP URL with a trailing slash",
arg: "http://example.com/owner/repo/pull/123/",
wantRepo: ghrepo.NewWithHost("owner", "repo", "example.com"),
wantNum: 123,
wantRest: "/",
},
{
name: "empty URL",
wantErr: "invalid URL: \"\"",
},
{
name: "no scheme",
arg: "github.com/owner/repo/pull/123",
wantErr: "invalid scheme: ",
},
{
name: "invalid scheme",
arg: "ftp://github.com/owner/repo/pull/123",
wantErr: "invalid scheme: ftp",
},
{
name: "no hostname",
arg: "/owner/repo/pull/123",
wantErr: "invalid scheme: ",
},
{
name: "incorrect path",
arg: "https://github.com/owner/repo/issues/123",
wantErr: "not a pull request URL: https://github.com/owner/repo/issues/123",
},
{
name: "no PR number",
arg: "https://github.com/owner/repo/pull/",
wantErr: "not a pull request URL: https://github.com/owner/repo/pull/",
},
{
name: "invalid PR number",
arg: "https://github.com/owner/repo/pull/foo",
wantErr: "not a pull request URL: https://github.com/owner/repo/pull/foo",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
repo, num, rest, err := ParseURL(tt.arg)
if tt.wantErr != "" {
require.Error(t, err)
require.Equal(t, tt.wantErr, err.Error())
return
}
require.NoError(t, err)
require.Equal(t, tt.wantNum, num)
require.Equal(t, tt.wantRest, rest)
require.NotNil(t, repo)
require.True(t, ghrepo.IsSame(tt.wantRepo, repo))
})
}
}
func TestParseFullReference(t *testing.T) {
tests := []struct {
name string
arg string
wantRepo ghrepo.Interface
wantNumber int
wantErr string
}{
{
name: "number",
arg: "123",
wantErr: `invalid reference: "123"`,
},
{
name: "number with hash",
arg: "#123",
wantErr: `invalid reference: "#123"`,
},
{
name: "full form",
arg: "OWNER/REPO#123",
wantNumber: 123,
wantRepo: ghrepo.New("OWNER", "REPO"),
},
{
name: "empty",
wantErr: "empty reference",
},
{
name: "invalid full form, without hash",
arg: "OWNER/REPO123",
wantErr: `invalid reference: "OWNER/REPO123"`,
},
{
name: "invalid full form, empty owner and repo",
arg: "/#123",
wantErr: `invalid reference: "/#123"`,
},
{
name: "invalid full form, without owner",
arg: "REPO#123",
wantErr: `invalid reference: "REPO#123"`,
},
{
name: "invalid full form, without repo",
arg: "OWNER/#123",
wantErr: `invalid reference: "OWNER/#123"`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
repo, number, err := ParseFullReference(tt.arg)
if tt.wantErr != "" {
require.EqualError(t, err, tt.wantErr)
assert.Nil(t, repo)
assert.Zero(t, number)
return
}
require.NoError(t, err)
assert.Equal(t, tt.wantNumber, number)
if tt.wantRepo != nil {
require.NotNil(t, repo)
assert.True(t, ghrepo.IsSame(tt.wantRepo, repo))
} else {
assert.Nil(t, repo)
}
})
}
}
type args struct {
baseRepoFn func() (ghrepo.Interface, error)
branchFn func() (string, error)
gitConfigClient stubGitConfigClient
progress *stubProgressIndicator
selector string
fields []string
baseBranch string
disableProgress bool
}
func TestFind(t *testing.T) {
originOwnerUrl, err := url.Parse("https://github.com/ORIGINOWNER/REPO.git")
if err != nil {
t.Fatal(err)
}
remoteOrigin := ghContext.Remote{
Remote: &git.Remote{
Name: "origin",
FetchURL: originOwnerUrl,
},
Repo: ghrepo.New("ORIGINOWNER", "REPO"),
}
remoteOther := ghContext.Remote{
Remote: &git.Remote{
Name: "other",
FetchURL: originOwnerUrl,
},
Repo: ghrepo.New("ORIGINOWNER", "OTHER-REPO"),
}
upstreamOwnerUrl, err := url.Parse("https://github.com/UPSTREAMOWNER/REPO.git")
if err != nil {
t.Fatal(err)
}
remoteUpstream := ghContext.Remote{
Remote: &git.Remote{
Name: "upstream",
FetchURL: upstreamOwnerUrl,
},
Repo: ghrepo.New("UPSTREAMOWNER", "REPO"),
}
tests := []struct {
name string
args args
httpStub func(*httpmock.Registry)
wantUseProgress bool
wantPR int
wantRepo string
wantErr bool
}{
{
name: "number argument",
args: args{
selector: "13",
fields: []string{"id", "number"},
baseRepoFn: stubBaseRepoFn(ghrepo.New("ORIGINOWNER", "REPO"), nil),
branchFn: func() (string, error) {
return "blueberries", nil
},
},
httpStub: func(r *httpmock.Registry) {
r.Register(
httpmock.GraphQL(`query PullRequestByNumber\b`),
httpmock.StringResponse(`{"data":{"repository":{
"pullRequest":{"number":13}
}}}`))
},
wantPR: 13,
wantRepo: "https://github.com/ORIGINOWNER/REPO",
},
{
name: "number argument with base branch",
args: args{
selector: "13",
baseBranch: "main",
fields: []string{"id", "number"},
baseRepoFn: stubBaseRepoFn(ghrepo.New("ORIGINOWNER", "REPO"), nil),
branchFn: func() (string, error) {
return "blueberries", nil
},
gitConfigClient: stubGitConfigClient{
readBranchConfigFn: stubBranchConfig(git.BranchConfig{
PushRemoteName: remoteOrigin.Remote.Name,
}, nil),
pushDefaultFn: stubPushDefault(git.PushDefaultSimple, nil),
remotePushDefaultFn: stubRemotePushDefault("", nil),
pushRevisionFn: stubPushRevision(git.RemoteTrackingRef{}, errors.New("testErr")),
},
},
httpStub: func(r *httpmock.Registry) {
r.Register(
httpmock.GraphQL(`query PullRequestForBranch\b`),
httpmock.StringResponse(`{"data":{"repository":{
"pullRequests":{"nodes":[
{
"number": 123,
"state": "OPEN",
"baseRefName": "main",
"headRefName": "13",
"isCrossRepository": false,
"headRepositoryOwner": {"login":"ORIGINOWNER"}
}
]}
}}}`))
},
wantPR: 123,
wantRepo: "https://github.com/ORIGINOWNER/REPO",
},
{
name: "baseRepo is error",
args: args{
selector: "13",
fields: []string{"id", "number"},
baseRepoFn: stubBaseRepoFn(nil, errors.New("baseRepoErr")),
branchFn: func() (string, error) {
return "blueberries", nil
},
gitConfigClient: stubGitConfigClient{
readBranchConfigFn: stubBranchConfig(git.BranchConfig{}, nil),
pushDefaultFn: stubPushDefault(git.PushDefaultSimple, nil),
remotePushDefaultFn: stubRemotePushDefault("", nil),
},
},
wantErr: true,
},
{
name: "blank fields is error",
args: args{
selector: "13",
fields: []string{},
},
wantErr: true,
},
{
name: "number only",
args: args{
selector: "13",
fields: []string{"number"},
baseRepoFn: stubBaseRepoFn(ghrepo.New("ORIGINOWNER", "REPO"), nil),
branchFn: func() (string, error) {
return "blueberries", nil
},
gitConfigClient: stubGitConfigClient{
readBranchConfigFn: stubBranchConfig(git.BranchConfig{}, nil),
pushDefaultFn: stubPushDefault(git.PushDefaultSimple, nil),
remotePushDefaultFn: stubRemotePushDefault("", nil),
},
},
httpStub: nil,
wantPR: 13,
wantRepo: "https://github.com/ORIGINOWNER/REPO",
},
{
name: "pr number zero",
args: args{
selector: "0",
fields: []string{"number"},
baseRepoFn: stubBaseRepoFn(ghrepo.New("ORIGINOWNER", "REPO"), nil),
branchFn: func() (string, error) {
return "blueberries", nil
},
gitConfigClient: stubGitConfigClient{
readBranchConfigFn: stubBranchConfig(git.BranchConfig{}, nil),
pushDefaultFn: stubPushDefault(git.PushDefaultSimple, nil),
remotePushDefaultFn: stubRemotePushDefault("", nil),
},
},
wantErr: true,
},
{
name: "number with hash argument",
args: args{
selector: "#13",
fields: []string{"id", "number"},
baseRepoFn: stubBaseRepoFn(ghrepo.New("ORIGINOWNER", "REPO"), nil),
branchFn: func() (string, error) {
return "blueberries", nil
},
gitConfigClient: stubGitConfigClient{
readBranchConfigFn: stubBranchConfig(git.BranchConfig{}, nil),
pushDefaultFn: stubPushDefault(git.PushDefaultSimple, nil),
remotePushDefaultFn: stubRemotePushDefault("", nil),
},
},
httpStub: func(r *httpmock.Registry) {
r.Register(
httpmock.GraphQL(`query PullRequestByNumber\b`),
httpmock.StringResponse(`{"data":{"repository":{
"pullRequest":{"number":13}
}}}`))
},
wantPR: 13,
wantRepo: "https://github.com/ORIGINOWNER/REPO",
},
{
name: "PR URL argument",
args: args{
selector: "https://example.org/OWNER/REPO/pull/13/files",
fields: []string{"id", "number"},
baseRepoFn: nil,
branchFn: func() (string, error) {
return "blueberries", nil
},
gitConfigClient: stubGitConfigClient{
readBranchConfigFn: stubBranchConfig(git.BranchConfig{}, nil),
pushDefaultFn: stubPushDefault(git.PushDefaultSimple, nil),
remotePushDefaultFn: stubRemotePushDefault("", nil),
},
},
httpStub: func(r *httpmock.Registry) {
r.Register(
httpmock.GraphQL(`query PullRequestByNumber\b`),
httpmock.StringResponse(`{"data":{"repository":{
"pullRequest":{"number":13}
}}}`))
},
wantPR: 13,
wantRepo: "https://example.org/OWNER/REPO",
},
{
name: "PR URL argument and not in a local git repo",
args: args{
selector: "https://example.org/OWNER/REPO/pull/13/files",
fields: []string{"id", "number"},
baseRepoFn: nil,
branchFn: func() (string, error) {
return "", &git.GitError{
Stderr: "fatal: branchFn error",
ExitCode: 128,
}
},
gitConfigClient: stubGitConfigClient{
readBranchConfigFn: stubBranchConfig(git.BranchConfig{}, &git.GitError{
Stderr: "fatal: branchConfig error",
ExitCode: 128,
}),
pushDefaultFn: stubPushDefault(git.PushDefaultSimple, nil),
remotePushDefaultFn: stubRemotePushDefault("", &git.GitError{
Stderr: "fatal: remotePushDefault error",
ExitCode: 128,
}),
},
},
httpStub: func(r *httpmock.Registry) {
r.Register(
httpmock.GraphQL(`query PullRequestByNumber\b`),
httpmock.StringResponse(`{"data":{"repository":{
"pullRequest":{"number":13}
}}}`))
},
wantPR: 13,
wantRepo: "https://example.org/OWNER/REPO",
},
{
name: "when provided branch argument with an open and closed PR for that branch name, it returns the open PR",
args: args{
selector: "blueberries",
fields: []string{"id", "number"},
baseRepoFn: stubBaseRepoFn(ghrepo.New("ORIGINOWNER", "REPO"), nil),
branchFn: func() (string, error) {
return "blueberries", nil
},
gitConfigClient: stubGitConfigClient{
readBranchConfigFn: stubBranchConfig(git.BranchConfig{}, nil),
pushDefaultFn: stubPushDefault(git.PushDefaultSimple, nil),
pushRevisionFn: stubPushRevision(git.RemoteTrackingRef{}, errors.New("testErr")),
remotePushDefaultFn: stubRemotePushDefault("", nil),
},
},
httpStub: func(r *httpmock.Registry) {
r.Register(
httpmock.GraphQL(`query PullRequestForBranch\b`),
httpmock.StringResponse(`{"data":{"repository":{
"pullRequests":{"nodes":[
{
"number": 14,
"state": "CLOSED",
"baseRefName": "main",
"headRefName": "blueberries",
"isCrossRepository": false,
"headRepositoryOwner": {"login":"ORIGINOWNER"}
},
{
"number": 13,
"state": "OPEN",
"baseRefName": "main",
"headRefName": "blueberries",
"isCrossRepository": false,
"headRepositoryOwner": {"login":"ORIGINOWNER"}
}
]}
}}}`))
},
wantPR: 13,
wantRepo: "https://github.com/ORIGINOWNER/REPO",
},
{
name: "branch argument with base branch",
args: args{
selector: "blueberries",
baseBranch: "main",
fields: []string{"id", "number"},
baseRepoFn: func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("OWNER/REPO")
},
branchFn: func() (string, error) {
return "blueberries", nil
},
gitConfigClient: stubGitConfigClient{
readBranchConfigFn: stubBranchConfig(git.BranchConfig{}, nil),
pushDefaultFn: stubPushDefault(git.PushDefaultSimple, nil),
remotePushDefaultFn: stubRemotePushDefault("", nil),
pushRevisionFn: stubPushRevision(git.RemoteTrackingRef{}, errors.New("testErr")),
},
},
httpStub: func(r *httpmock.Registry) {
r.Register(
httpmock.GraphQL(`query PullRequestForBranch\b`),
httpmock.StringResponse(`{"data":{"repository":{
"pullRequests":{"nodes":[
{
"number": 14,
"state": "OPEN",
"baseRefName": "dev",
"headRefName": "blueberries",
"isCrossRepository": false,
"headRepositoryOwner": {"login":"OWNER"}
},
{
"number": 13,
"state": "OPEN",
"baseRefName": "main",
"headRefName": "blueberries",
"isCrossRepository": false,
"headRepositoryOwner": {"login":"OWNER"}
}
]}
}}}`))
},
wantPR: 13,
wantRepo: "https://github.com/OWNER/REPO",
},
{
name: "no argument reads current branch",
args: args{
selector: "",
fields: []string{"id", "number"},
baseRepoFn: func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("OWNER/REPO")
},
branchFn: func() (string, error) {
return "blueberries", nil
},
gitConfigClient: stubGitConfigClient{
readBranchConfigFn: stubBranchConfig(git.BranchConfig{}, nil),
pushDefaultFn: stubPushDefault(git.PushDefaultSimple, nil),
remotePushDefaultFn: stubRemotePushDefault("", nil),
pushRevisionFn: stubPushRevision(git.RemoteTrackingRef{}, errors.New("testErr")),
},
},
httpStub: func(r *httpmock.Registry) {
r.Register(
httpmock.GraphQL(`query PullRequestForBranch\b`),
httpmock.StringResponse(`{"data":{"repository":{
"pullRequests":{"nodes":[
{
"number": 13,
"state": "OPEN",
"baseRefName": "main",
"headRefName": "blueberries",
"isCrossRepository": false,
"headRepositoryOwner": {"login":"OWNER"}
}
]}
}}}`))
},
wantPR: 13,
wantRepo: "https://github.com/OWNER/REPO",
},
{
name: "current branch with merged pr",
args: args{
selector: "",
fields: []string{"id", "number"},
baseRepoFn: func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("OWNER/REPO")
},
branchFn: func() (string, error) {
return "blueberries", nil
},
gitConfigClient: stubGitConfigClient{
readBranchConfigFn: stubBranchConfig(git.BranchConfig{}, nil),
pushDefaultFn: stubPushDefault(git.PushDefaultSimple, nil),
remotePushDefaultFn: stubRemotePushDefault("", nil),
pushRevisionFn: stubPushRevision(git.RemoteTrackingRef{}, errors.New("testErr")),
},
},
httpStub: func(r *httpmock.Registry) {
r.Register(
httpmock.GraphQL(`query PullRequestForBranch\b`),
httpmock.StringResponse(`{"data":{"repository":{
"pullRequests":{"nodes":[
{
"number": 13,
"state": "MERGED",
"baseRefName": "main",
"headRefName": "blueberries",
"isCrossRepository": false,
"headRepositoryOwner": {"login":"OWNER"}
}
]},
"defaultBranchRef":{
"name": "blueberries"
}
}}}`))
},
wantErr: true,
},
{
name: "current branch is error",
args: args{
selector: "",
fields: []string{"id", "number"},
baseRepoFn: func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("OWNER/REPO")
},
branchFn: func() (string, error) {
return "", errors.New("branchErr")
},
},
wantErr: true,
},
{
name: "when the current branch is configured to push to and pull from 'upstream' and push.default = upstream but the repo push/pulls from 'origin', it finds the PR associated with the upstream repo and returns origin as the base repo",
args: args{
selector: "",
fields: []string{"id", "number"},
baseRepoFn: stubBaseRepoFn(ghrepo.New("ORIGINOWNER", "REPO"), nil),
branchFn: func() (string, error) {
return "blueberries", nil
},
gitConfigClient: stubGitConfigClient{
readBranchConfigFn: stubBranchConfig(git.BranchConfig{
MergeRef: "refs/heads/blue-upstream-berries",
PushRemoteName: "upstream",
}, nil),
pushDefaultFn: stubPushDefault("upstream", nil),
remotePushDefaultFn: stubRemotePushDefault("", nil),
pushRevisionFn: stubPushRevision(git.RemoteTrackingRef{}, errors.New("testErr")),
},
},
httpStub: func(r *httpmock.Registry) {
r.Register(
httpmock.GraphQL(`query PullRequestForBranch\b`),
httpmock.StringResponse(`{"data":{"repository":{
"pullRequests":{"nodes":[
{
"number": 13,
"state": "OPEN",
"baseRefName": "main",
"headRefName": "blue-upstream-berries",
"isCrossRepository": true,
"headRepositoryOwner": {"login":"UPSTREAMOWNER"}
}
]}
}}}`))
},
wantPR: 13,
wantRepo: "https://github.com/ORIGINOWNER/REPO",
},
{
// The current BRANCH is configured to push to and pull from a URL (upstream, in this example)
// which is different from what the REPO is configured to push to and pull from (origin, in this example)
// and push.default = upstream. It should find the PR associated with the upstream repo and return
// origin as the base repo
name: "when push.default = upstream and the current branch is configured to push/pull from a different remote than the repo",
args: args{
selector: "",
fields: []string{"id", "number"},
baseRepoFn: stubBaseRepoFn(ghrepo.New("ORIGINOWNER", "REPO"), nil),
branchFn: func() (string, error) {
return "blueberries", nil
},
gitConfigClient: stubGitConfigClient{
readBranchConfigFn: stubBranchConfig(git.BranchConfig{
MergeRef: "refs/heads/blue-upstream-berries",
PushRemoteURL: remoteUpstream.Remote.FetchURL,
}, nil),
pushDefaultFn: stubPushDefault("upstream", nil),
remotePushDefaultFn: stubRemotePushDefault("", nil),
pushRevisionFn: stubPushRevision(git.RemoteTrackingRef{}, errors.New("testErr")),
},
},
httpStub: func(r *httpmock.Registry) {
r.Register(
httpmock.GraphQL(`query PullRequestForBranch\b`),
httpmock.StringResponse(`{"data":{"repository":{
"pullRequests":{"nodes":[
{
"number": 13,
"state": "OPEN",
"baseRefName": "main",
"headRefName": "blue-upstream-berries",
"isCrossRepository": true,
"headRepositoryOwner": {"login":"UPSTREAMOWNER"}
}
]}
}}}`))
},
wantPR: 13,
wantRepo: "https://github.com/ORIGINOWNER/REPO",
},
{
name: "current branch with upstream and fork in same org",
args: args{
selector: "",
fields: []string{"id", "number"},
baseRepoFn: stubBaseRepoFn(ghrepo.New("ORIGINOWNER", "REPO"), nil),
branchFn: func() (string, error) {
return "blueberries", nil
},
gitConfigClient: stubGitConfigClient{
readBranchConfigFn: stubBranchConfig(git.BranchConfig{}, nil),
pushDefaultFn: stubPushDefault(git.PushDefaultSimple, nil),
remotePushDefaultFn: stubRemotePushDefault("", nil),
pushRevisionFn: stubPushRevision(git.RemoteTrackingRef{Remote: "other", Branch: "blueberries"}, nil),
},
},
httpStub: func(r *httpmock.Registry) {
r.Register(
httpmock.GraphQL(`query PullRequestForBranch\b`),
httpmock.StringResponse(`{"data":{"repository":{
"pullRequests":{"nodes":[
{
"number": 13,
"state": "OPEN",
"baseRefName": "main",
"headRefName": "blueberries",
"isCrossRepository": true,
"headRepositoryOwner": {"login":"ORIGINOWNER"}
}
]}
}}}`))
},
wantPR: 13,
wantRepo: "https://github.com/ORIGINOWNER/REPO",
},
{
name: "current branch made by pr checkout",
args: args{
selector: "",
fields: []string{"id", "number"},
baseRepoFn: func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("OWNER/REPO")
},
branchFn: func() (string, error) {
return "blueberries", nil
},
gitConfigClient: stubGitConfigClient{
readBranchConfigFn: stubBranchConfig(git.BranchConfig{
MergeRef: "refs/pull/13/head",
}, nil),
},
},
httpStub: func(r *httpmock.Registry) {
r.Register(
httpmock.GraphQL(`query PullRequestByNumber\b`),
httpmock.StringResponse(`{"data":{"repository":{
"pullRequest":{"number":13}
}}}`))
},
wantPR: 13,
wantRepo: "https://github.com/OWNER/REPO",
},
{
name: "including project items",
args: args{
selector: "",
fields: []string{"projectItems"},
baseRepoFn: func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("OWNER/REPO")
},
branchFn: func() (string, error) {
return "blueberries", nil
},
gitConfigClient: stubGitConfigClient{
readBranchConfigFn: stubBranchConfig(git.BranchConfig{
MergeRef: "refs/pull/13/head",
}, nil),
pushDefaultFn: stubPushDefault(git.PushDefaultSimple, nil),
remotePushDefaultFn: stubRemotePushDefault("", nil),
},
},
httpStub: func(r *httpmock.Registry) {
r.Register(
httpmock.GraphQL(`query PullRequestByNumber\b`),
httpmock.StringResponse(`{"data":{"repository":{
"pullRequest":{"number":13}
}}}`))
r.Register(
httpmock.GraphQL(`query PullRequestProjectItems\b`),
httpmock.GraphQLQuery(`{
"data": {
"repository": {
"pullRequest": {
"projectItems": {
"nodes": [
{
"id": "PVTI_lADOB-vozM4AVk16zgK6U50",
"project": {
"id": "PVT_kwDOB-vozM4AVk16",
"title": "Test Project"
},
"status": {
"optionId": "47fc9ee4",
"name": "In Progress"
}
}
],
"pageInfo": {
"hasNextPage": false,
"endCursor": "MQ"
}
}
}
}
}
}`,
func(query string, inputs map[string]interface{}) {
require.Equal(t, float64(13), inputs["number"])
require.Equal(t, "OWNER", inputs["owner"])
require.Equal(t, "REPO", inputs["name"])
}),
)
},
wantPR: 13,
wantRepo: "https://github.com/OWNER/REPO",
},
{
name: "number argument, with non nil-progress indicator",
args: args{
selector: "13",
fields: []string{"id", "number"},
baseRepoFn: stubBaseRepoFn(ghrepo.New("ORIGINOWNER", "REPO"), nil),
branchFn: func() (string, error) {
return "blueberries", nil
},
progress: &stubProgressIndicator{},
},
httpStub: func(r *httpmock.Registry) {
r.Register(
httpmock.GraphQL(`query PullRequestByNumber\b`),
httpmock.StringResponse(`{"data":{"repository":{
"pullRequest":{"number":13}
}}}`))
},
wantPR: 13,
wantRepo: "https://github.com/ORIGINOWNER/REPO",
wantUseProgress: true,
},
{
name: "number argument, with non-nil progress indicator and DisableProgress set",
args: args{
selector: "13",
fields: []string{"id", "number"},
baseRepoFn: stubBaseRepoFn(ghrepo.New("ORIGINOWNER", "REPO"), nil),
branchFn: func() (string, error) {
return "blueberries", nil
},
progress: &stubProgressIndicator{},
disableProgress: true,
},
httpStub: func(r *httpmock.Registry) {
r.Register(
httpmock.GraphQL(`query PullRequestByNumber\b`),
httpmock.StringResponse(`{"data":{"repository":{
"pullRequest":{"number":13}
}}}`))
},
wantPR: 13,
wantRepo: "https://github.com/ORIGINOWNER/REPO",
wantUseProgress: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
defer reg.Verify(t)
if tt.httpStub != nil {
tt.httpStub(reg)
}
f := finder{
httpClient: func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
},
baseRepoFn: tt.args.baseRepoFn,
branchFn: tt.args.branchFn,
gitConfigClient: tt.args.gitConfigClient,
remotesFn: stubRemotes(ghContext.Remotes{
&remoteOrigin,
&remoteOther,
&remoteUpstream,
}, nil),
}
if tt.args.progress != nil {
f.progress = tt.args.progress
}
pr, repo, err := f.Find(FindOptions{
Selector: tt.args.selector,
Fields: tt.args.fields,
BaseBranch: tt.args.baseBranch,
DisableProgress: tt.args.disableProgress,
})
if tt.args.progress != nil {
if tt.args.progress.startCalled != tt.wantUseProgress {
t.Errorf("progress was (not) used as expected")
} else if tt.args.progress.startCalled != tt.args.progress.stopCalled {
t.Errorf("progress was started but not stopped")
}
}
if (err != nil) != tt.wantErr {
t.Errorf("Find() error = %v, wantErr %v", err, tt.wantErr)
return
}
if tt.wantErr {
if tt.wantPR > 0 {
t.Error("wantPR field is not checked in error case")
}
if tt.wantRepo != "" {
t.Error("wantRepo field is not checked in error case")
}
return
}
if pr.Number != tt.wantPR {
t.Errorf("want pr #%d, got #%d", tt.wantPR, pr.Number)
}
repoURL := ghrepo.GenerateRepoURL(repo, "")
if repoURL != tt.wantRepo {
t.Errorf("want repo %s, got %s", tt.wantRepo, repoURL)
}
})
}
}
func stubBranchConfig(branchConfig git.BranchConfig, err error) func(context.Context, string) (git.BranchConfig, error) {
return func(_ context.Context, branch string) (git.BranchConfig, error) {
return branchConfig, err
}
}
func stubRemotes(remotes ghContext.Remotes, err error) func() (ghContext.Remotes, error) {
return func() (ghContext.Remotes, error) {
return remotes, err
}
}
func stubBaseRepoFn(baseRepo ghrepo.Interface, err error) func() (ghrepo.Interface, error) {
return func() (ghrepo.Interface, error) {
return baseRepo, err
}
}
func stubPushDefault(pushDefault git.PushDefault, err error) func(context.Context) (git.PushDefault, error) {
return func(_ context.Context) (git.PushDefault, error) {
return pushDefault, err
}
}
func stubRemotePushDefault(remotePushDefault string, err error) func(context.Context) (string, error) {
return func(_ context.Context) (string, error) {
return remotePushDefault, err
}
}
func stubPushRevision(parsedPushRevision git.RemoteTrackingRef, err error) func(context.Context, string) (git.RemoteTrackingRef, error) {
return func(_ context.Context, _ string) (git.RemoteTrackingRef, error) {
return parsedPushRevision, err
}
}
type stubGitConfigClient struct {
readBranchConfigFn func(ctx context.Context, branchName string) (git.BranchConfig, error)
pushDefaultFn func(ctx context.Context) (git.PushDefault, error)
remotePushDefaultFn func(ctx context.Context) (string, error)
pushRevisionFn func(ctx context.Context, branchName string) (git.RemoteTrackingRef, error)
}
func (s stubGitConfigClient) ReadBranchConfig(ctx context.Context, branchName string) (git.BranchConfig, error) {
if s.readBranchConfigFn == nil {
panic("unexpected call to ReadBranchConfig")
}
return s.readBranchConfigFn(ctx, branchName)
}
func (s stubGitConfigClient) PushDefault(ctx context.Context) (git.PushDefault, error) {
if s.pushDefaultFn == nil {
panic("unexpected call to PushDefault")
}
return s.pushDefaultFn(ctx)
}
func (s stubGitConfigClient) RemotePushDefault(ctx context.Context) (string, error) {
if s.remotePushDefaultFn == nil {
panic("unexpected call to RemotePushDefault")
}
return s.remotePushDefaultFn(ctx)
}
func (s stubGitConfigClient) PushRevision(ctx context.Context, branchName string) (git.RemoteTrackingRef, error) {
if s.pushRevisionFn == nil {
panic("unexpected call to PushRevision")
}
return s.pushRevisionFn(ctx, branchName)
}
type stubProgressIndicator struct {
startCalled bool
stopCalled bool
}
func (s *stubProgressIndicator) StartProgressIndicator() {
s.startCalled = true
}
func (s *stubProgressIndicator) StopProgressIndicator() {
s.stopCalled = true
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/shared/commentable.go | pkg/cmd/pr/shared/commentable.go | package shared
import (
"bufio"
"errors"
"fmt"
"io"
"net/http"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/pkg/surveyext"
"github.com/spf13/cobra"
)
var errNoUserComments = errors.New("no comments found for current user")
var errDeleteNotConfirmed = errors.New("deletion not confirmed")
type InputType int
const (
InputTypeEditor InputType = iota
InputTypeInline
InputTypeWeb
)
type Commentable interface {
Link() string
Identifier() string
CurrentUserComments() []api.Comment
}
type CommentableOptions struct {
IO *iostreams.IOStreams
HttpClient func() (*http.Client, error)
RetrieveCommentable func() (Commentable, ghrepo.Interface, error)
EditSurvey func(string) (string, error)
InteractiveEditSurvey func(string) (string, error)
ConfirmSubmitSurvey func() (bool, error)
ConfirmCreateIfNoneSurvey func() (bool, error)
ConfirmDeleteLastComment func(string) (bool, error)
OpenInBrowser func(string) error
Interactive bool
InputType InputType
Body string
EditLast bool
DeleteLast bool
DeleteLastConfirmed bool
CreateIfNone bool
Quiet bool
Host string
}
func CommentablePreRun(cmd *cobra.Command, opts *CommentableOptions) error {
inputFlags := 0
if cmd.Flags().Changed("body") {
opts.InputType = InputTypeInline
inputFlags++
}
if cmd.Flags().Changed("body-file") {
opts.InputType = InputTypeInline
inputFlags++
}
if web, _ := cmd.Flags().GetBool("web"); web {
opts.InputType = InputTypeWeb
inputFlags++
}
if editor, _ := cmd.Flags().GetBool("editor"); editor {
opts.InputType = InputTypeEditor
inputFlags++
}
if opts.CreateIfNone && !opts.EditLast {
return cmdutil.FlagErrorf("`--create-if-none` can only be used with `--edit-last`")
}
if opts.DeleteLastConfirmed && !opts.DeleteLast {
return cmdutil.FlagErrorf("`--yes` should only be used with `--delete-last`")
}
if opts.DeleteLast {
if inputFlags > 0 {
return cmdutil.FlagErrorf("should not provide comment body when using `--delete-last`")
}
if opts.IO.CanPrompt() || opts.DeleteLastConfirmed {
opts.Interactive = opts.IO.CanPrompt()
return nil
}
return cmdutil.FlagErrorf("should provide `--yes` to confirm deletion in non-interactive mode")
}
if inputFlags == 0 {
if !opts.IO.CanPrompt() {
return cmdutil.FlagErrorf("flags required when not running interactively")
}
opts.Interactive = true
} else if inputFlags > 1 {
return cmdutil.FlagErrorf("specify only one of `--body`, `--body-file`, `--editor`, or `--web`")
}
return nil
}
func CommentableRun(opts *CommentableOptions) error {
commentable, repo, err := opts.RetrieveCommentable()
if err != nil {
return err
}
opts.Host = repo.RepoHost()
if opts.DeleteLast {
return deleteComment(commentable, opts)
}
// Create new comment, bail before complexities of updating the last comment
if !opts.EditLast {
return createComment(commentable, opts)
}
// Update the last comment, handling success or unexpected errors accordingly
err = updateComment(commentable, opts)
if err == nil {
return nil
}
if !errors.Is(err, errNoUserComments) {
return err
}
// Determine whether to create new comment, prompt user if interactive and missing option
if !opts.CreateIfNone && opts.Interactive {
opts.CreateIfNone, err = opts.ConfirmCreateIfNoneSurvey()
if err != nil {
return err
}
}
if !opts.CreateIfNone {
return errNoUserComments
}
// Create new comment because updating the last comment failed due to no user comments
if opts.Interactive {
fmt.Fprintln(opts.IO.ErrOut, "No comments found. Creating a new comment.")
}
return createComment(commentable, opts)
}
func createComment(commentable Commentable, opts *CommentableOptions) error {
switch opts.InputType {
case InputTypeWeb:
openURL := commentable.Link() + "#issuecomment-new"
if opts.IO.IsStdoutTTY() && !opts.Quiet {
fmt.Fprintf(opts.IO.ErrOut, "Opening %s in your browser.\n", text.DisplayURL(openURL))
}
return opts.OpenInBrowser(openURL)
case InputTypeEditor:
var body string
var err error
if opts.Interactive {
body, err = opts.InteractiveEditSurvey("")
} else {
body, err = opts.EditSurvey("")
}
if err != nil {
return err
}
opts.Body = body
}
if opts.Interactive {
cont, err := opts.ConfirmSubmitSurvey()
if err != nil {
return err
}
if !cont {
return errors.New("Discarding...")
}
}
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
apiClient := api.NewClientFromHTTP(httpClient)
params := api.CommentCreateInput{Body: opts.Body, SubjectId: commentable.Identifier()}
url, err := api.CommentCreate(apiClient, opts.Host, params)
if err != nil {
return err
}
if !opts.Quiet {
fmt.Fprintln(opts.IO.Out, url)
}
return nil
}
func updateComment(commentable Commentable, opts *CommentableOptions) error {
comments := commentable.CurrentUserComments()
if len(comments) == 0 {
return errNoUserComments
}
lastComment := &comments[len(comments)-1]
switch opts.InputType {
case InputTypeWeb:
openURL := lastComment.Link()
if opts.IO.IsStdoutTTY() && !opts.Quiet {
fmt.Fprintf(opts.IO.ErrOut, "Opening %s in your browser.\n", text.DisplayURL(openURL))
}
return opts.OpenInBrowser(openURL)
case InputTypeEditor:
var body string
var err error
initialValue := lastComment.Content()
if opts.Interactive {
body, err = opts.InteractiveEditSurvey(initialValue)
} else {
body, err = opts.EditSurvey(initialValue)
}
if err != nil {
return err
}
opts.Body = body
}
if opts.Interactive {
cont, err := opts.ConfirmSubmitSurvey()
if err != nil {
return err
}
if !cont {
return errors.New("Discarding...")
}
}
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
apiClient := api.NewClientFromHTTP(httpClient)
params := api.CommentUpdateInput{Body: opts.Body, CommentId: lastComment.Identifier()}
url, err := api.CommentUpdate(apiClient, opts.Host, params)
if err != nil {
return err
}
if !opts.Quiet {
fmt.Fprintln(opts.IO.Out, url)
}
return nil
}
func deleteComment(commentable Commentable, opts *CommentableOptions) error {
comments := commentable.CurrentUserComments()
if len(comments) == 0 {
return errNoUserComments
}
lastComment := comments[len(comments)-1]
cs := opts.IO.ColorScheme()
if opts.Interactive && !opts.DeleteLastConfirmed {
// This is not an ideal way of truncating a random string that may
// contain emojis or other kind of wide chars.
truncated := lastComment.Body
if len(lastComment.Body) > 40 {
truncated = lastComment.Body[:40] + "..."
}
fmt.Fprintf(opts.IO.Out, "%s Deleted comments cannot be recovered.\n", cs.WarningIcon())
ok, err := opts.ConfirmDeleteLastComment(truncated)
if err != nil {
return err
}
if !ok {
return errDeleteNotConfirmed
}
}
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
apiClient := api.NewClientFromHTTP(httpClient)
params := api.CommentDeleteInput{CommentId: lastComment.Identifier()}
deletionErr := api.CommentDelete(apiClient, opts.Host, params)
if deletionErr != nil {
return deletionErr
}
if !opts.Quiet {
fmt.Fprintln(opts.IO.ErrOut, "Comment deleted")
}
return nil
}
func CommentableConfirmSubmitSurvey(p Prompt) func() (bool, error) {
return func() (bool, error) {
return p.Confirm("Submit?", true)
}
}
func CommentableInteractiveEditSurvey(cf func() (gh.Config, error), io *iostreams.IOStreams) func(string) (string, error) {
return func(initialValue string) (string, error) {
editorCommand, err := cmdutil.DetermineEditor(cf)
if err != nil {
return "", err
}
cs := io.ColorScheme()
fmt.Fprintf(io.Out, "- %s to draft your comment in %s... ", cs.Bold("Press Enter"), cs.Bold(surveyext.EditorName(editorCommand)))
_ = waitForEnter(io.In)
return surveyext.Edit(editorCommand, "*.md", initialValue, io.In, io.Out, io.ErrOut)
}
}
func CommentableInteractiveCreateIfNoneSurvey(p Prompt) func() (bool, error) {
return func() (bool, error) {
return p.Confirm("No comments found. Create one?", true)
}
}
func CommentableEditSurvey(cf func() (gh.Config, error), io *iostreams.IOStreams) func(string) (string, error) {
return func(initialValue string) (string, error) {
editorCommand, err := cmdutil.DetermineEditor(cf)
if err != nil {
return "", err
}
return surveyext.Edit(editorCommand, "*.md", initialValue, io.In, io.Out, io.ErrOut)
}
}
func CommentableConfirmDeleteLastComment(p Prompt) func(string) (bool, error) {
return func(body string) (bool, error) {
return p.Confirm(fmt.Sprintf("Delete the comment: %q?", body), true)
}
}
func waitForEnter(r io.Reader) error {
scanner := bufio.NewScanner(r)
scanner.Scan()
return scanner.Err()
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/shared/editable_http.go | pkg/cmd/pr/shared/editable_http.go | package shared
import (
"net/http"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/shurcooL/githubv4"
"golang.org/x/sync/errgroup"
)
func UpdateIssue(httpClient *http.Client, repo ghrepo.Interface, id string, isPR bool, options Editable) error {
var wg errgroup.Group
// Labels are updated through discrete mutations to avoid having to replace the entire list of labels
// and risking race conditions.
if options.Labels.Edited {
if len(options.Labels.Add) > 0 {
wg.Go(func() error {
addedLabelIds, err := options.Metadata.LabelsToIDs(options.Labels.Add)
if err != nil {
return err
}
return addLabels(httpClient, id, repo, addedLabelIds)
})
}
if len(options.Labels.Remove) > 0 {
wg.Go(func() error {
removeLabelIds, err := options.Metadata.LabelsToIDs(options.Labels.Remove)
if err != nil {
return err
}
return removeLabels(httpClient, id, repo, removeLabelIds)
})
}
}
// updateIssue mutation does not support ProjectsV2 so do them in a separate request.
if options.Projects.Edited {
wg.Go(func() error {
apiClient := api.NewClientFromHTTP(httpClient)
addIds, removeIds, err := options.ProjectV2Ids()
if err != nil {
return err
}
if addIds == nil && removeIds == nil {
return nil
}
toAdd := make(map[string]string, len(*addIds))
toRemove := make(map[string]string, len(*removeIds))
for _, p := range *addIds {
toAdd[p] = id
}
for _, p := range *removeIds {
toRemove[p] = options.Projects.ProjectItems[p]
}
return api.UpdateProjectV2Items(apiClient, repo, toAdd, toRemove)
})
}
if dirtyExcludingLabels(options) {
wg.Go(func() error {
// updateIssue mutation does not support Actors so assignment needs to
// be in a separate request when our assignees are Actors.
// Note: this is intentionally done synchronously with updating
// other issue fields to ensure consistency with how legacy
// user assignees are handled.
// https://github.com/cli/cli/pull/10960#discussion_r2086725348
if options.Assignees.Edited && options.Assignees.ActorAssignees {
apiClient := api.NewClientFromHTTP(httpClient)
assigneeIds, err := options.AssigneeIds(apiClient, repo)
if err != nil {
return err
}
err = replaceActorAssigneesForEditable(apiClient, repo, id, assigneeIds)
if err != nil {
return err
}
}
err := replaceIssueFields(httpClient, repo, id, isPR, options)
if err != nil {
return err
}
return nil
})
}
return wg.Wait()
}
func replaceActorAssigneesForEditable(apiClient *api.Client, repo ghrepo.Interface, id string, assigneeIds *[]string) error {
type ReplaceActorsForAssignableInput struct {
AssignableID githubv4.ID `json:"assignableId"`
ActorIDs []githubv4.ID `json:"actorIds"`
}
params := ReplaceActorsForAssignableInput{
AssignableID: githubv4.ID(id),
ActorIDs: *ghIds(assigneeIds),
}
var mutation struct {
ReplaceActorsForAssignable struct {
TypeName string `graphql:"__typename"`
} `graphql:"replaceActorsForAssignable(input: $input)"`
}
variables := map[string]interface{}{"input": params}
err := apiClient.Mutate(repo.RepoHost(), "ReplaceActorsForAssignable", &mutation, variables)
if err != nil {
return err
}
return nil
}
func replaceIssueFields(httpClient *http.Client, repo ghrepo.Interface, id string, isPR bool, options Editable) error {
apiClient := api.NewClientFromHTTP(httpClient)
projectIds, err := options.ProjectIds()
if err != nil {
return err
}
var assigneeIds *[]string
if !options.Assignees.ActorAssignees {
assigneeIds, err = options.AssigneeIds(apiClient, repo)
if err != nil {
return err
}
}
milestoneId, err := options.MilestoneId()
if err != nil {
return err
}
if isPR {
params := githubv4.UpdatePullRequestInput{
PullRequestID: id,
Title: ghString(options.TitleValue()),
Body: ghString(options.BodyValue()),
AssigneeIDs: ghIds(assigneeIds),
ProjectIDs: ghIds(projectIds),
MilestoneID: ghId(milestoneId),
}
if options.Base.Edited {
params.BaseRefName = ghString(&options.Base.Value)
}
return updatePullRequest(httpClient, repo, params)
}
params := githubv4.UpdateIssueInput{
ID: id,
Title: ghString(options.TitleValue()),
Body: ghString(options.BodyValue()),
AssigneeIDs: ghIds(assigneeIds),
ProjectIDs: ghIds(projectIds),
MilestoneID: ghId(milestoneId),
}
return updateIssue(httpClient, repo, params)
}
func dirtyExcludingLabels(e Editable) bool {
return e.Title.Edited ||
e.Body.Edited ||
e.Base.Edited ||
e.Reviewers.Edited ||
e.Assignees.Edited ||
e.Projects.Edited ||
e.Milestone.Edited
}
func addLabels(httpClient *http.Client, id string, repo ghrepo.Interface, labels []string) error {
params := githubv4.AddLabelsToLabelableInput{
LabelableID: id,
LabelIDs: *ghIds(&labels),
}
var mutation struct {
AddLabelsToLabelable struct {
Typename string `graphql:"__typename"`
} `graphql:"addLabelsToLabelable(input: $input)"`
}
variables := map[string]interface{}{"input": params}
gql := api.NewClientFromHTTP(httpClient)
return gql.Mutate(repo.RepoHost(), "LabelAdd", &mutation, variables)
}
func removeLabels(httpClient *http.Client, id string, repo ghrepo.Interface, labels []string) error {
params := githubv4.RemoveLabelsFromLabelableInput{
LabelableID: id,
LabelIDs: *ghIds(&labels),
}
var mutation struct {
RemoveLabelsFromLabelable struct {
Typename string `graphql:"__typename"`
} `graphql:"removeLabelsFromLabelable(input: $input)"`
}
variables := map[string]interface{}{"input": params}
gql := api.NewClientFromHTTP(httpClient)
return gql.Mutate(repo.RepoHost(), "LabelRemove", &mutation, variables)
}
func updateIssue(httpClient *http.Client, repo ghrepo.Interface, params githubv4.UpdateIssueInput) error {
var mutation struct {
UpdateIssue struct {
Typename string `graphql:"__typename"`
} `graphql:"updateIssue(input: $input)"`
}
variables := map[string]interface{}{"input": params}
gql := api.NewClientFromHTTP(httpClient)
return gql.Mutate(repo.RepoHost(), "IssueUpdate", &mutation, variables)
}
func updatePullRequest(httpClient *http.Client, repo ghrepo.Interface, params githubv4.UpdatePullRequestInput) error {
var mutation struct {
UpdatePullRequest struct {
Typename string `graphql:"__typename"`
} `graphql:"updatePullRequest(input: $input)"`
}
variables := map[string]interface{}{"input": params}
gql := api.NewClientFromHTTP(httpClient)
err := gql.Mutate(repo.RepoHost(), "PullRequestUpdate", &mutation, variables)
return err
}
func ghIds(s *[]string) *[]githubv4.ID {
if s == nil {
return nil
}
ids := make([]githubv4.ID, len(*s))
for i, v := range *s {
ids[i] = v
}
return &ids
}
func ghId(s *string) *githubv4.ID {
if s == nil {
return nil
}
if *s == "" {
r := githubv4.ID(nil)
return &r
}
r := githubv4.ID(*s)
return &r
}
func ghString(s *string) *githubv4.String {
if s == nil {
return nil
}
r := githubv4.String(*s)
return &r
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/shared/survey.go | pkg/cmd/pr/shared/survey.go | package shared
import (
"errors"
"fmt"
"slices"
"strings"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/pkg/surveyext"
)
type Action int
const (
SubmitAction Action = iota
PreviewAction
CancelAction
MetadataAction
EditCommitMessageAction
EditCommitSubjectAction
SubmitDraftAction
noMilestone = "(none)"
submitLabel = "Submit"
submitDraftLabel = "Submit as draft"
previewLabel = "Continue in browser"
metadataLabel = "Add metadata"
cancelLabel = "Cancel"
)
type Prompt interface {
Input(string, string) (string, error)
Select(string, string, []string) (int, error)
MarkdownEditor(string, string, bool) (string, error)
Confirm(string, bool) (bool, error)
MultiSelect(string, []string, []string) ([]int, error)
}
func ConfirmIssueSubmission(p Prompt, allowPreview bool, allowMetadata bool) (Action, error) {
return confirmSubmission(p, allowPreview, allowMetadata, false, false)
}
func ConfirmPRSubmission(p Prompt, allowPreview, allowMetadata, isDraft bool) (Action, error) {
return confirmSubmission(p, allowPreview, allowMetadata, true, isDraft)
}
func confirmSubmission(p Prompt, allowPreview, allowMetadata, allowDraft, isDraft bool) (Action, error) {
var options []string
if !isDraft {
options = append(options, submitLabel)
}
if allowDraft {
options = append(options, submitDraftLabel)
}
if allowPreview {
options = append(options, previewLabel)
}
if allowMetadata {
options = append(options, metadataLabel)
}
options = append(options, cancelLabel)
result, err := p.Select("What's next?", "", options)
if err != nil {
return -1, fmt.Errorf("could not prompt: %w", err)
}
switch options[result] {
case submitLabel:
return SubmitAction, nil
case submitDraftLabel:
return SubmitDraftAction, nil
case previewLabel:
return PreviewAction, nil
case metadataLabel:
return MetadataAction, nil
case cancelLabel:
return CancelAction, nil
default:
return -1, fmt.Errorf("invalid index: %d", result)
}
}
func BodySurvey(p Prompt, state *IssueMetadataState, templateContent string) error {
if templateContent != "" {
if state.Body != "" {
// prevent excessive newlines between default body and template
state.Body = strings.TrimRight(state.Body, "\n")
state.Body += "\n\n"
}
state.Body += templateContent
}
result, err := p.MarkdownEditor("Body", state.Body, true)
if err != nil {
return err
}
if state.Body != result {
state.MarkDirty()
}
state.Body = result
return nil
}
func TitleSurvey(p Prompt, io *iostreams.IOStreams, state *IssueMetadataState) error {
var err error
result := ""
for result == "" {
result, err = p.Input("Title (required)", state.Title)
if err != nil {
return err
}
if result == "" {
fmt.Fprintf(io.ErrOut, "%s Title cannot be blank\n", io.ColorScheme().FailureIcon())
}
}
if result != state.Title {
state.MarkDirty()
}
state.Title = result
return nil
}
type MetadataFetcher struct {
IO *iostreams.IOStreams
APIClient *api.Client
Repo ghrepo.Interface
State *IssueMetadataState
}
func (mf *MetadataFetcher) RepoMetadataFetch(input api.RepoMetadataInput) (*api.RepoMetadataResult, error) {
mf.IO.StartProgressIndicator()
metadataResult, err := api.RepoMetadata(mf.APIClient, mf.Repo, input)
mf.IO.StopProgressIndicator()
mf.State.MetadataResult = metadataResult
return metadataResult, err
}
type RepoMetadataFetcher interface {
RepoMetadataFetch(api.RepoMetadataInput) (*api.RepoMetadataResult, error)
}
func MetadataSurvey(p Prompt, io *iostreams.IOStreams, baseRepo ghrepo.Interface, fetcher RepoMetadataFetcher, state *IssueMetadataState, projectsV1Support gh.ProjectsV1Support) error {
isChosen := func(m string) bool {
for _, c := range state.Metadata {
if m == c {
return true
}
}
return false
}
allowReviewers := state.Type == PRMetadata
extraFieldsOptions := []string{}
if allowReviewers {
extraFieldsOptions = append(extraFieldsOptions, "Reviewers")
}
extraFieldsOptions = append(extraFieldsOptions, "Assignees", "Labels", "Projects", "Milestone")
selected, err := p.MultiSelect("What would you like to add?", nil, extraFieldsOptions)
if err != nil {
return err
}
for _, i := range selected {
state.Metadata = append(state.Metadata, extraFieldsOptions[i])
}
// Retrieve and process data for survey prompts based on the extra fields selected
metadataInput := api.RepoMetadataInput{
Reviewers: isChosen("Reviewers"),
TeamReviewers: isChosen("Reviewers"),
Assignees: isChosen("Assignees"),
ActorAssignees: isChosen("Assignees") && state.ActorAssignees,
Labels: isChosen("Labels"),
ProjectsV1: isChosen("Projects") && projectsV1Support == gh.ProjectsV1Supported,
ProjectsV2: isChosen("Projects"),
Milestones: isChosen("Milestone"),
}
metadataResult, err := fetcher.RepoMetadataFetch(metadataInput)
if err != nil {
return fmt.Errorf("error fetching metadata options: %w", err)
}
var reviewers []string
for _, u := range metadataResult.AssignableUsers {
if u.Login() != metadataResult.CurrentLogin {
reviewers = append(reviewers, u.DisplayName())
}
}
for _, t := range metadataResult.Teams {
reviewers = append(reviewers, fmt.Sprintf("%s/%s", baseRepo.RepoOwner(), t.Slug))
}
// Populate the list of selectable assignees and their default selections.
// This logic maps the default assignees from `state` to the corresponding actors or users
// so that the correct display names are preselected in the prompt.
var assignees []string
var assigneesDefault []string
if state.ActorAssignees {
for _, u := range metadataResult.AssignableActors {
assignees = append(assignees, u.DisplayName())
if slices.Contains(state.Assignees, u.Login()) {
assigneesDefault = append(assigneesDefault, u.DisplayName())
}
}
} else {
for _, u := range metadataResult.AssignableUsers {
assignees = append(assignees, u.DisplayName())
if slices.Contains(state.Assignees, u.Login()) {
assigneesDefault = append(assigneesDefault, u.DisplayName())
}
}
}
var labels []string
for _, l := range metadataResult.Labels {
labels = append(labels, l.Name)
}
var projects []string
for _, p := range metadataResult.Projects {
projects = append(projects, p.Name)
}
for _, p := range metadataResult.ProjectsV2 {
projects = append(projects, p.Title)
}
milestones := []string{noMilestone}
for _, m := range metadataResult.Milestones {
milestones = append(milestones, m.Title)
}
// Prompt user for additional metadata based on selected fields
values := struct {
Reviewers []string
Assignees []string
Labels []string
Projects []string
Milestone string
}{}
if isChosen("Reviewers") {
if len(reviewers) > 0 {
selected, err := p.MultiSelect("Reviewers", state.Reviewers, reviewers)
if err != nil {
return err
}
for _, i := range selected {
values.Reviewers = append(values.Reviewers, reviewers[i])
}
} else {
fmt.Fprintln(io.ErrOut, "warning: no available reviewers")
}
}
if isChosen("Assignees") {
if len(assignees) > 0 {
selected, err := p.MultiSelect("Assignees", assigneesDefault, assignees)
if err != nil {
return err
}
for _, i := range selected {
// Previously, this logic relied upon `assignees` being in `<login>` or `<login> (<name>)` form,
// however the inclusion of actors breaks this convention.
// Instead, we map the selected indexes to the source that populated `assignees` rather than
// relying on parsing the information out.
if state.ActorAssignees {
values.Assignees = append(values.Assignees, metadataResult.AssignableActors[i].Login())
} else {
values.Assignees = append(values.Assignees, metadataResult.AssignableUsers[i].Login())
}
}
} else {
fmt.Fprintln(io.ErrOut, "warning: no assignable users")
}
}
if isChosen("Labels") {
if len(labels) > 0 {
selected, err := p.MultiSelect("Labels", state.Labels, labels)
if err != nil {
return err
}
for _, i := range selected {
values.Labels = append(values.Labels, labels[i])
}
} else {
fmt.Fprintln(io.ErrOut, "warning: no labels in the repository")
}
}
if isChosen("Projects") {
if len(projects) > 0 {
selected, err := p.MultiSelect("Projects", state.ProjectTitles, projects)
if err != nil {
return err
}
for _, i := range selected {
values.Projects = append(values.Projects, projects[i])
}
} else {
fmt.Fprintln(io.ErrOut, "warning: no projects to choose from")
}
}
if isChosen("Milestone") {
if len(milestones) > 1 {
var milestoneDefault string
if len(state.Milestones) > 0 {
milestoneDefault = state.Milestones[0]
} else {
milestoneDefault = milestones[1]
}
selected, err := p.Select("Milestone", milestoneDefault, milestones)
if err != nil {
return err
}
values.Milestone = milestones[selected]
} else {
fmt.Fprintln(io.ErrOut, "warning: no milestones in the repository")
}
}
// Update issue / pull request metadata state
if isChosen("Reviewers") {
var logins []string
for _, r := range values.Reviewers {
// Extract user login from display name
logins = append(logins, (strings.Split(r, " "))[0])
}
state.Reviewers = logins
}
if isChosen("Assignees") {
state.Assignees = values.Assignees
}
if isChosen("Labels") {
state.Labels = values.Labels
}
if isChosen("Projects") {
state.ProjectTitles = values.Projects
}
if isChosen("Milestone") {
if values.Milestone != "" && values.Milestone != noMilestone {
state.Milestones = []string{values.Milestone}
} else {
state.Milestones = []string{}
}
}
return nil
}
type Editor interface {
Edit(filename, initialValue string) (string, error)
}
type UserEditor struct {
IO *iostreams.IOStreams
Config func() (gh.Config, error)
}
func (e *UserEditor) Edit(filename, initialValue string) (string, error) {
editorCommand, err := cmdutil.DetermineEditor(e.Config)
if err != nil {
return "", err
}
return surveyext.Edit(editorCommand, filename, initialValue, e.IO.In, e.IO.Out, e.IO.ErrOut)
}
const editorHintMarker = "------------------------ >8 ------------------------"
const editorHint = `
Please Enter the title on the first line and the body on subsequent lines.
Lines below dotted lines will be ignored, and an empty title aborts the creation process.`
func TitledEditSurvey(editor Editor) func(string, string) (string, string, error) {
return func(initialTitle, initialBody string) (string, string, error) {
initialValue := strings.Join([]string{initialTitle, initialBody, editorHintMarker, editorHint}, "\n")
titleAndBody, err := editor.Edit("*.md", initialValue)
if err != nil {
return "", "", err
}
titleAndBody = strings.ReplaceAll(titleAndBody, "\r\n", "\n")
titleAndBody, _, _ = strings.Cut(titleAndBody, editorHintMarker)
title, body, _ := strings.Cut(titleAndBody, "\n")
return title, strings.TrimSuffix(body, "\n"), nil
}
}
func InitEditorMode(f *cmdutil.Factory, editorMode bool, webMode bool, canPrompt bool) (bool, error) {
if err := cmdutil.MutuallyExclusive(
"specify only one of `--editor` or `--web`",
editorMode,
webMode,
); err != nil {
return false, err
}
config, err := f.Config()
if err != nil {
return false, err
}
editorMode = !webMode && (editorMode || config.PreferEditorPrompt("").Value == "enabled")
if editorMode && !canPrompt {
return false, errors.New("--editor or enabled prefer_editor_prompt configuration are not supported in non-tty mode")
}
return editorMode, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/shared/survey_test.go | pkg/cmd/pr/shared/survey_test.go | package shared
import (
"errors"
"testing"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/prompter"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type metadataFetcher struct {
metadataResult *api.RepoMetadataResult
}
func (mf *metadataFetcher) RepoMetadataFetch(input api.RepoMetadataInput) (*api.RepoMetadataResult, error) {
return mf.metadataResult, nil
}
func TestMetadataSurvey_selectAll(t *testing.T) {
ios, _, stdout, stderr := iostreams.Test()
repo := ghrepo.New("OWNER", "REPO")
fetcher := &metadataFetcher{
metadataResult: &api.RepoMetadataResult{
AssignableUsers: []api.AssignableUser{
api.NewAssignableUser("", "hubot", ""),
api.NewAssignableUser("", "monalisa", ""),
},
Labels: []api.RepoLabel{
{Name: "help wanted"},
{Name: "good first issue"},
},
Projects: []api.RepoProject{
{Name: "Huge Refactoring"},
{Name: "The road to 1.0"},
},
Milestones: []api.RepoMilestone{
{Title: "1.2 patch release"},
},
},
}
pm := prompter.NewMockPrompter(t)
pm.RegisterMultiSelect("What would you like to add?",
[]string{}, []string{"Reviewers", "Assignees", "Labels", "Projects", "Milestone"}, func(_ string, _, _ []string) ([]int, error) {
return []int{0, 1, 2, 3, 4}, nil
})
pm.RegisterMultiSelect("Reviewers", []string{}, []string{"hubot", "monalisa"}, func(_ string, _, _ []string) ([]int, error) {
return []int{1}, nil
})
pm.RegisterMultiSelect("Assignees", []string{}, []string{"hubot", "monalisa"}, func(_ string, _, _ []string) ([]int, error) {
return []int{0}, nil
})
pm.RegisterMultiSelect("Labels", []string{}, []string{"help wanted", "good first issue"}, func(_ string, _, _ []string) ([]int, error) {
return []int{1}, nil
})
pm.RegisterMultiSelect("Projects", []string{}, []string{"Huge Refactoring", "The road to 1.0"}, func(_ string, _, _ []string) ([]int, error) {
return []int{1}, nil
})
pm.RegisterSelect("Milestone", []string{"(none)", "1.2 patch release"}, func(_, _ string, _ []string) (int, error) {
return 0, nil
})
state := &IssueMetadataState{
Assignees: []string{"hubot"},
Type: PRMetadata,
}
err := MetadataSurvey(pm, ios, repo, fetcher, state, gh.ProjectsV1Supported)
assert.NoError(t, err)
assert.Equal(t, "", stdout.String())
assert.Equal(t, "", stderr.String())
assert.Equal(t, []string{"hubot"}, state.Assignees)
assert.Equal(t, []string{"monalisa"}, state.Reviewers)
assert.Equal(t, []string{"good first issue"}, state.Labels)
assert.Equal(t, []string{"The road to 1.0"}, state.ProjectTitles)
assert.Equal(t, []string{}, state.Milestones)
}
func TestMetadataSurvey_keepExisting(t *testing.T) {
ios, _, stdout, stderr := iostreams.Test()
repo := ghrepo.New("OWNER", "REPO")
fetcher := &metadataFetcher{
metadataResult: &api.RepoMetadataResult{
Labels: []api.RepoLabel{
{Name: "help wanted"},
{Name: "good first issue"},
},
Projects: []api.RepoProject{
{Name: "Huge Refactoring"},
{Name: "The road to 1.0"},
},
},
}
pm := prompter.NewMockPrompter(t)
pm.RegisterMultiSelect("What would you like to add?", []string{}, []string{"Assignees", "Labels", "Projects", "Milestone"}, func(_ string, _, _ []string) ([]int, error) {
return []int{1, 2}, nil
})
pm.RegisterMultiSelect("Labels", []string{}, []string{"help wanted", "good first issue"}, func(_ string, _, _ []string) ([]int, error) {
return []int{1}, nil
})
pm.RegisterMultiSelect("Projects", []string{}, []string{"Huge Refactoring", "The road to 1.0"}, func(_ string, _, _ []string) ([]int, error) {
return []int{1}, nil
})
state := &IssueMetadataState{
Assignees: []string{"hubot"},
}
err := MetadataSurvey(pm, ios, repo, fetcher, state, gh.ProjectsV1Supported)
assert.NoError(t, err)
assert.Equal(t, "", stdout.String())
assert.Equal(t, "", stderr.String())
assert.Equal(t, []string{"hubot"}, state.Assignees)
assert.Equal(t, []string{"good first issue"}, state.Labels)
assert.Equal(t, []string{"The road to 1.0"}, state.ProjectTitles)
}
// TODO projectsV1Deprecation
// Remove this test and projectsV1MetadataFetcherSpy
func TestMetadataSurveyProjectV1Deprecation(t *testing.T) {
t.Run("when projectsV1 is supported, requests projectsV1", func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
repo := ghrepo.New("OWNER", "REPO")
fetcher := &projectsV1MetadataFetcherSpy{}
pm := prompter.NewMockPrompter(t)
pm.RegisterMultiSelect("What would you like to add?", []string{}, []string{"Assignees", "Labels", "Projects", "Milestone"}, func(_ string, _, options []string) ([]int, error) {
i, err := prompter.IndexFor(options, "Projects")
require.NoError(t, err)
return []int{i}, nil
})
pm.RegisterMultiSelect("Projects", []string{}, []string{"Huge Refactoring"}, func(_ string, _, _ []string) ([]int, error) {
return []int{0}, nil
})
err := MetadataSurvey(pm, ios, repo, fetcher, &IssueMetadataState{}, gh.ProjectsV1Supported)
require.ErrorContains(t, err, "expected test error")
require.True(t, fetcher.projectsV1Requested, "expected projectsV1 to be requested")
})
t.Run("when projectsV1 is supported, does not request projectsV1", func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
repo := ghrepo.New("OWNER", "REPO")
fetcher := &projectsV1MetadataFetcherSpy{}
pm := prompter.NewMockPrompter(t)
pm.RegisterMultiSelect("What would you like to add?", []string{}, []string{"Assignees", "Labels", "Projects", "Milestone"}, func(_ string, _, options []string) ([]int, error) {
i, err := prompter.IndexFor(options, "Projects")
require.NoError(t, err)
return []int{i}, nil
})
pm.RegisterMultiSelect("Projects", []string{}, []string{"Huge Refactoring"}, func(_ string, _, _ []string) ([]int, error) {
return []int{0}, nil
})
err := MetadataSurvey(pm, ios, repo, fetcher, &IssueMetadataState{}, gh.ProjectsV1Unsupported)
require.ErrorContains(t, err, "expected test error")
require.False(t, fetcher.projectsV1Requested, "expected projectsV1 not to be requested")
})
}
type projectsV1MetadataFetcherSpy struct {
projectsV1Requested bool
}
func (mf *projectsV1MetadataFetcherSpy) RepoMetadataFetch(input api.RepoMetadataInput) (*api.RepoMetadataResult, error) {
if input.ProjectsV1 {
mf.projectsV1Requested = true
}
return nil, errors.New("expected test error")
}
func TestTitledEditSurvey_cleanupHint(t *testing.T) {
var editorInitialText string
editor := &testEditor{
edit: func(s string) (string, error) {
editorInitialText = s
return `editedTitle
editedBody
------------------------ >8 ------------------------
Please Enter the title on the first line and the body on subsequent lines.
Lines below dotted lines will be ignored, and an empty title aborts the creation process.`, nil
},
}
title, body, err := TitledEditSurvey(editor)("initialTitle", "initialBody")
assert.NoError(t, err)
assert.Equal(t, `initialTitle
initialBody
------------------------ >8 ------------------------
Please Enter the title on the first line and the body on subsequent lines.
Lines below dotted lines will be ignored, and an empty title aborts the creation process.`, editorInitialText)
assert.Equal(t, "editedTitle", title)
assert.Equal(t, "editedBody", body)
}
type testEditor struct {
edit func(string) (string, error)
}
func (e testEditor) Edit(filename, text string) (string, error) {
return e.edit(text)
}
func TestTitleSurvey(t *testing.T) {
tests := []struct {
name string
prompterMockInputs []string
expectedTitle string
expectStderr bool
}{
{
name: "title provided",
prompterMockInputs: []string{"title"},
expectedTitle: "title",
},
{
name: "first input empty",
prompterMockInputs: []string{"", "title"},
expectedTitle: "title",
expectStderr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
io, _, _, stderr := iostreams.Test()
pm := prompter.NewMockPrompter(t)
for _, input := range tt.prompterMockInputs {
pm.RegisterInput("Title (required)", func(string, string) (string, error) {
return input, nil
})
}
state := &IssueMetadataState{}
err := TitleSurvey(pm, io, state)
assert.NoError(t, err)
assert.Equal(t, tt.expectedTitle, state.Title)
if tt.expectStderr {
assert.Equal(t, "X Title cannot be blank\n", stderr.String())
}
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/shared/comments.go | pkg/cmd/pr/shared/comments.go | package shared
import (
"fmt"
"sort"
"strings"
"time"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/pkg/markdown"
)
type Comment interface {
Identifier() string
AuthorLogin() string
Association() string
Content() string
Created() time.Time
HiddenReason() string
IsEdited() bool
IsHidden() bool
Link() string
Reactions() api.ReactionGroups
Status() string
}
func RawCommentList(comments api.Comments, reviews api.PullRequestReviews) string {
sortedComments := sortComments(comments, reviews)
var b strings.Builder
for _, comment := range sortedComments {
fmt.Fprint(&b, formatRawComment(comment))
}
return b.String()
}
func formatRawComment(comment Comment) string {
if comment.IsHidden() {
return ""
}
var b strings.Builder
fmt.Fprintf(&b, "author:\t%s\n", comment.AuthorLogin())
fmt.Fprintf(&b, "association:\t%s\n", strings.ToLower(comment.Association()))
fmt.Fprintf(&b, "edited:\t%t\n", comment.IsEdited())
fmt.Fprintf(&b, "status:\t%s\n", formatRawCommentStatus(comment.Status()))
fmt.Fprintln(&b, "--")
fmt.Fprintln(&b, comment.Content())
fmt.Fprintln(&b, "--")
return b.String()
}
func CommentList(io *iostreams.IOStreams, comments api.Comments, reviews api.PullRequestReviews, preview bool) (string, error) {
sortedComments := sortComments(comments, reviews)
if preview && len(sortedComments) > 0 {
sortedComments = sortedComments[len(sortedComments)-1:]
}
var b strings.Builder
cs := io.ColorScheme()
totalCount := comments.TotalCount + reviews.TotalCount
retrievedCount := len(sortedComments)
hiddenCount := totalCount - retrievedCount
if preview && hiddenCount > 0 {
fmt.Fprint(&b, cs.Muted(fmt.Sprintf("ββββββββ Not showing %s ββββββββ", text.Pluralize(hiddenCount, "comment"))))
fmt.Fprintf(&b, "\n\n\n")
}
for i, comment := range sortedComments {
last := i+1 == retrievedCount
cmt, err := formatComment(io, comment, last)
if err != nil {
return "", err
}
fmt.Fprint(&b, cmt)
if last {
fmt.Fprintln(&b)
}
}
if preview && hiddenCount > 0 {
fmt.Fprint(&b, cs.Muted("Use --comments to view the full conversation"))
fmt.Fprintln(&b)
}
return b.String(), nil
}
func formatComment(io *iostreams.IOStreams, comment Comment, newest bool) (string, error) {
var b strings.Builder
cs := io.ColorScheme()
if comment.IsHidden() {
return cs.Bold(formatHiddenComment(comment)), nil
}
// Header
fmt.Fprint(&b, cs.Bold(comment.AuthorLogin()))
if comment.Status() != "" {
fmt.Fprint(&b, formatCommentStatus(cs, comment.Status()))
}
if comment.Association() != "NONE" {
fmt.Fprint(&b, cs.Boldf(" (%s)", text.Title(comment.Association())))
}
fmt.Fprint(&b, cs.Boldf(" β’ %s", text.FuzzyAgoAbbr(time.Now(), comment.Created())))
if comment.IsEdited() {
fmt.Fprint(&b, cs.Bold(" β’ Edited"))
}
if newest {
fmt.Fprint(&b, cs.Bold(" β’ "))
fmt.Fprint(&b, cs.CyanBold("Newest comment"))
}
fmt.Fprintln(&b)
// Reactions
if reactions := ReactionGroupList(comment.Reactions()); reactions != "" {
fmt.Fprint(&b, reactions)
fmt.Fprintln(&b)
}
// Body
var md string
var err error
if comment.Content() == "" {
md = fmt.Sprintf("\n %s\n\n", cs.Muted("No body provided"))
} else {
md, err = markdown.Render(comment.Content(),
markdown.WithTheme(io.TerminalTheme()),
markdown.WithWrap(io.TerminalWidth()))
if err != nil {
return "", err
}
}
fmt.Fprint(&b, md)
// Footer
if comment.Link() != "" {
fmt.Fprintf(&b, cs.Muted("View the full review: %s\n\n"), comment.Link())
}
return b.String(), nil
}
func sortComments(cs api.Comments, rs api.PullRequestReviews) []Comment {
comments := cs.Nodes
reviews := rs.Nodes
var sorted []Comment = make([]Comment, len(comments)+len(reviews))
var i int
for _, c := range comments {
sorted[i] = c
i++
}
for _, r := range reviews {
sorted[i] = r
i++
}
sort.Slice(sorted, func(i, j int) bool {
return sorted[i].Created().Before(sorted[j].Created())
})
return sorted
}
const (
approvedStatus = "APPROVED"
changesRequestedStatus = "CHANGES_REQUESTED"
commentedStatus = "COMMENTED"
dismissedStatus = "DISMISSED"
)
func formatCommentStatus(cs *iostreams.ColorScheme, status string) string {
switch status {
case approvedStatus:
return fmt.Sprintf(" %s", cs.Green("approved"))
case changesRequestedStatus:
return fmt.Sprintf(" %s", cs.Red("requested changes"))
case commentedStatus, dismissedStatus:
return fmt.Sprintf(" %s", strings.ToLower(status))
}
return ""
}
func formatRawCommentStatus(status string) string {
if status == approvedStatus ||
status == changesRequestedStatus ||
status == commentedStatus ||
status == dismissedStatus {
return strings.ReplaceAll(strings.ToLower(status), "_", " ")
}
return "none"
}
func formatHiddenComment(comment Comment) string {
var b strings.Builder
fmt.Fprint(&b, comment.AuthorLogin())
if comment.Association() != "NONE" {
fmt.Fprintf(&b, " (%s)", text.Title(comment.Association()))
}
fmt.Fprintf(&b, " β’ This comment has been marked as %s\n\n", comment.HiddenReason())
return b.String()
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/shared/reaction_groups.go | pkg/cmd/pr/shared/reaction_groups.go | package shared
import (
"fmt"
"strings"
"github.com/cli/cli/v2/api"
)
func ReactionGroupList(rgs api.ReactionGroups) string {
var rs []string
for _, rg := range rgs {
if r := formatReactionGroup(rg); r != "" {
rs = append(rs, r)
}
}
return strings.Join(rs, " β’ ")
}
func formatReactionGroup(rg api.ReactionGroup) string {
c := rg.Count()
if c == 0 {
return ""
}
e := rg.Emoji()
if e == "" {
return ""
}
return fmt.Sprintf("%v %s", c, e)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/shared/state.go | pkg/cmd/pr/shared/state.go | package shared
import (
"encoding/json"
"fmt"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/pkg/iostreams"
)
type metadataStateType int
const (
IssueMetadata metadataStateType = iota
PRMetadata
)
type IssueMetadataState struct {
Type metadataStateType
Draft bool
ActorAssignees bool
Body string
Title string
Template string
Metadata []string
Reviewers []string
Assignees []string
Labels []string
ProjectTitles []string
Milestones []string
MetadataResult *api.RepoMetadataResult
dirty bool // whether user i/o has modified this
}
func (tb *IssueMetadataState) MarkDirty() {
tb.dirty = true
}
func (tb *IssueMetadataState) IsDirty() bool {
return tb.dirty || tb.HasMetadata()
}
func (tb *IssueMetadataState) HasMetadata() bool {
return len(tb.Reviewers) > 0 ||
len(tb.Assignees) > 0 ||
len(tb.Labels) > 0 ||
len(tb.ProjectTitles) > 0 ||
len(tb.Milestones) > 0
}
func FillFromJSON(io *iostreams.IOStreams, recoverFile string, state *IssueMetadataState) error {
var data []byte
var err error
data, err = io.ReadUserFile(recoverFile)
if err != nil {
return fmt.Errorf("failed to read file %s: %w", recoverFile, err)
}
err = json.Unmarshal(data, state)
if err != nil {
return fmt.Errorf("JSON parsing failure: %w", err)
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/shared/completion_test.go | pkg/cmd/pr/shared/completion_test.go | package shared
import (
"net/http"
"testing"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/stretchr/testify/require"
)
func TestRequestableReviewersForCompletion(t *testing.T) {
tests := []struct {
name string
expectedReviewers []string
httpStubs func(*httpmock.Registry, *testing.T)
}{
{
name: "when users and teams are both available, both are listed",
expectedReviewers: []string{"MonaLisa\tMona Display Name", "OWNER/core", "OWNER/robots", "hubot"},
httpStubs: func(reg *httpmock.Registry, t *testing.T) {
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data": {"viewer": {"login": "OWNER"} } }`))
reg.Register(
httpmock.GraphQL(`query RepositoryAssignableUsers\b`),
httpmock.StringResponse(`
{ "data": { "repository": { "assignableUsers": {
"nodes": [
{ "login": "hubot", "id": "HUBOTID", "name": "" },
{ "login": "MonaLisa", "id": "MONAID", "name": "Mona Display Name" }
],
"pageInfo": { "hasNextPage": false }
} } } }
`))
reg.Register(
httpmock.GraphQL(`query OrganizationTeamList\b`),
httpmock.StringResponse(`
{ "data": { "organization": { "teams": {
"nodes": [
{ "slug": "core", "id": "COREID" },
{ "slug": "robots", "id": "ROBOTID" }
],
"pageInfo": { "hasNextPage": false }
} } } }
`))
},
},
{
name: "when users are available but teams aren't, users are listed",
expectedReviewers: []string{"MonaLisa\tMona Display Name", "hubot"},
httpStubs: func(reg *httpmock.Registry, t *testing.T) {
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data": {"viewer": {"login": "OWNER"} } }`))
reg.Register(
httpmock.GraphQL(`query RepositoryAssignableUsers\b`),
httpmock.StringResponse(`
{ "data": { "repository": { "assignableUsers": {
"nodes": [
{ "login": "hubot", "id": "HUBOTID", "name": "" },
{ "login": "MonaLisa", "id": "MONAID", "name": "Mona Display Name" }
],
"pageInfo": { "hasNextPage": false }
} } } }
`))
reg.Register(
httpmock.GraphQL(`query OrganizationTeamList\b`),
httpmock.StringResponse(`
{ "data": { "organization": { "teams": {
"nodes": [],
"pageInfo": { "hasNextPage": false }
} } } }
`))
},
},
{
name: "when teams are available but users aren't, teams are listed",
expectedReviewers: []string{"OWNER/core", "OWNER/robots"},
httpStubs: func(reg *httpmock.Registry, t *testing.T) {
reg.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`{"data": {"viewer": {"login": "OWNER"} } }`))
reg.Register(
httpmock.GraphQL(`query RepositoryAssignableUsers\b`),
httpmock.StringResponse(`
{ "data": { "repository": { "assignableUsers": {
"nodes": [],
"pageInfo": { "hasNextPage": false }
} } } }
`))
reg.Register(
httpmock.GraphQL(`query OrganizationTeamList\b`),
httpmock.StringResponse(`
{ "data": { "organization": { "teams": {
"nodes": [
{ "slug": "core", "id": "COREID" },
{ "slug": "robots", "id": "ROBOTID" }
],
"pageInfo": { "hasNextPage": false }
} } } }
`))
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
defer reg.Verify(t)
if tt.httpStubs != nil {
tt.httpStubs(reg, t)
}
reviewers, err := RequestableReviewersForCompletion(&http.Client{Transport: reg}, ghrepo.New("OWNER", "REPO"))
require.NoError(t, err)
require.Equal(t, tt.expectedReviewers, reviewers)
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/shared/params.go | pkg/cmd/pr/shared/params.go | package shared
import (
"fmt"
"net/url"
"slices"
"strings"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/search"
"github.com/google/shlex"
)
func WithPrAndIssueQueryParams(client *api.Client, baseRepo ghrepo.Interface, baseURL string, state IssueMetadataState, projectsV1Support gh.ProjectsV1Support) (string, error) {
u, err := url.Parse(baseURL)
if err != nil {
return "", err
}
q := u.Query()
if state.Title != "" {
q.Set("title", state.Title)
}
// We always want to send the body parameter, even if it's empty, to prevent the web interface from
// applying the default template. Since the user has the option to select a template in the terminal,
// assume that empty body here means that the user either skipped it or erased its contents.
q.Set("body", state.Body)
if len(state.Assignees) > 0 {
q.Set("assignees", strings.Join(state.Assignees, ","))
}
// Set a template parameter if no body parameter is provided e.g. Web Mode
if len(state.Template) > 0 && len(state.Body) == 0 {
q.Set("template", state.Template)
}
if len(state.Labels) > 0 {
q.Set("labels", strings.Join(state.Labels, ","))
}
if len(state.ProjectTitles) > 0 {
projectPaths, err := api.ProjectTitlesToPaths(client, baseRepo, state.ProjectTitles, projectsV1Support)
if err != nil {
return "", fmt.Errorf("could not add to project: %w", err)
}
q.Set("projects", strings.Join(projectPaths, ","))
}
if len(state.Milestones) > 0 {
q.Set("milestone", state.Milestones[0])
}
u.RawQuery = q.Encode()
return u.String(), nil
}
// Maximum length of a URL: 8192 bytes
func ValidURL(urlStr string) bool {
return len(urlStr) < 8192
}
func AddMetadataToIssueParams(client *api.Client, baseRepo ghrepo.Interface, params map[string]interface{}, tb *IssueMetadataState, projectV1Support gh.ProjectsV1Support) error {
if !tb.HasMetadata() {
return nil
}
// Retrieve minimal information needed to resolve metadata if this was not previously cached from additional metadata survey.
if tb.MetadataResult == nil {
input := api.RepoMetadataInput{
Reviewers: len(tb.Reviewers) > 0,
TeamReviewers: len(tb.Reviewers) > 0 && slices.ContainsFunc(tb.Reviewers, func(r string) bool {
return strings.ContainsRune(r, '/')
}),
Assignees: len(tb.Assignees) > 0,
ActorAssignees: tb.ActorAssignees,
Labels: len(tb.Labels) > 0,
ProjectsV1: len(tb.ProjectTitles) > 0 && projectV1Support == gh.ProjectsV1Supported,
ProjectsV2: len(tb.ProjectTitles) > 0,
Milestones: len(tb.Milestones) > 0,
}
metadataResult, err := api.RepoMetadata(client, baseRepo, input)
if err != nil {
return err
}
tb.MetadataResult = metadataResult
}
assigneeIDs, err := tb.MetadataResult.MembersToIDs(tb.Assignees)
if err != nil {
return fmt.Errorf("could not assign user: %w", err)
}
params["assigneeIds"] = assigneeIDs
labelIDs, err := tb.MetadataResult.LabelsToIDs(tb.Labels)
if err != nil {
return fmt.Errorf("could not add label: %w", err)
}
params["labelIds"] = labelIDs
projectIDs, projectV2IDs, err := tb.MetadataResult.ProjectsTitlesToIDs(tb.ProjectTitles)
if err != nil {
return fmt.Errorf("could not add to project: %w", err)
}
params["projectIds"] = projectIDs
params["projectV2Ids"] = projectV2IDs
if len(tb.Milestones) > 0 {
milestoneID, err := tb.MetadataResult.MilestoneToID(tb.Milestones[0])
if err != nil {
return fmt.Errorf("could not add to milestone '%s': %w", tb.Milestones[0], err)
}
params["milestoneId"] = milestoneID
}
if len(tb.Reviewers) == 0 {
return nil
}
var userReviewers []string
var teamReviewers []string
for _, r := range tb.Reviewers {
if strings.ContainsRune(r, '/') {
teamReviewers = append(teamReviewers, r)
} else {
userReviewers = append(userReviewers, r)
}
}
userReviewerIDs, err := tb.MetadataResult.MembersToIDs(userReviewers)
if err != nil {
return fmt.Errorf("could not request reviewer: %w", err)
}
params["userReviewerIds"] = userReviewerIDs
teamReviewerIDs, err := tb.MetadataResult.TeamsToIDs(teamReviewers)
if err != nil {
return fmt.Errorf("could not request reviewer: %w", err)
}
params["teamReviewerIds"] = teamReviewerIDs
return nil
}
type FilterOptions struct {
Assignee string
Author string
BaseBranch string
Draft *bool
Entity string
Fields []string
HeadBranch string
Labels []string
Mention string
Milestone string
Repo string
Search string
State string
}
func (opts *FilterOptions) IsDefault() bool {
if opts.State != "open" {
return false
}
if len(opts.Labels) > 0 {
return false
}
if opts.Assignee != "" {
return false
}
if opts.Author != "" {
return false
}
if opts.BaseBranch != "" {
return false
}
if opts.HeadBranch != "" {
return false
}
if opts.Mention != "" {
return false
}
if opts.Milestone != "" {
return false
}
if opts.Search != "" {
return false
}
return true
}
func ListURLWithQuery(listURL string, options FilterOptions, advancedIssueSearchSyntax bool) (string, error) {
u, err := url.Parse(listURL)
if err != nil {
return "", err
}
params := u.Query()
params.Set("q", SearchQueryBuild(options, advancedIssueSearchSyntax))
u.RawQuery = params.Encode()
return u.String(), nil
}
func SearchQueryBuild(options FilterOptions, advancedIssueSearchSyntax bool) string {
var is, state string
switch options.State {
case "open", "closed":
state = options.State
case "merged":
is = "merged"
}
query := search.Query{
Qualifiers: search.Qualifiers{
Assignee: options.Assignee,
Author: options.Author,
Base: options.BaseBranch,
Draft: options.Draft,
Head: options.HeadBranch,
Label: options.Labels,
Mentions: options.Mention,
Milestone: options.Milestone,
Repo: []string{options.Repo},
State: state,
Is: []string{is},
Type: options.Entity,
},
ImmutableKeywords: options.Search,
}
if !advancedIssueSearchSyntax {
return query.StandardSearchString()
}
return query.AdvancedIssueSearchString()
}
func QueryHasStateClause(searchQuery string) bool {
argv, err := shlex.Split(searchQuery)
if err != nil {
return false
}
for _, arg := range argv {
if arg == "is:closed" || arg == "is:merged" || arg == "state:closed" || arg == "state:merged" || strings.HasPrefix(arg, "merged:") || strings.HasPrefix(arg, "closed:") {
return true
}
}
return false
}
// MeReplacer resolves usages of `@me` to the handle of the currently logged in user.
type MeReplacer struct {
apiClient *api.Client
hostname string
login string
}
func NewMeReplacer(apiClient *api.Client, hostname string) *MeReplacer {
return &MeReplacer{
apiClient: apiClient,
hostname: hostname,
}
}
func (r *MeReplacer) currentLogin() (string, error) {
if r.login != "" {
return r.login, nil
}
login, err := api.CurrentLoginName(r.apiClient, r.hostname)
if err != nil {
return "", fmt.Errorf("failed resolving `@me` to your user handle: %w", err)
}
r.login = login
return login, nil
}
func (r *MeReplacer) Replace(handle string) (string, error) {
if handle == "@me" {
return r.currentLogin()
}
return handle, nil
}
func (r *MeReplacer) ReplaceSlice(handles []string) ([]string, error) {
res := make([]string, len(handles))
for i, h := range handles {
var err error
res[i], err = r.Replace(h)
if err != nil {
return nil, err
}
}
return res, nil
}
// CopilotReplacer resolves usages of `@copilot` to either Copilot's login or name.
// Login is generally needed for API calls; name is used when launching web browser.
type CopilotReplacer struct {
returnLogin bool
}
func NewCopilotReplacer(returnLogin bool) *CopilotReplacer {
return &CopilotReplacer{
returnLogin: returnLogin,
}
}
func (r *CopilotReplacer) replace(handle string) string {
if !strings.EqualFold(handle, "@copilot") {
return handle
}
if r.returnLogin {
return api.CopilotActorLogin
}
return api.CopilotActorName
}
// ReplaceSlice replaces usages of `@copilot` in a slice with Copilot's login.
func (r *CopilotReplacer) ReplaceSlice(handles []string) []string {
res := make([]string, len(handles))
for i, h := range handles {
res[i] = r.replace(h)
}
return res
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/shared/preserve_test.go | pkg/cmd/pr/shared/preserve_test.go | package shared
import (
"encoding/json"
"errors"
"io"
"os"
"testing"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/test"
"github.com/stretchr/testify/assert"
)
func Test_PreserveInput(t *testing.T) {
tests := []struct {
name string
state *IssueMetadataState
err bool
wantErrLine string
wantPreservation bool
}{
{
name: "err, no changes to state",
err: true,
},
{
name: "no err, no changes to state",
err: false,
},
{
name: "no err, changes to state",
state: &IssueMetadataState{
dirty: true,
},
},
{
name: "err, title/body input received",
state: &IssueMetadataState{
dirty: true,
Title: "almost a",
Body: "jill sandwich",
Reviewers: []string{"barry", "chris"},
Labels: []string{"sandwich"},
},
wantErrLine: `X operation failed. To restore: gh issue create --recover .*testfile.*`,
err: true,
wantPreservation: true,
},
{
name: "err, metadata received",
state: &IssueMetadataState{
Reviewers: []string{"barry", "chris"},
Labels: []string{"sandwich"},
},
wantErrLine: `X operation failed. To restore: gh issue create --recover .*testfile.*`,
err: true,
wantPreservation: true,
},
{
name: "err, dirty, pull request",
state: &IssueMetadataState{
dirty: true,
Title: "a pull request",
Type: PRMetadata,
},
wantErrLine: `X operation failed. To restore: gh pr create --recover .*testfile.*`,
err: true,
wantPreservation: true,
},
}
tempDir := t.TempDir()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.state == nil {
tt.state = &IssueMetadataState{}
}
ios, _, _, errOut := iostreams.Test()
tf, tferr := os.CreateTemp(tempDir, "testfile*")
assert.NoError(t, tferr)
defer tf.Close()
ios.TempFileOverride = tf
var err error
if tt.err {
err = errors.New("error during creation")
}
PreserveInput(ios, tt.state, &err)()
_, err = tf.Seek(0, 0)
assert.NoError(t, err)
data, err := io.ReadAll(tf)
assert.NoError(t, err)
if tt.wantPreservation {
//nolint:staticcheck // prefer exact matchers over ExpectLines
test.ExpectLines(t, errOut.String(), tt.wantErrLine)
preserved := &IssueMetadataState{}
assert.NoError(t, json.Unmarshal(data, preserved))
preserved.dirty = tt.state.dirty
assert.Equal(t, preserved, tt.state)
} else {
assert.Equal(t, errOut.String(), "")
assert.Equal(t, string(data), "")
}
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/shared/display_test.go | pkg/cmd/pr/shared/display_test.go | package shared
import (
"testing"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/stretchr/testify/assert"
)
func Test_listHeader(t *testing.T) {
type args struct {
repoName string
itemName string
matchCount int
totalMatchCount int
hasFilters bool
}
tests := []struct {
name string
args args
want string
}{
{
name: "one result",
args: args{
repoName: "REPO",
itemName: "genie",
matchCount: 1,
totalMatchCount: 23,
hasFilters: false,
},
want: "Showing 1 of 23 open genies in REPO",
},
{
name: "one result after filters",
args: args{
repoName: "REPO",
itemName: "tiny cup",
matchCount: 1,
totalMatchCount: 23,
hasFilters: true,
},
want: "Showing 1 of 23 tiny cups in REPO that match your search",
},
{
name: "one result in total",
args: args{
repoName: "REPO",
itemName: "chip",
matchCount: 1,
totalMatchCount: 1,
hasFilters: false,
},
want: "Showing 1 of 1 open chip in REPO",
},
{
name: "one result in total after filters",
args: args{
repoName: "REPO",
itemName: "spicy noodle",
matchCount: 1,
totalMatchCount: 1,
hasFilters: true,
},
want: "Showing 1 of 1 spicy noodle in REPO that matches your search",
},
{
name: "multiple results",
args: args{
repoName: "REPO",
itemName: "plant",
matchCount: 4,
totalMatchCount: 23,
hasFilters: false,
},
want: "Showing 4 of 23 open plants in REPO",
},
{
name: "multiple results after filters",
args: args{
repoName: "REPO",
itemName: "boomerang",
matchCount: 4,
totalMatchCount: 23,
hasFilters: true,
},
want: "Showing 4 of 23 boomerangs in REPO that match your search",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := ListHeader(tt.args.repoName, tt.args.itemName, tt.args.matchCount, tt.args.totalMatchCount, tt.args.hasFilters); got != tt.want {
t.Errorf("listHeader() = %v, want %v", got, tt.want)
}
})
}
}
func TestPrCheckStatusSummaryWithColor(t *testing.T) {
testCases := []struct {
Name string
args api.PullRequestChecksStatus
want string
}{
{
Name: "No Checks",
args: api.PullRequestChecksStatus{
Total: 0,
Failing: 0,
Passing: 0,
Pending: 0,
},
want: "No checks",
},
{
Name: "All Passing",
args: api.PullRequestChecksStatus{
Total: 3,
Failing: 0,
Passing: 3,
Pending: 0,
},
want: "β Checks passing",
},
{
Name: "Some pending",
args: api.PullRequestChecksStatus{
Total: 3,
Failing: 0,
Passing: 1,
Pending: 2,
},
want: "- Checks pending",
},
{
Name: "Sll failing",
args: api.PullRequestChecksStatus{
Total: 3,
Failing: 3,
Passing: 0,
Pending: 0,
},
want: "Γ All checks failing",
},
{
Name: "Some failing",
args: api.PullRequestChecksStatus{
Total: 3,
Failing: 2,
Passing: 1,
Pending: 0,
},
want: "Γ 2/3 checks failing",
},
}
ios, _, _, _ := iostreams.Test()
ios.SetStdoutTTY(true)
ios.SetAlternateScreenBufferEnabled(true)
cs := ios.ColorScheme()
for _, testCase := range testCases {
out := PrCheckStatusSummaryWithColor(cs, testCase.args)
assert.Equal(t, testCase.want, out)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/shared/display.go | pkg/cmd/pr/shared/display.go | package shared
import (
"fmt"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
)
func StateTitleWithColor(cs *iostreams.ColorScheme, pr api.PullRequest) string {
prStateColorFunc := cs.ColorFromString(ColorForPRState(pr))
if pr.State == "OPEN" && pr.IsDraft {
return prStateColorFunc("Draft")
}
return prStateColorFunc(text.Title(pr.State))
}
func PrStateWithDraft(pr *api.PullRequest) string {
if pr.IsDraft && pr.State == "OPEN" {
return "DRAFT"
}
return pr.State
}
func ColorForPRState(pr api.PullRequest) string {
switch pr.State {
case "OPEN":
if pr.IsDraft {
return "gray"
}
return "green"
case "CLOSED":
return "red"
case "MERGED":
return "magenta"
default:
return ""
}
}
func ColorForIssueState(issue api.Issue) string {
switch issue.State {
case "OPEN":
return "green"
case "CLOSED":
if issue.StateReason == "NOT_PLANNED" {
return "gray"
}
return "magenta"
default:
return ""
}
}
func PrintHeader(io *iostreams.IOStreams, s string) {
fmt.Fprintln(io.Out, io.ColorScheme().Bold(s))
}
func PrintMessage(io *iostreams.IOStreams, s string) {
fmt.Fprintln(io.Out, io.ColorScheme().Muted(s))
}
func ListNoResults(repoName string, itemName string, hasFilters bool) error {
if hasFilters {
return cmdutil.NewNoResultsError(fmt.Sprintf("no %ss match your search in %s", itemName, repoName))
}
return cmdutil.NewNoResultsError(fmt.Sprintf("no open %ss in %s", itemName, repoName))
}
func ListHeader(repoName string, itemName string, matchCount int, totalMatchCount int, hasFilters bool) string {
if hasFilters {
matchVerb := "match"
if totalMatchCount == 1 {
matchVerb = "matches"
}
return fmt.Sprintf("Showing %d of %s in %s that %s your search", matchCount, text.Pluralize(totalMatchCount, itemName), repoName, matchVerb)
}
return fmt.Sprintf("Showing %d of %s in %s", matchCount, text.Pluralize(totalMatchCount, fmt.Sprintf("open %s", itemName)), repoName)
}
func PrCheckStatusSummaryWithColor(cs *iostreams.ColorScheme, checks api.PullRequestChecksStatus) string {
var summary = cs.Muted("No checks")
if checks.Total > 0 {
if checks.Failing > 0 {
if checks.Failing == checks.Total {
summary = cs.Red("Γ All checks failing")
} else {
summary = cs.Redf("Γ %d/%d checks failing", checks.Failing, checks.Total)
}
} else if checks.Pending > 0 {
summary = cs.Yellow("- Checks pending")
} else if checks.Passing == checks.Total {
summary = cs.Green("β Checks passing")
}
}
return summary
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/shared/editable.go | pkg/cmd/pr/shared/editable.go | package shared
import (
"fmt"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/set"
)
type Editable struct {
Title EditableString
Body EditableString
Base EditableString
Reviewers EditableSlice
Assignees EditableAssignees
Labels EditableSlice
Projects EditableProjects
Milestone EditableString
Metadata api.RepoMetadataResult
}
type EditableString struct {
Value string
Default string
Options []string
Edited bool
}
type EditableSlice struct {
Value []string
Add []string
Remove []string
Default []string
Options []string
Edited bool
Allowed bool
}
// EditableAssignees is a special case of EditableSlice.
// It contains a flag to indicate whether the assignees are actors or not.
type EditableAssignees struct {
EditableSlice
ActorAssignees bool
DefaultLogins []string // For disambiguating actors from display names
}
// ProjectsV2 mutations require a mapping of an item ID to a project ID.
// Keep that map along with standard EditableSlice data.
type EditableProjects struct {
EditableSlice
ProjectItems map[string]string
}
func (e Editable) Dirty() bool {
return e.Title.Edited ||
e.Body.Edited ||
e.Base.Edited ||
e.Reviewers.Edited ||
e.Assignees.Edited ||
e.Labels.Edited ||
e.Projects.Edited ||
e.Milestone.Edited
}
func (e Editable) TitleValue() *string {
if !e.Title.Edited {
return nil
}
return &e.Title.Value
}
func (e Editable) BodyValue() *string {
if !e.Body.Edited {
return nil
}
return &e.Body.Value
}
func (e Editable) AssigneeIds(client *api.Client, repo ghrepo.Interface) (*[]string, error) {
if !e.Assignees.Edited {
return nil, nil
}
// If assignees came in from command line flags, we need to
// curate the final list of assignees from the default list.
if len(e.Assignees.Add) != 0 || len(e.Assignees.Remove) != 0 {
meReplacer := NewMeReplacer(client, repo.RepoHost())
copilotReplacer := NewCopilotReplacer(true)
replaceSpecialAssigneeNames := func(value []string) ([]string, error) {
replaced, err := meReplacer.ReplaceSlice(value)
if err != nil {
return nil, err
}
// Only suppported for actor assignees.
if e.Assignees.ActorAssignees {
replaced = copilotReplacer.ReplaceSlice(replaced)
}
return replaced, nil
}
assigneeSet := set.NewStringSet()
// This check below is required because in a non-interactive flow,
// the user gives us a login and not the DisplayName, and when
// we have actor assignees e.Assignees.Default will contain
// DisplayNames and not logins (this is to accommodate special actor
// display names in the interactive flow).
// So, we need to add the default logins here instead of the DisplayNames.
// Otherwise, the value the user provided won't be found in the
// set to be added or removed, causing unexpected behavior.
if e.Assignees.ActorAssignees {
assigneeSet.AddValues(e.Assignees.DefaultLogins)
} else {
assigneeSet.AddValues(e.Assignees.Default)
}
add, err := replaceSpecialAssigneeNames(e.Assignees.Add)
if err != nil {
return nil, err
}
assigneeSet.AddValues(add)
remove, err := replaceSpecialAssigneeNames(e.Assignees.Remove)
if err != nil {
return nil, err
}
assigneeSet.RemoveValues(remove)
e.Assignees.Value = assigneeSet.ToSlice()
}
a, err := e.Metadata.MembersToIDs(e.Assignees.Value)
return &a, err
}
// ProjectIds returns a slice containing IDs of projects v1 that the issue or a PR has to be linked to.
func (e Editable) ProjectIds() (*[]string, error) {
if !e.Projects.Edited {
return nil, nil
}
if len(e.Projects.Add) != 0 || len(e.Projects.Remove) != 0 {
s := set.NewStringSet()
s.AddValues(e.Projects.Default)
s.AddValues(e.Projects.Add)
s.RemoveValues(e.Projects.Remove)
e.Projects.Value = s.ToSlice()
}
p, _, err := e.Metadata.ProjectsTitlesToIDs(e.Projects.Value)
return &p, err
}
// ProjectV2Ids returns a pair of slices.
// The first is the projects the item should be added to.
// The second is the projects the items should be removed from.
func (e Editable) ProjectV2Ids() (*[]string, *[]string, error) {
if !e.Projects.Edited {
return nil, nil, nil
}
// titles of projects to add
addTitles := set.NewStringSet()
// titles of projects to remove
removeTitles := set.NewStringSet()
if len(e.Projects.Add) != 0 || len(e.Projects.Remove) != 0 {
// Projects were selected using flags.
addTitles.AddValues(e.Projects.Add)
removeTitles.AddValues(e.Projects.Remove)
} else {
// Projects were selected interactively.
addTitles.AddValues(e.Projects.Value)
addTitles.RemoveValues(e.Projects.Default)
removeTitles.AddValues(e.Projects.Default)
removeTitles.RemoveValues(e.Projects.Value)
}
var addIds []string
var removeIds []string
var err error
if addTitles.Len() > 0 {
_, addIds, err = e.Metadata.ProjectsTitlesToIDs(addTitles.ToSlice())
if err != nil {
return nil, nil, err
}
}
if removeTitles.Len() > 0 {
_, removeIds, err = e.Metadata.ProjectsTitlesToIDs(removeTitles.ToSlice())
if err != nil {
return nil, nil, err
}
}
return &addIds, &removeIds, nil
}
func (e Editable) MilestoneId() (*string, error) {
if !e.Milestone.Edited {
return nil, nil
}
if e.Milestone.Value == noMilestone || e.Milestone.Value == "" {
s := ""
return &s, nil
}
m, err := e.Metadata.MilestoneToID(e.Milestone.Value)
return &m, err
}
// Clone creates a mostly-shallow copy of Editable suitable for use in parallel
// go routines. Fields that would be mutated will be copied.
func (e *Editable) Clone() Editable {
return Editable{
Title: e.Title.clone(),
Body: e.Body.clone(),
Base: e.Base.clone(),
Reviewers: e.Reviewers.clone(),
Assignees: e.Assignees.clone(),
Labels: e.Labels.clone(),
Projects: e.Projects.clone(),
Milestone: e.Milestone.clone(),
// Shallow copy since no mutation.
Metadata: e.Metadata,
}
}
func (es *EditableString) clone() EditableString {
return EditableString{
Value: es.Value,
Default: es.Default,
Edited: es.Edited,
// Shallow copies since no mutation.
Options: es.Options,
}
}
func (es *EditableSlice) clone() EditableSlice {
cpy := EditableSlice{
Edited: es.Edited,
Allowed: es.Allowed,
// Shallow copies since no mutation.
Options: es.Options,
// Copy mutable string slices.
Add: make([]string, len(es.Add)),
Remove: make([]string, len(es.Remove)),
Value: make([]string, len(es.Value)),
Default: make([]string, len(es.Default)),
}
copy(cpy.Add, es.Add)
copy(cpy.Remove, es.Remove)
copy(cpy.Value, es.Value)
copy(cpy.Default, es.Default)
return cpy
}
func (ea *EditableAssignees) clone() EditableAssignees {
return EditableAssignees{
EditableSlice: ea.EditableSlice.clone(),
ActorAssignees: ea.ActorAssignees,
DefaultLogins: ea.DefaultLogins,
}
}
func (ep *EditableProjects) clone() EditableProjects {
return EditableProjects{
EditableSlice: ep.EditableSlice.clone(),
ProjectItems: ep.ProjectItems,
}
}
type EditPrompter interface {
Select(string, string, []string) (int, error)
Input(string, string) (string, error)
MarkdownEditor(string, string, bool) (string, error)
MultiSelect(string, []string, []string) ([]int, error)
Confirm(string, bool) (bool, error)
}
func EditFieldsSurvey(p EditPrompter, editable *Editable, editorCommand string) error {
var err error
if editable.Title.Edited {
editable.Title.Value, err = p.Input("Title", editable.Title.Default)
if err != nil {
return err
}
}
if editable.Body.Edited {
editable.Body.Value, err = p.MarkdownEditor("Body", editable.Body.Default, false)
if err != nil {
return err
}
}
if editable.Reviewers.Edited {
editable.Reviewers.Value, err = multiSelectSurvey(
p, "Reviewers", editable.Reviewers.Default, editable.Reviewers.Options)
if err != nil {
return err
}
}
if editable.Assignees.Edited {
editable.Assignees.Value, err = multiSelectSurvey(
p, "Assignees", editable.Assignees.Default, editable.Assignees.Options)
if err != nil {
return err
}
}
if editable.Labels.Edited {
editable.Labels.Add, err = multiSelectSurvey(
p, "Labels", editable.Labels.Default, editable.Labels.Options)
if err != nil {
return err
}
for _, prev := range editable.Labels.Default {
var found bool
for _, selected := range editable.Labels.Add {
if prev == selected {
found = true
break
}
}
if !found {
editable.Labels.Remove = append(editable.Labels.Remove, prev)
}
}
}
if editable.Projects.Edited {
editable.Projects.Value, err = multiSelectSurvey(
p, "Projects", editable.Projects.Default, editable.Projects.Options)
if err != nil {
return err
}
}
if editable.Milestone.Edited {
editable.Milestone.Value, err = milestoneSurvey(p, editable.Milestone.Default, editable.Milestone.Options)
if err != nil {
return err
}
}
confirm, err := p.Confirm("Submit?", true)
if err != nil {
return err
}
if !confirm {
return fmt.Errorf("Discarding...")
}
return nil
}
func FieldsToEditSurvey(p EditPrompter, editable *Editable) error {
contains := func(s []string, str string) bool {
for _, v := range s {
if v == str {
return true
}
}
return false
}
opts := []string{"Title", "Body"}
if editable.Reviewers.Allowed {
opts = append(opts, "Reviewers")
}
opts = append(opts, "Assignees", "Labels", "Projects", "Milestone")
results, err := multiSelectSurvey(p, "What would you like to edit?", []string{}, opts)
if err != nil {
return err
}
if contains(results, "Title") {
editable.Title.Edited = true
}
if contains(results, "Body") {
editable.Body.Edited = true
}
if contains(results, "Reviewers") {
editable.Reviewers.Edited = true
}
if contains(results, "Assignees") {
editable.Assignees.Edited = true
}
if contains(results, "Labels") {
editable.Labels.Edited = true
}
if contains(results, "Projects") {
editable.Projects.Edited = true
}
if contains(results, "Milestone") {
editable.Milestone.Edited = true
}
return nil
}
func FetchOptions(client *api.Client, repo ghrepo.Interface, editable *Editable, projectV1Support gh.ProjectsV1Support) error {
// Determine whether to fetch organization teams.
// Interactive reviewer editing (Edited true, but no Add/Remove slices) still needs
// team data for selection UI. For non-interactive flows, we never need to fetch teams.
teamReviewers := false
if editable.Reviewers.Edited {
// This is likely an interactive flow since edited is set but no mutations to
// Add/Remove slices, so we need to load the teams.
if len(editable.Reviewers.Add) == 0 && len(editable.Reviewers.Remove) == 0 {
teamReviewers = true
}
}
input := api.RepoMetadataInput{
Reviewers: editable.Reviewers.Edited,
TeamReviewers: teamReviewers,
Assignees: editable.Assignees.Edited,
ActorAssignees: editable.Assignees.ActorAssignees,
Labels: editable.Labels.Edited,
ProjectsV1: editable.Projects.Edited && projectV1Support == gh.ProjectsV1Supported,
ProjectsV2: editable.Projects.Edited,
Milestones: editable.Milestone.Edited,
}
metadata, err := api.RepoMetadata(client, repo, input)
if err != nil {
return err
}
var users []string
for _, u := range metadata.AssignableUsers {
users = append(users, u.Login())
}
var actors []string
for _, a := range metadata.AssignableActors {
actors = append(actors, a.DisplayName())
}
var teams []string
for _, t := range metadata.Teams {
teams = append(teams, fmt.Sprintf("%s/%s", repo.RepoOwner(), t.Slug))
}
var labels []string
for _, l := range metadata.Labels {
labels = append(labels, l.Name)
}
var projects []string
for _, p := range metadata.Projects {
projects = append(projects, p.Name)
}
for _, p := range metadata.ProjectsV2 {
projects = append(projects, p.Title)
}
milestones := []string{noMilestone}
for _, m := range metadata.Milestones {
milestones = append(milestones, m.Title)
}
editable.Metadata = *metadata
editable.Reviewers.Options = append(users, teams...)
if editable.Assignees.ActorAssignees {
editable.Assignees.Options = actors
} else {
editable.Assignees.Options = users
}
editable.Labels.Options = labels
editable.Projects.Options = projects
editable.Milestone.Options = milestones
return nil
}
func multiSelectSurvey(p EditPrompter, message string, defaults, options []string) (results []string, err error) {
if len(options) == 0 {
return nil, nil
}
var selected []int
selected, err = p.MultiSelect(message, defaults, options)
if err != nil {
return
}
for _, i := range selected {
results = append(results, options[i])
}
return results, err
}
func milestoneSurvey(p EditPrompter, title string, opts []string) (result string, err error) {
if len(opts) == 0 {
return "", nil
}
var selected int
selected, err = p.Select("Milestone", title, opts)
if err != nil {
return
}
result = opts[selected]
return
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/shared/completion.go | pkg/cmd/pr/shared/completion.go | package shared
import (
"fmt"
"net/http"
"sort"
"strings"
"time"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghrepo"
)
func RequestableReviewersForCompletion(httpClient *http.Client, repo ghrepo.Interface) ([]string, error) {
client := api.NewClientFromHTTP(api.NewCachedHTTPClient(httpClient, time.Minute*2))
metadata, err := api.RepoMetadata(client, repo, api.RepoMetadataInput{
Reviewers: true,
TeamReviewers: true,
})
if err != nil {
return nil, err
}
results := []string{}
for _, user := range metadata.AssignableUsers {
if strings.EqualFold(user.Login(), metadata.CurrentLogin) {
continue
}
if user.Name() != "" {
results = append(results, fmt.Sprintf("%s\t%s", user.Login(), user.Name()))
} else {
results = append(results, user.Login())
}
}
for _, team := range metadata.Teams {
results = append(results, fmt.Sprintf("%s/%s", repo.RepoOwner(), team.Slug))
}
sort.Strings(results)
return results, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/shared/params_test.go | pkg/cmd/pr/shared/params_test.go | package shared
import (
"net/http"
"net/url"
"reflect"
"testing"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_listURLWithQuery(t *testing.T) {
trueBool := true
falseBool := false
type args struct {
listURL string
options FilterOptions
advancedIssueSearchSyntax bool
}
tests := []struct {
name string
args args
want string
wantErr bool
}{
{
name: "blank",
args: args{
listURL: "https://example.com/path?a=b",
options: FilterOptions{
Entity: "issue",
State: "open",
},
},
want: "https://example.com/path?a=b&q=state%3Aopen+type%3Aissue",
wantErr: false,
},
{
name: "blank, advanced search",
args: args{
listURL: "https://example.com/path?a=b",
options: FilterOptions{
Entity: "issue",
State: "open",
},
advancedIssueSearchSyntax: true,
},
want: "https://example.com/path?a=b&q=state%3Aopen+type%3Aissue",
wantErr: false,
},
{
name: "draft",
args: args{
listURL: "https://example.com/path",
options: FilterOptions{
Entity: "pr",
State: "open",
Draft: &trueBool,
},
},
want: "https://example.com/path?q=draft%3Atrue+state%3Aopen+type%3Apr",
wantErr: false,
},
{
name: "draft, advanced search",
args: args{
listURL: "https://example.com/path",
options: FilterOptions{
Entity: "pr",
State: "open",
Draft: &trueBool,
},
advancedIssueSearchSyntax: true,
},
want: "https://example.com/path?q=draft%3Atrue+state%3Aopen+type%3Apr",
wantErr: false,
},
{
name: "non-draft",
args: args{
listURL: "https://example.com/path",
options: FilterOptions{
Entity: "pr",
State: "open",
Draft: &falseBool,
},
},
want: "https://example.com/path?q=draft%3Afalse+state%3Aopen+type%3Apr",
wantErr: false,
},
{
name: "non-draft, advanced search",
args: args{
listURL: "https://example.com/path",
options: FilterOptions{
Entity: "pr",
State: "open",
Draft: &falseBool,
},
advancedIssueSearchSyntax: true,
},
want: "https://example.com/path?q=draft%3Afalse+state%3Aopen+type%3Apr",
wantErr: false,
},
{
name: "all",
args: args{
listURL: "https://example.com/path",
options: FilterOptions{
Entity: "issue",
State: "open",
Assignee: "bo",
Author: "ka",
BaseBranch: "trunk",
HeadBranch: "bug-fix",
Mention: "nu",
},
},
want: "https://example.com/path?q=assignee%3Abo+author%3Aka+base%3Atrunk+head%3Abug-fix+mentions%3Anu+state%3Aopen+type%3Aissue",
wantErr: false,
},
{
name: "all, advanced search",
args: args{
listURL: "https://example.com/path",
options: FilterOptions{
Entity: "issue",
State: "open",
Assignee: "bo",
Author: "ka",
BaseBranch: "trunk",
HeadBranch: "bug-fix",
Mention: "nu",
},
advancedIssueSearchSyntax: true,
},
want: "https://example.com/path?q=assignee%3Abo+author%3Aka+base%3Atrunk+head%3Abug-fix+mentions%3Anu+state%3Aopen+type%3Aissue",
wantErr: false,
},
{
name: "spaces in values",
args: args{
listURL: "https://example.com/path",
options: FilterOptions{
Entity: "pr",
State: "open",
Labels: []string{"docs", "help wanted"},
Milestone: `Codename "What Was Missing"`,
},
},
want: "https://example.com/path?q=label%3A%22help+wanted%22+label%3Adocs+milestone%3A%22Codename+%5C%22What+Was+Missing%5C%22%22+state%3Aopen+type%3Apr",
wantErr: false,
},
{
name: "spaces in values, advanced search",
args: args{
listURL: "https://example.com/path",
options: FilterOptions{
Entity: "pr",
State: "open",
Labels: []string{"docs", "help wanted"},
Milestone: `Codename "What Was Missing"`,
},
advancedIssueSearchSyntax: true,
},
want: "https://example.com/path?q=label%3A%22help+wanted%22+label%3Adocs+milestone%3A%22Codename+%5C%22What+Was+Missing%5C%22%22+state%3Aopen+type%3Apr",
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := ListURLWithQuery(tt.args.listURL, tt.args.options, tt.args.advancedIssueSearchSyntax)
if (err != nil) != tt.wantErr {
t.Errorf("listURLWithQuery() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("listURLWithQuery() = %v, want %v", got, tt.want)
}
})
}
}
func TestMeReplacer_Replace(t *testing.T) {
rtSuccess := &httpmock.Registry{}
rtSuccess.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StringResponse(`
{ "data": {
"viewer": { "login": "ResolvedLogin" }
} }
`),
)
rtFailure := &httpmock.Registry{}
rtFailure.Register(
httpmock.GraphQL(`query UserCurrent\b`),
httpmock.StatusStringResponse(500, `
{ "data": {
"viewer": { }
} }
`),
)
type args struct {
logins []string
client *api.Client
repo ghrepo.Interface
}
tests := []struct {
name string
args args
verify func(t httpmock.Testing)
want []string
wantErr bool
}{
{
name: "succeeds resolving the userlogin",
args: args{
client: api.NewClientFromHTTP(&http.Client{Transport: rtSuccess}),
repo: ghrepo.New("OWNER", "REPO"),
logins: []string{"some", "@me", "other"},
},
verify: rtSuccess.Verify,
want: []string{"some", "ResolvedLogin", "other"},
},
{
name: "fails resolving the userlogin",
args: args{
client: api.NewClientFromHTTP(&http.Client{Transport: rtFailure}),
repo: ghrepo.New("OWNER", "REPO"),
logins: []string{"some", "@me", "other"},
},
verify: rtFailure.Verify,
want: []string(nil),
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
me := NewMeReplacer(tt.args.client, tt.args.repo.RepoHost())
got, err := me.ReplaceSlice(tt.args.logins)
if (err != nil) != tt.wantErr {
t.Errorf("ReplaceAtMeLogin() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("ReplaceAtMeLogin() = %v, want %v", got, tt.want)
}
if tt.verify != nil {
tt.verify(t)
}
})
}
}
func TestCopilotReplacer_ReplaceSlice(t *testing.T) {
type args struct {
handles []string
}
tests := []struct {
name string
returnLogin bool
args args
want []string
}{
{
name: "replaces @copilot with login",
returnLogin: true,
args: args{
handles: []string{"monalisa", "@copilot", "hubot"},
},
want: []string{"monalisa", "copilot-swe-agent", "hubot"},
},
{
name: "replaces @copilot with name",
args: args{
handles: []string{"monalisa", "@copilot", "hubot"},
},
want: []string{"monalisa", "Copilot", "hubot"},
},
{
name: "handles no @copilot mentions",
args: args{
handles: []string{"monalisa", "user", "hubot"},
},
want: []string{"monalisa", "user", "hubot"},
},
{
name: "replaces multiple @copilot mentions",
returnLogin: true,
args: args{
handles: []string{"@copilot", "user", "@copilot"},
},
want: []string{"copilot-swe-agent", "user", "copilot-swe-agent"},
},
{
name: "handles @copilot case-insensitively",
returnLogin: true,
args: args{
handles: []string{"@Copilot", "user", "@CoPiLoT"},
},
want: []string{"copilot-swe-agent", "user", "copilot-swe-agent"},
},
{
name: "handles nil slice",
args: args{
handles: nil,
},
want: []string{},
},
{
name: "handles empty slice",
args: args{
handles: []string{},
},
want: []string{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r := NewCopilotReplacer(tt.returnLogin)
got := r.ReplaceSlice(tt.args.handles)
require.Equal(t, tt.want, got)
})
}
}
func Test_QueryHasStateClause(t *testing.T) {
tests := []struct {
searchQuery string
hasState bool
}{
{
searchQuery: "is:closed is:merged",
hasState: true,
},
{
searchQuery: "author:mislav",
hasState: false,
},
{
searchQuery: "assignee:g14a mentions:vilmibm",
hasState: false,
},
{
searchQuery: "merged:>2021-05-20",
hasState: true,
},
{
searchQuery: "state:merged state:open",
hasState: true,
},
{
searchQuery: "assignee:g14a is:closed",
hasState: true,
},
{
searchQuery: "state:closed label:bug",
hasState: true,
},
}
for _, tt := range tests {
gotState := QueryHasStateClause(tt.searchQuery)
assert.Equal(t, tt.hasState, gotState)
}
}
func Test_WithPrAndIssueQueryParams(t *testing.T) {
type args struct {
baseURL string
state IssueMetadataState
}
tests := []struct {
name string
args args
want string
wantErr bool
}{
{
name: "blank",
args: args{
baseURL: "",
state: IssueMetadataState{},
},
want: "?body=",
},
{
name: "no values",
args: args{
baseURL: "http://example.com/hey",
state: IssueMetadataState{},
},
want: "http://example.com/hey?body=",
},
{
name: "title and body",
args: args{
baseURL: "http://example.com/hey",
state: IssueMetadataState{
Title: "my title",
Body: "my bodeh",
},
},
want: "http://example.com/hey?body=my+bodeh&title=my+title",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := WithPrAndIssueQueryParams(nil, nil, tt.args.baseURL, tt.args.state, gh.ProjectsV1Supported)
if (err != nil) != tt.wantErr {
t.Errorf("WithPrAndIssueQueryParams() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("WithPrAndIssueQueryParams() = %v, want %v", got, tt.want)
}
})
}
}
// TODO projectsV1Deprecation
// Remove this test.
func TestWithPrAndIssueQueryParamsProjectsV1Deprecation(t *testing.T) {
t.Run("when projectsV1 is supported, requests them", func(t *testing.T) {
reg := &httpmock.Registry{}
client := api.NewClientFromHTTP(&http.Client{
Transport: reg,
})
repo, _ := ghrepo.FromFullName("OWNER/REPO")
reg.Register(
httpmock.GraphQL(`query RepositoryProjectList\b`),
httpmock.StringResponse(`
{ "data": { "repository": { "projects": {
"nodes": [],
"pageInfo": { "hasNextPage": false }
} } } }
`))
reg.Register(
httpmock.GraphQL(`query OrganizationProjectList\b`),
httpmock.StringResponse(`
{ "data": { "organization": { "projects": {
"nodes": [
{ "name": "Triage", "id": "TRIAGEID", "resourcePath": "/orgs/ORG/projects/1" }
],
"pageInfo": { "hasNextPage": false }
} } } }
`))
reg.Register(
httpmock.GraphQL(`query RepositoryProjectV2List\b`),
httpmock.StringResponse(`
{ "data": { "repository": { "projectsV2": {
"nodes": [],
"pageInfo": { "hasNextPage": false }
} } } }
`))
reg.Register(
httpmock.GraphQL(`query OrganizationProjectV2List\b`),
httpmock.StringResponse(`
{ "data": { "organization": { "projectsV2": {
"nodes": [],
"pageInfo": { "hasNextPage": false }
} } } }
`))
reg.Register(
httpmock.GraphQL(`query UserProjectV2List\b`),
httpmock.StringResponse(`
{ "data": { "viewer": { "projectsV2": {
"nodes": [],
"pageInfo": { "hasNextPage": false }
} } } }
`))
u, err := WithPrAndIssueQueryParams(
client,
repo,
"http://example.com/hey",
IssueMetadataState{
ProjectTitles: []string{"Triage"},
},
gh.ProjectsV1Supported,
)
require.NoError(t, err)
url, err := url.Parse(u)
require.NoError(t, err)
require.Equal(
t,
url.Query().Get("projects"),
"ORG/1",
)
})
t.Run("when projectsV1 is not supported, does not request them", func(t *testing.T) {
reg := &httpmock.Registry{}
client := api.NewClientFromHTTP(&http.Client{
Transport: reg,
})
repo, _ := ghrepo.FromFullName("OWNER/REPO")
reg.Exclude(
t,
httpmock.GraphQL(`query RepositoryProjectList\b`),
)
reg.Exclude(
t,
httpmock.GraphQL(`query OrganizationProjectList\b`),
)
reg.Register(
httpmock.GraphQL(`query RepositoryProjectV2List\b`),
httpmock.StringResponse(`
{ "data": { "repository": { "projectsV2": {
"nodes": [],
"pageInfo": { "hasNextPage": false }
} } } }
`))
reg.Register(
httpmock.GraphQL(`query OrganizationProjectV2List\b`),
httpmock.StringResponse(`
{ "data": { "organization": { "projectsV2": {
"nodes": [
{ "title": "TriageV2", "id": "TRIAGEV2ID", "resourcePath": "/orgs/ORG/projects/2" }
],
"pageInfo": { "hasNextPage": false }
} } } }
`))
reg.Register(
httpmock.GraphQL(`query UserProjectV2List\b`),
httpmock.StringResponse(`
{ "data": { "viewer": { "projectsV2": {
"nodes": [],
"pageInfo": { "hasNextPage": false }
} } } }
`))
u, err := WithPrAndIssueQueryParams(
client,
repo,
"http://example.com/hey",
IssueMetadataState{
ProjectTitles: []string{"TriageV2"},
},
gh.ProjectsV1Unsupported,
)
require.NoError(t, err)
url, err := url.Parse(u)
require.NoError(t, err)
require.Equal(
t,
url.Query().Get("projects"),
"ORG/2",
)
})
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/shared/find_refs_resolution_test.go | pkg/cmd/pr/shared/find_refs_resolution_test.go | package shared
import (
"errors"
"net/url"
"testing"
ghContext "github.com/cli/cli/v2/context"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/ghrepo"
o "github.com/cli/cli/v2/pkg/option"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestQualifiedHeadRef(t *testing.T) {
t.Parallel()
testCases := []struct {
behavior string
ref string
expectedString string
expectedBranchName string
expectedError error
}{
{
behavior: "when a branch is provided, the parsed qualified head ref only has a branch",
ref: "feature-branch",
expectedString: "feature-branch",
expectedBranchName: "feature-branch",
},
{
behavior: "when an owner and branch are provided, the parsed qualified head ref has both",
ref: "owner:feature-branch",
expectedString: "owner:feature-branch",
expectedBranchName: "feature-branch",
},
{
behavior: "when the structure cannot be interpreted correctly, an error is returned",
ref: "owner:feature-branch:extra",
expectedError: errors.New("invalid qualified head ref format 'owner:feature-branch:extra'"),
},
}
for _, tc := range testCases {
t.Run(tc.behavior, func(t *testing.T) {
t.Parallel()
qualifiedHeadRef, err := ParseQualifiedHeadRef(tc.ref)
if tc.expectedError != nil {
require.Equal(t, tc.expectedError, err)
return
}
require.NoError(t, err)
assert.Equal(t, tc.expectedString, qualifiedHeadRef.String())
assert.Equal(t, tc.expectedBranchName, qualifiedHeadRef.BranchName())
})
}
}
func TestPRFindRefs(t *testing.T) {
t.Parallel()
t.Run("qualified head ref with owner", func(t *testing.T) {
t.Parallel()
refs := PRFindRefs{
qualifiedHeadRef: mustParseQualifiedHeadRef("forkowner:feature-branch"),
}
require.Equal(t, "forkowner:feature-branch", refs.QualifiedHeadRef())
require.Equal(t, "feature-branch", refs.UnqualifiedHeadRef())
})
t.Run("qualified head ref without owner", func(t *testing.T) {
t.Parallel()
refs := PRFindRefs{
qualifiedHeadRef: mustParseQualifiedHeadRef("feature-branch"),
}
require.Equal(t, "feature-branch", refs.QualifiedHeadRef())
require.Equal(t, "feature-branch", refs.UnqualifiedHeadRef())
})
t.Run("base repo", func(t *testing.T) {
t.Parallel()
refs := PRFindRefs{
baseRepo: ghrepo.New("owner", "repo"),
}
require.True(t, ghrepo.IsSame(refs.BaseRepo(), ghrepo.New("owner", "repo")), "expected repos to be the same")
})
t.Run("matches", func(t *testing.T) {
t.Parallel()
testCases := []struct {
behavior string
refs PRFindRefs
baseBranchName string
qualifiedHeadRef string
expectedMatch bool
}{
{
behavior: "when qualified head refs don't match, returns false",
refs: PRFindRefs{
qualifiedHeadRef: mustParseQualifiedHeadRef("owner:feature-branch"),
},
baseBranchName: "feature-branch",
qualifiedHeadRef: "feature-branch",
expectedMatch: false,
},
{
behavior: "when base branches don't match, returns false",
refs: PRFindRefs{
qualifiedHeadRef: mustParseQualifiedHeadRef("feature-branch"),
baseBranchName: o.Some("not-main"),
},
baseBranchName: "main",
qualifiedHeadRef: "feature-branch",
expectedMatch: false,
},
{
behavior: "when head refs match and there is no base branch, returns true",
refs: PRFindRefs{
qualifiedHeadRef: mustParseQualifiedHeadRef("feature-branch"),
baseBranchName: o.None[string](),
},
baseBranchName: "main",
qualifiedHeadRef: "feature-branch",
expectedMatch: true,
},
{
behavior: "when head refs match and base branches match, returns true",
refs: PRFindRefs{
qualifiedHeadRef: mustParseQualifiedHeadRef("feature-branch"),
baseBranchName: o.Some("main"),
},
baseBranchName: "main",
qualifiedHeadRef: "feature-branch",
expectedMatch: true,
},
}
for _, tc := range testCases {
t.Run(tc.behavior, func(t *testing.T) {
t.Parallel()
require.Equal(t, tc.expectedMatch, tc.refs.Matches(tc.baseBranchName, tc.qualifiedHeadRef))
})
}
})
}
func TestPullRequestResolution(t *testing.T) {
t.Parallel()
baseRepo := ghrepo.New("owner", "repo")
baseRemote := ghContext.Remote{
Remote: &git.Remote{
Name: "upstream",
},
Repo: ghrepo.New("owner", "repo"),
}
forkRemote := ghContext.Remote{
Remote: &git.Remote{
Name: "origin",
},
Repo: ghrepo.New("otherowner", "repo-fork"),
}
t.Run("when the base repo is nil, returns an error", func(t *testing.T) {
t.Parallel()
resolver := NewPullRequestFindRefsResolver(stubGitConfigClient{}, dummyRemotesFn)
_, err := resolver.ResolvePullRequestRefs(nil, "", "")
require.Error(t, err)
})
t.Run("when the local branch name is empty, returns an error", func(t *testing.T) {
t.Parallel()
resolver := NewPullRequestFindRefsResolver(stubGitConfigClient{}, dummyRemotesFn)
_, err := resolver.ResolvePullRequestRefs(baseRepo, "", "")
require.Error(t, err)
})
t.Run("when the default pr head has a repo, it is used for the refs", func(t *testing.T) {
t.Parallel()
// Push revision is the first thing checked for resolution,
// so nothing else needs to be stubbed.
repoResolvedFromPushRevisionClient := stubGitConfigClient{
pushRevisionFn: stubPushRevision(git.RemoteTrackingRef{
Remote: "origin",
Branch: "feature-branch",
}, nil),
}
resolver := NewPullRequestFindRefsResolver(
repoResolvedFromPushRevisionClient,
stubRemotes(ghContext.Remotes{&baseRemote, &forkRemote}, nil),
)
refs, err := resolver.ResolvePullRequestRefs(baseRepo, "main", "feature-branch")
require.NoError(t, err)
expectedRefs := PRFindRefs{
qualifiedHeadRef: QualifiedHeadRef{
owner: o.Some("otherowner"),
branchName: "feature-branch",
},
baseRepo: baseRepo,
baseBranchName: o.Some("main"),
}
require.Equal(t, expectedRefs, refs)
})
t.Run("when the default pr head does not have a repo, we use the base repo for the head", func(t *testing.T) {
t.Parallel()
// All the values stubbed here result in being unable to resolve a default repo.
noRepoResolutionStubClient := stubGitConfigClient{
pushRevisionFn: stubPushRevision(git.RemoteTrackingRef{}, errors.New("test error")),
readBranchConfigFn: stubBranchConfig(git.BranchConfig{}, nil),
pushDefaultFn: stubPushDefault("", nil),
remotePushDefaultFn: stubRemotePushDefault("", nil),
}
resolver := NewPullRequestFindRefsResolver(
noRepoResolutionStubClient,
stubRemotes(ghContext.Remotes{&baseRemote, &forkRemote}, nil),
)
refs, err := resolver.ResolvePullRequestRefs(baseRepo, "main", "feature-branch")
require.NoError(t, err)
expectedRefs := PRFindRefs{
qualifiedHeadRef: QualifiedHeadRef{
owner: o.None[string](),
branchName: "feature-branch",
},
baseRepo: baseRepo,
baseBranchName: o.Some("main"),
}
require.Equal(t, expectedRefs, refs)
})
}
func TestTryDetermineDefaultPRHead(t *testing.T) {
t.Parallel()
baseRepo := ghrepo.New("owner", "repo")
baseRemote := ghContext.Remote{
Remote: &git.Remote{
Name: "upstream",
},
Repo: baseRepo,
}
forkRepo := ghrepo.New("otherowner", "repo-fork")
forkRemote := ghContext.Remote{
Remote: &git.Remote{
Name: "origin",
},
Repo: forkRepo,
}
forkRepoURL, err := url.Parse("https://github.com/otherowner/repo-fork.git")
require.NoError(t, err)
t.Run("when the push revision is set, use that", func(t *testing.T) {
t.Parallel()
repoResolvedFromPushRevisionClient := stubGitConfigClient{
pushRevisionFn: stubPushRevision(git.RemoteTrackingRef{
Remote: "origin",
Branch: "remote-feature-branch",
}, nil),
}
defaultPRHead, err := TryDetermineDefaultPRHead(
repoResolvedFromPushRevisionClient,
stubRemoteToRepoResolver(ghContext.Remotes{&baseRemote, &forkRemote}, nil),
"feature-branch",
)
require.NoError(t, err)
require.True(t, ghrepo.IsSame(defaultPRHead.Repo.Unwrap(), forkRepo), "expected repos to be the same")
require.Equal(t, "remote-feature-branch", defaultPRHead.BranchName)
})
t.Run("when the branch config push remote is set to a name, use that", func(t *testing.T) {
t.Parallel()
repoResolvedFromPushRemoteClient := stubGitConfigClient{
pushRevisionFn: stubPushRevision(git.RemoteTrackingRef{}, errors.New("no push revision")),
readBranchConfigFn: stubBranchConfig(git.BranchConfig{
PushRemoteName: "origin",
}, nil),
pushDefaultFn: stubPushDefault(git.PushDefaultCurrent, nil),
}
defaultPRHead, err := TryDetermineDefaultPRHead(
repoResolvedFromPushRemoteClient,
stubRemoteToRepoResolver(ghContext.Remotes{&baseRemote, &forkRemote}, nil),
"feature-branch",
)
require.NoError(t, err)
require.True(t, ghrepo.IsSame(defaultPRHead.Repo.Unwrap(), forkRepo), "expected repos to be the same")
require.Equal(t, "feature-branch", defaultPRHead.BranchName)
})
t.Run("when the branch config push remote is set to a URL, use that", func(t *testing.T) {
t.Parallel()
repoResolvedFromPushRemoteClient := stubGitConfigClient{
pushRevisionFn: stubPushRevision(git.RemoteTrackingRef{}, errors.New("no push revision")),
readBranchConfigFn: stubBranchConfig(git.BranchConfig{
PushRemoteURL: forkRepoURL,
}, nil),
pushDefaultFn: stubPushDefault(git.PushDefaultCurrent, nil),
}
defaultPRHead, err := TryDetermineDefaultPRHead(
repoResolvedFromPushRemoteClient,
dummyRemoteToRepoResolver(),
"feature-branch",
)
require.NoError(t, err)
require.True(t, ghrepo.IsSame(defaultPRHead.Repo.Unwrap(), forkRepo), "expected repos to be the same")
require.Equal(t, "feature-branch", defaultPRHead.BranchName)
})
t.Run("when a remote push default is set, use that", func(t *testing.T) {
t.Parallel()
repoResolvedFromPushRemoteClient := stubGitConfigClient{
pushRevisionFn: stubPushRevision(git.RemoteTrackingRef{}, errors.New("no push revision")),
readBranchConfigFn: stubBranchConfig(git.BranchConfig{}, nil),
pushDefaultFn: stubPushDefault(git.PushDefaultCurrent, nil),
remotePushDefaultFn: stubRemotePushDefault("origin", nil),
}
defaultPRHead, err := TryDetermineDefaultPRHead(
repoResolvedFromPushRemoteClient,
stubRemoteToRepoResolver(ghContext.Remotes{&baseRemote, &forkRemote}, nil),
"feature-branch",
)
require.NoError(t, err)
require.True(t, ghrepo.IsSame(defaultPRHead.Repo.Unwrap(), forkRepo), "expected repos to be the same")
require.Equal(t, "feature-branch", defaultPRHead.BranchName)
})
t.Run("when the branch config remote is set to a name, use that", func(t *testing.T) {
t.Parallel()
repoResolvedFromPushRemoteClient := stubGitConfigClient{
pushRevisionFn: stubPushRevision(git.RemoteTrackingRef{}, errors.New("no push revision")),
readBranchConfigFn: stubBranchConfig(git.BranchConfig{
RemoteName: "origin",
}, nil),
pushDefaultFn: stubPushDefault(git.PushDefaultCurrent, nil),
remotePushDefaultFn: stubRemotePushDefault("", nil),
}
defaultPRHead, err := TryDetermineDefaultPRHead(
repoResolvedFromPushRemoteClient,
stubRemoteToRepoResolver(ghContext.Remotes{&baseRemote, &forkRemote}, nil),
"feature-branch",
)
require.NoError(t, err)
require.True(t, ghrepo.IsSame(defaultPRHead.Repo.Unwrap(), forkRepo), "expected repos to be the same")
require.Equal(t, "feature-branch", defaultPRHead.BranchName)
})
t.Run("when the branch config remote is set to a URL, use that", func(t *testing.T) {
t.Parallel()
repoResolvedFromPushRemoteClient := stubGitConfigClient{
pushRevisionFn: stubPushRevision(git.RemoteTrackingRef{}, errors.New("no push revision")),
readBranchConfigFn: stubBranchConfig(git.BranchConfig{
RemoteURL: forkRepoURL,
}, nil),
pushDefaultFn: stubPushDefault(git.PushDefaultCurrent, nil),
remotePushDefaultFn: stubRemotePushDefault("", nil),
}
defaultPRHead, err := TryDetermineDefaultPRHead(
repoResolvedFromPushRemoteClient,
dummyRemoteToRepoResolver(),
"feature-branch",
)
require.NoError(t, err)
require.True(t, ghrepo.IsSame(defaultPRHead.Repo.Unwrap(), forkRepo), "expected repos to be the same")
require.Equal(t, "feature-branch", defaultPRHead.BranchName)
})
t.Run("when git didn't provide the necessary information, return none for the remote", func(t *testing.T) {
t.Parallel()
// All the values stubbed here result in being unable to resolve a default repo.
noRepoResolutionStubClient := stubGitConfigClient{
pushRevisionFn: stubPushRevision(git.RemoteTrackingRef{}, errors.New("test error")),
readBranchConfigFn: stubBranchConfig(git.BranchConfig{}, nil),
pushDefaultFn: stubPushDefault("", nil),
remotePushDefaultFn: stubRemotePushDefault("", nil),
}
defaultPRHead, err := TryDetermineDefaultPRHead(
noRepoResolutionStubClient,
stubRemoteToRepoResolver(ghContext.Remotes{&baseRemote, &forkRemote}, nil),
"feature-branch",
)
require.NoError(t, err)
require.True(t, defaultPRHead.Repo.IsNone(), "expected repo to be none")
require.Equal(t, "feature-branch", defaultPRHead.BranchName)
})
t.Run("when the push default is tracking or upstream, use the merge ref", func(t *testing.T) {
t.Parallel()
testCases := []struct {
pushDefault git.PushDefault
}{
{pushDefault: git.PushDefaultTracking},
{pushDefault: git.PushDefaultUpstream},
}
for _, tc := range testCases {
t.Run(string(tc.pushDefault), func(t *testing.T) {
t.Parallel()
repoResolvedFromPushRemoteClient := stubGitConfigClient{
pushRevisionFn: stubPushRevision(git.RemoteTrackingRef{}, errors.New("test error")),
readBranchConfigFn: stubBranchConfig(git.BranchConfig{
PushRemoteName: "origin",
MergeRef: "main",
}, nil),
pushDefaultFn: stubPushDefault(tc.pushDefault, nil),
}
defaultPRHead, err := TryDetermineDefaultPRHead(
repoResolvedFromPushRemoteClient,
stubRemoteToRepoResolver(ghContext.Remotes{&baseRemote, &forkRemote}, nil),
"feature-branch",
)
require.NoError(t, err)
require.True(t, ghrepo.IsSame(defaultPRHead.Repo.Unwrap(), forkRepo), "expected repos to be the same")
require.Equal(t, "main", defaultPRHead.BranchName)
})
}
t.Run("but if the merge ref is empty, use the provided branch name", func(t *testing.T) {
t.Parallel()
repoResolvedFromPushRemoteClient := stubGitConfigClient{
pushRevisionFn: stubPushRevision(git.RemoteTrackingRef{}, errors.New("test error")),
readBranchConfigFn: stubBranchConfig(git.BranchConfig{
PushRemoteName: "origin",
MergeRef: "", // intentionally empty
}, nil),
pushDefaultFn: stubPushDefault(git.PushDefaultUpstream, nil),
}
defaultPRHead, err := TryDetermineDefaultPRHead(
repoResolvedFromPushRemoteClient,
stubRemoteToRepoResolver(ghContext.Remotes{&baseRemote, &forkRemote}, nil),
"feature-branch",
)
require.NoError(t, err)
require.Equal(t, "feature-branch", defaultPRHead.BranchName)
})
})
}
func dummyRemotesFn() (ghContext.Remotes, error) {
panic("remotes fn not implemented")
}
func dummyRemoteToRepoResolver() remoteToRepoResolver {
return NewRemoteToRepoResolver(dummyRemotesFn)
}
func stubRemoteToRepoResolver(remotes ghContext.Remotes, err error) remoteToRepoResolver {
return NewRemoteToRepoResolver(func() (ghContext.Remotes, error) {
return remotes, err
})
}
func mustParseQualifiedHeadRef(ref string) QualifiedHeadRef {
parsed, err := ParseQualifiedHeadRef(ref)
if err != nil {
panic(err)
}
return parsed
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/shared/lister.go | pkg/cmd/pr/shared/lister.go | package shared
import (
"fmt"
"net/http"
"github.com/cli/cli/v2/internal/ghrepo"
api "github.com/cli/cli/v2/api"
)
type PRLister interface {
List(opt ListOptions) (*api.PullRequestAndTotalCount, error)
}
type ListOptions struct {
BaseRepo ghrepo.Interface
LimitResults int
State string
BaseBranch string
HeadBranch string
Fields []string
}
type lister struct {
httpClient *http.Client
}
func NewLister(httpClient *http.Client) PRLister {
return &lister{
httpClient: httpClient,
}
}
func (l *lister) List(opts ListOptions) (*api.PullRequestAndTotalCount, error) {
type response struct {
Repository struct {
PullRequests struct {
Nodes []api.PullRequest
PageInfo struct {
HasNextPage bool
EndCursor string
}
TotalCount int
}
}
}
limit := opts.LimitResults
fragment := fmt.Sprintf("fragment pr on PullRequest{%s}", api.PullRequestGraphQL(opts.Fields))
query := fragment + `
query PullRequestList(
$owner: String!,
$repo: String!,
$limit: Int!,
$endCursor: String,
$baseBranch: String,
$headBranch: String,
$state: [PullRequestState!] = OPEN
) {
repository(owner: $owner, name: $repo) {
pullRequests(
states: $state,
baseRefName: $baseBranch,
headRefName: $headBranch,
first: $limit,
after: $endCursor,
orderBy: {field: CREATED_AT, direction: DESC}
) {
totalCount
nodes {
...pr
}
pageInfo {
hasNextPage
endCursor
}
}
}
}`
pageLimit := min(limit, 100)
variables := map[string]interface{}{
"owner": opts.BaseRepo.RepoOwner(),
"repo": opts.BaseRepo.RepoName(),
}
switch opts.State {
case "open":
variables["state"] = []string{"OPEN"}
case "closed":
variables["state"] = []string{"CLOSED", "MERGED"}
case "merged":
variables["state"] = []string{"MERGED"}
case "all":
variables["state"] = []string{"OPEN", "CLOSED", "MERGED"}
default:
return nil, fmt.Errorf("invalid state: %s", opts.State)
}
if opts.BaseBranch != "" {
variables["baseBranch"] = opts.BaseBranch
}
if opts.HeadBranch != "" {
variables["headBranch"] = opts.HeadBranch
}
res := api.PullRequestAndTotalCount{}
var check = make(map[int]struct{})
client := api.NewClientFromHTTP(l.httpClient)
loop:
for {
variables["limit"] = pageLimit
var data response
err := client.GraphQL(opts.BaseRepo.RepoHost(), query, variables, &data)
if err != nil {
return nil, err
}
prData := data.Repository.PullRequests
res.TotalCount = prData.TotalCount
for _, pr := range prData.Nodes {
if _, exists := check[pr.Number]; exists && pr.Number > 0 {
continue
}
check[pr.Number] = struct{}{}
res.PullRequests = append(res.PullRequests, pr)
if len(res.PullRequests) == limit {
break loop
}
}
if prData.PageInfo.HasNextPage {
variables["endCursor"] = prData.PageInfo.EndCursor
pageLimit = min(pageLimit, limit-len(res.PullRequests))
} else {
break
}
}
return &res, nil
}
type mockLister struct {
called bool
expectFields []string
result *api.PullRequestAndTotalCount
err error
}
func NewMockLister(result *api.PullRequestAndTotalCount, err error) *mockLister {
return &mockLister{
result: result,
err: err,
}
}
func (m *mockLister) List(opt ListOptions) (*api.PullRequestAndTotalCount, error) {
m.called = true
if m.err != nil {
return nil, m.err
}
if m.expectFields != nil {
if !isEqualSet(m.expectFields, opt.Fields) {
return nil, fmt.Errorf("unexpected fields: %v", opt.Fields)
}
}
return m.result, m.err
}
func (m *mockLister) ExpectFields(fields []string) {
m.expectFields = fields
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/shared/templates_test.go | pkg/cmd/pr/shared/templates_test.go | package shared
import (
"net/http"
"os"
"path/filepath"
"testing"
fd "github.com/cli/cli/v2/internal/featuredetection"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/prompter"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/stretchr/testify/assert"
)
func TestTemplateManager_hasAPI(t *testing.T) {
rootDir := t.TempDir()
legacyTemplateFile := filepath.Join(rootDir, ".github", "ISSUE_TEMPLATE.md")
_ = os.MkdirAll(filepath.Dir(legacyTemplateFile), 0755)
_ = os.WriteFile(legacyTemplateFile, []byte("LEGACY"), 0644)
tr := httpmock.Registry{}
httpClient := &http.Client{Transport: &tr}
defer tr.Verify(t)
tr.Register(
httpmock.GraphQL(`query IssueTemplates\b`),
httpmock.StringResponse(`{"data":{"repository":{
"issueTemplates": [
{"name": "Bug report", "body": "I found a problem", "title": "bug: "},
{"name": "Feature request", "body": "I need a feature", "title": "request: "}
]
}}}`))
pm := &prompter.PrompterMock{}
pm.SelectFunc = func(p, _ string, opts []string) (int, error) {
if p == "Choose a template" {
return prompter.IndexFor(opts, "Feature request")
} else {
return -1, prompter.NoSuchPromptErr(p)
}
}
m := templateManager{
repo: ghrepo.NewWithHost("OWNER", "REPO", "example.com"),
rootDir: rootDir,
allowFS: true,
isPR: false,
httpClient: httpClient,
detector: &fd.EnabledDetectorMock{},
prompter: pm,
}
hasTemplates, err := m.HasTemplates()
assert.NoError(t, err)
assert.True(t, hasTemplates)
assert.Equal(t, "LEGACY", string(m.LegacyBody()))
tpl, err := m.Choose()
assert.NoError(t, err)
assert.Equal(t, "Feature request", tpl.NameForSubmit())
assert.Equal(t, "I need a feature", string(tpl.Body()))
assert.Equal(t, "request: ", tpl.Title())
}
func TestTemplateManager_hasAPI_PullRequest(t *testing.T) {
rootDir := t.TempDir()
legacyTemplateFile := filepath.Join(rootDir, ".github", "PULL_REQUEST_TEMPLATE.md")
_ = os.MkdirAll(filepath.Dir(legacyTemplateFile), 0755)
_ = os.WriteFile(legacyTemplateFile, []byte("LEGACY"), 0644)
tr := httpmock.Registry{}
httpClient := &http.Client{Transport: &tr}
defer tr.Verify(t)
tr.Register(
httpmock.GraphQL(`query PullRequestTemplates\b`),
httpmock.StringResponse(`{"data":{"repository":{
"pullRequestTemplates": [
{"filename": "bug_pr.md", "body": "I fixed a problem"},
{"filename": "feature_pr.md", "body": "I added a feature"}
]
}}}`))
pm := &prompter.PrompterMock{}
pm.SelectFunc = func(p, _ string, opts []string) (int, error) {
if p == "Choose a template" {
return prompter.IndexFor(opts, "bug_pr.md")
} else {
return -1, prompter.NoSuchPromptErr(p)
}
}
m := templateManager{
repo: ghrepo.NewWithHost("OWNER", "REPO", "example.com"),
rootDir: rootDir,
allowFS: true,
isPR: true,
httpClient: httpClient,
detector: &fd.EnabledDetectorMock{},
prompter: pm,
}
hasTemplates, err := m.HasTemplates()
assert.NoError(t, err)
assert.True(t, hasTemplates)
assert.Equal(t, "LEGACY", string(m.LegacyBody()))
tpl, err := m.Choose()
assert.NoError(t, err)
assert.Equal(t, "", tpl.NameForSubmit())
assert.Equal(t, "I fixed a problem", string(tpl.Body()))
assert.Equal(t, "", tpl.Title())
}
func TestTemplateManagerSelect(t *testing.T) {
tests := []struct {
name string
isPR bool
templateName string
wantTemplate Template
wantErr bool
errMsg string
httpStubs func(*httpmock.Registry)
}{
{
name: "no templates found",
templateName: "Bug report",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query IssueTemplates\b`),
httpmock.StringResponse(`{"data":{"repository":{"issueTemplates":[]}}}`),
)
},
wantErr: true,
errMsg: "no templates found",
},
{
name: "no matching templates found",
templateName: "Unknown report",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query IssueTemplates\b`),
httpmock.StringResponse(`
{ "data": { "repository": { "issueTemplates": [
{ "name": "Bug report", "body": "I found a problem" },
{ "name": "Feature request", "body": "I need a feature" }
] } } }`),
)
},
wantErr: true,
errMsg: `template "Unknown report" not found`,
},
{
name: "matching issue template found",
templateName: "Bug report",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query IssueTemplates\b`),
httpmock.StringResponse(`
{ "data": { "repository": { "issueTemplates": [
{ "name": "Bug report", "body": "I found a problem" },
{ "name": "Feature request", "body": "I need a feature" }
] } } }`),
)
},
wantTemplate: &issueTemplate{
Gname: "Bug report",
Gbody: "I found a problem",
},
},
{
name: "matching pull request template found",
isPR: true,
templateName: "feature.md",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestTemplates\b`),
httpmock.StringResponse(`
{ "data": { "repository": { "PullRequestTemplates": [
{ "filename": "bug.md", "body": "I fixed a problem" },
{ "filename": "feature.md", "body": "I made a feature" }
] } } }`),
)
},
wantTemplate: &pullRequestTemplate{
Gname: "feature.md",
Gbody: "I made a feature",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
defer reg.Verify(t)
if tt.httpStubs != nil {
tt.httpStubs(reg)
}
m := templateManager{
repo: ghrepo.NewWithHost("OWNER", "REPO", "example.com"),
allowFS: false,
isPR: tt.isPR,
httpClient: &http.Client{Transport: reg},
detector: &fd.EnabledDetectorMock{},
}
tmpl, err := m.Select(tt.templateName)
if tt.wantErr {
assert.EqualError(t, err, tt.errMsg)
} else {
assert.NoError(t, err)
}
if tt.wantTemplate != nil {
assert.Equal(t, tt.wantTemplate.Name(), tmpl.Name())
assert.Equal(t, tt.wantTemplate.Body(), tmpl.Body())
}
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/shared/preserve.go | pkg/cmd/pr/shared/preserve.go | package shared
import (
"encoding/json"
"fmt"
"os"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
)
func PreserveInput(io *iostreams.IOStreams, state *IssueMetadataState, createErr *error) func() {
return func() {
if !state.IsDirty() {
return
}
if *createErr == nil {
return
}
if cmdutil.IsUserCancellation(*createErr) {
// these errors are user-initiated cancellations
return
}
out := io.ErrOut
// this extra newline guards against appending to the end of a survey line
fmt.Fprintln(out)
data, err := json.Marshal(state)
if err != nil {
fmt.Fprintf(out, "failed to save input to file: %s\n", err)
fmt.Fprintln(out, "would have saved:")
fmt.Fprintf(out, "%v\n", state)
return
}
tmpfile, err := io.TempFile(os.TempDir(), "gh*.json")
if err != nil {
fmt.Fprintf(out, "failed to save input to file: %s\n", err)
fmt.Fprintln(out, "would have saved:")
fmt.Fprintf(out, "%v\n", state)
return
}
_, err = tmpfile.Write(data)
if err != nil {
fmt.Fprintf(out, "failed to save input to file: %s\n", err)
fmt.Fprintln(out, "would have saved:")
fmt.Fprintln(out, string(data))
return
}
cs := io.ColorScheme()
issueType := "pr"
if state.Type == IssueMetadata {
issueType = "issue"
}
fmt.Fprintf(out, "%s operation failed. To restore: gh %s create --recover %s\n", cs.FailureIcon(), issueType, tmpfile.Name())
// some whitespace before the actual error
fmt.Fprintln(out)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/shared/git_cached_config_client.go | pkg/cmd/pr/shared/git_cached_config_client.go | package shared
import (
"context"
"github.com/cli/cli/v2/git"
)
var _ GitConfigClient = &CachedBranchConfigGitConfigClient{}
type CachedBranchConfigGitConfigClient struct {
CachedBranchConfig git.BranchConfig
GitConfigClient
}
func (c CachedBranchConfigGitConfigClient) ReadBranchConfig(ctx context.Context, branchName string) (git.BranchConfig, error) {
return c.CachedBranchConfig, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/checks/checks.go | pkg/cmd/pr/checks/checks.go | package checks
import (
"errors"
"fmt"
"net/http"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/browser"
fd "github.com/cli/cli/v2/internal/featuredetection"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/cmd/pr/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
const defaultInterval time.Duration = 10 * time.Second
var prCheckFields = []string{
"name",
"state",
"startedAt",
"completedAt",
"link",
"bucket",
"event",
"workflow",
"description",
}
type ChecksOptions struct {
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
Browser browser.Browser
Exporter cmdutil.Exporter
Finder shared.PRFinder
Detector fd.Detector
SelectorArg string
WebMode bool
Interval time.Duration
Watch bool
FailFast bool
Required bool
}
func NewCmdChecks(f *cmdutil.Factory, runF func(*ChecksOptions) error) *cobra.Command {
var interval int
opts := &ChecksOptions{
HttpClient: f.HttpClient,
IO: f.IOStreams,
Browser: f.Browser,
Interval: defaultInterval,
}
cmd := &cobra.Command{
Use: "checks [<number> | <url> | <branch>]",
Short: "Show CI status for a single pull request",
Long: heredoc.Docf(`
Show CI status for a single pull request.
Without an argument, the pull request that belongs to the current branch
is selected.
When the %[1]s--json%[1]s flag is used, it includes a %[1]sbucket%[1]s field, which categorizes
the %[1]sstate%[1]s field into %[1]spass%[1]s, %[1]sfail%[1]s, %[1]spending%[1]s, %[1]sskipping%[1]s, or %[1]scancel%[1]s.
Additional exit codes:
8: Checks pending
`, "`"),
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
opts.Finder = shared.NewFinder(f)
if opts.Exporter != nil && opts.Watch {
return cmdutil.FlagErrorf("cannot use `--watch` with `--json` flag")
}
if repoOverride, _ := cmd.Flags().GetString("repo"); repoOverride != "" && len(args) == 0 {
return cmdutil.FlagErrorf("argument required when using the `--repo` flag")
}
if opts.FailFast && !opts.Watch {
return cmdutil.FlagErrorf("cannot use `--fail-fast` flag without `--watch` flag")
}
intervalChanged := cmd.Flags().Changed("interval")
if !opts.Watch && intervalChanged {
return cmdutil.FlagErrorf("cannot use `--interval` flag without `--watch` flag")
}
if intervalChanged {
var err error
opts.Interval, err = time.ParseDuration(fmt.Sprintf("%ds", interval))
if err != nil {
return cmdutil.FlagErrorf("could not parse `--interval` flag: %w", err)
}
}
if len(args) > 0 {
opts.SelectorArg = args[0]
}
if runF != nil {
return runF(opts)
}
return checksRun(opts)
},
}
cmd.Flags().BoolVarP(&opts.WebMode, "web", "w", false, "Open the web browser to show details about checks")
cmd.Flags().BoolVarP(&opts.Watch, "watch", "", false, "Watch checks until they finish")
cmd.Flags().BoolVarP(&opts.FailFast, "fail-fast", "", false, "Exit watch mode on first check failure")
cmd.Flags().IntVarP(&interval, "interval", "i", 10, "Refresh interval in seconds in watch mode")
cmd.Flags().BoolVar(&opts.Required, "required", false, "Only show checks that are required")
cmdutil.AddJSONFlags(cmd, &opts.Exporter, prCheckFields)
return cmd
}
func checksRunWebMode(opts *ChecksOptions) error {
findOptions := shared.FindOptions{
Selector: opts.SelectorArg,
Fields: []string{"number"},
}
pr, baseRepo, err := opts.Finder.Find(findOptions)
if err != nil {
return err
}
isTerminal := opts.IO.IsStdoutTTY()
openURL := ghrepo.GenerateRepoURL(baseRepo, "pull/%d/checks", pr.Number)
if isTerminal {
fmt.Fprintf(opts.IO.ErrOut, "Opening %s in your browser.\n", text.DisplayURL(openURL))
}
return opts.Browser.Browse(openURL)
}
func checksRun(opts *ChecksOptions) error {
if opts.WebMode {
return checksRunWebMode(opts)
}
findOptions := shared.FindOptions{
Selector: opts.SelectorArg,
Fields: []string{"number", "headRefName"},
}
var pr *api.PullRequest
pr, repo, findErr := opts.Finder.Find(findOptions)
if findErr != nil {
return findErr
}
client, clientErr := opts.HttpClient()
if clientErr != nil {
return clientErr
}
var checks []check
var counts checkCounts
var err error
var includeEvent bool
if opts.Detector == nil {
cachedClient := api.NewCachedHTTPClient(client, time.Hour*24)
opts.Detector = fd.NewDetector(cachedClient, repo.RepoHost())
}
if features, featuresErr := opts.Detector.PullRequestFeatures(); featuresErr != nil {
return featuresErr
} else {
includeEvent = features.CheckRunEvent
}
checks, counts, err = populateStatusChecks(client, repo, pr, opts.Required, includeEvent)
if err != nil {
return err
}
if opts.Exporter != nil {
return opts.Exporter.Write(opts.IO, checks)
}
if opts.Watch {
opts.IO.StartAlternateScreenBuffer()
} else {
// Only start pager in non-watch mode
if err := opts.IO.StartPager(); err == nil {
defer opts.IO.StopPager()
} else {
fmt.Fprintf(opts.IO.ErrOut, "failed to start pager: %v\n", err)
}
}
// Do not return err until we can StopAlternateScreenBuffer()
for {
if counts.Pending != 0 && opts.Watch {
opts.IO.RefreshScreen()
cs := opts.IO.ColorScheme()
fmt.Fprintln(opts.IO.Out, cs.Boldf("Refreshing checks status every %v seconds. Press Ctrl+C to quit.\n", opts.Interval.Seconds()))
}
printSummary(opts.IO, counts)
err = printTable(opts.IO, checks)
if err != nil {
break
}
if counts.Pending == 0 || !opts.Watch {
break
}
if opts.FailFast && counts.Failed > 0 {
break
}
time.Sleep(opts.Interval)
checks, counts, err = populateStatusChecks(client, repo, pr, opts.Required, includeEvent)
if err != nil {
break
}
}
opts.IO.StopAlternateScreenBuffer()
if err != nil {
return err
}
if opts.Watch {
// Print final summary to original screen buffer
printSummary(opts.IO, counts)
err = printTable(opts.IO, checks)
if err != nil {
return err
}
}
if counts.Failed > 0 {
return cmdutil.SilentError
} else if counts.Pending > 0 {
return cmdutil.PendingError
}
return nil
}
func populateStatusChecks(client *http.Client, repo ghrepo.Interface, pr *api.PullRequest, requiredChecks bool, includeEvent bool) ([]check, checkCounts, error) {
apiClient := api.NewClientFromHTTP(client)
type response struct {
Node *api.PullRequest
}
query := fmt.Sprintf(`
query PullRequestStatusChecks($id: ID!, $endCursor: String) {
node(id: $id) {
...on PullRequest {
%s
}
}
}`, api.RequiredStatusCheckRollupGraphQL("$id", "$endCursor", includeEvent))
variables := map[string]interface{}{
"id": pr.ID,
}
statusCheckRollup := api.CheckContexts{}
for {
var resp response
err := apiClient.GraphQL(repo.RepoHost(), query, variables, &resp)
if err != nil {
return nil, checkCounts{}, err
}
if len(resp.Node.StatusCheckRollup.Nodes) == 0 {
return nil, checkCounts{}, errors.New("no commit found on the pull request")
}
result := resp.Node.StatusCheckRollup.Nodes[0].Commit.StatusCheckRollup.Contexts
statusCheckRollup.Nodes = append(
statusCheckRollup.Nodes,
result.Nodes...,
)
if !result.PageInfo.HasNextPage {
break
}
variables["endCursor"] = result.PageInfo.EndCursor
}
if len(statusCheckRollup.Nodes) == 0 {
return nil, checkCounts{}, fmt.Errorf("no checks reported on the '%s' branch", pr.HeadRefName)
}
checks, counts := aggregateChecks(statusCheckRollup.Nodes, requiredChecks)
if len(checks) == 0 && requiredChecks {
return checks, counts, fmt.Errorf("no required checks reported on the '%s' branch", pr.HeadRefName)
}
return checks, counts, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/checks/checks_test.go | pkg/cmd/pr/checks/checks_test.go | package checks
import (
"bytes"
"net/http"
"reflect"
"testing"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/browser"
fd "github.com/cli/cli/v2/internal/featuredetection"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/run"
"github.com/cli/cli/v2/pkg/cmd/pr/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
)
func TestNewCmdChecks(t *testing.T) {
tests := []struct {
name string
cli string
wants ChecksOptions
wantsError string
}{
{
name: "no arguments",
cli: "",
wants: ChecksOptions{
Interval: time.Duration(10000000000),
},
},
{
name: "pr argument",
cli: "1234",
wants: ChecksOptions{
SelectorArg: "1234",
Interval: time.Duration(10000000000),
},
},
{
name: "watch flag",
cli: "--watch",
wants: ChecksOptions{
Watch: true,
Interval: time.Duration(10000000000),
},
},
{
name: "watch flag and interval flag",
cli: "--watch --interval 5",
wants: ChecksOptions{
Watch: true,
Interval: time.Duration(5000000000),
},
},
{
name: "interval flag without watch flag",
cli: "--interval 5",
wantsError: "cannot use `--interval` flag without `--watch` flag",
},
{
name: "watch with fail-fast flag",
cli: "--watch --fail-fast",
wants: ChecksOptions{
Watch: true,
FailFast: true,
Interval: time.Duration(10000000000),
},
},
{
name: "fail-fast flag without watch flag",
cli: "--fail-fast",
wantsError: "cannot use `--fail-fast` flag without `--watch` flag",
},
{
name: "watch with json flag",
cli: "--watch --json workflow",
wantsError: "cannot use `--watch` with `--json` flag",
},
{
name: "required flag",
cli: "--required",
wants: ChecksOptions{
Required: true,
Interval: time.Duration(10000000000),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
f := &cmdutil.Factory{
IOStreams: ios,
}
argv, err := shlex.Split(tt.cli)
assert.NoError(t, err)
var gotOpts *ChecksOptions
cmd := NewCmdChecks(f, func(opts *ChecksOptions) error {
gotOpts = opts
return nil
})
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
_, err = cmd.ExecuteC()
if tt.wantsError != "" {
assert.EqualError(t, err, tt.wantsError)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.wants.SelectorArg, gotOpts.SelectorArg)
assert.Equal(t, tt.wants.Watch, gotOpts.Watch)
assert.Equal(t, tt.wants.Interval, gotOpts.Interval)
assert.Equal(t, tt.wants.Required, gotOpts.Required)
assert.Equal(t, tt.wants.FailFast, gotOpts.FailFast)
})
}
}
func Test_checksRun(t *testing.T) {
tests := []struct {
name string
tty bool
watch bool
failFast bool
required bool
disableDetector bool
httpStubs func(*httpmock.Registry)
wantOut string
wantErr string
}{
{
name: "no commits tty",
tty: true,
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.StringResponse(`{"data":{"node":{}}}`),
)
},
wantOut: "",
wantErr: "no commit found on the pull request",
},
{
name: "no checks tty",
tty: true,
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.StringResponse(`{"data":{"node":{"statusCheckRollup":{"nodes":[{"commit":{"oid": "abc"}}]}}}}`),
)
},
wantOut: "",
wantErr: "no checks reported on the 'trunk' branch",
},
{
name: "some failing tty",
tty: true,
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.FileResponse("./fixtures/someFailing.json"),
)
},
wantOut: heredoc.Doc(`
Some checks were not successful
0 cancelled, 1 failing, 1 successful, 0 skipped, and 1 pending checks
NAME DESCRIPTION ELAPSED URL
X sad tests 1m26s sweet link
β cool tests 1m26s sweet link
* slow tests 1m26s sweet link
`),
wantErr: "SilentError",
},
{
name: "some cancelled tty",
tty: true,
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.FileResponse("./fixtures/someCancelled.json"),
)
},
wantOut: heredoc.Doc(`
Some checks were cancelled
1 cancelled, 0 failing, 2 successful, 0 skipped, and 0 pending checks
NAME DESCRIPTION ELAPSED URL
β cool tests 1m26s sweet link
- sad tests 1m26s sweet link
β awesome tests 1m26s sweet link
`),
wantErr: "",
},
{
name: "some pending tty",
tty: true,
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.FileResponse("./fixtures/somePending.json"),
)
},
wantOut: heredoc.Doc(`
Some checks are still pending
1 cancelled, 0 failing, 2 successful, 0 skipped, and 1 pending checks
NAME DESCRIPTION ELAPSED URL
β cool tests 1m26s sweet link
β rad tests 1m26s sweet link
* slow tests 1m26s sweet link
- sad tests 1m26s sweet link
`),
wantErr: "PendingError",
},
{
name: "all passing tty",
tty: true,
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.FileResponse("./fixtures/allPassing.json"),
)
},
wantOut: heredoc.Doc(`
All checks were successful
0 cancelled, 0 failing, 3 successful, 0 skipped, and 0 pending checks
NAME DESCRIPTION ELAPSED URL
β awesome tests 1m26s sweet link
β cool tests 1m26s sweet link
β rad tests 1m26s sweet link
`),
wantErr: "",
},
{
name: "watch all passing tty",
tty: true,
watch: true,
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.FileResponse("./fixtures/allPassing.json"),
)
},
wantOut: heredoc.Docf(`
%[1]s[?1049hAll checks were successful
0 cancelled, 0 failing, 3 successful, 0 skipped, and 0 pending checks
NAME DESCRIPTION ELAPSED URL
β awesome tests 1m26s sweet link
β cool tests 1m26s sweet link
β rad tests 1m26s sweet link
%[1]s[?1049lAll checks were successful
0 cancelled, 0 failing, 3 successful, 0 skipped, and 0 pending checks
NAME DESCRIPTION ELAPSED URL
β awesome tests 1m26s sweet link
β cool tests 1m26s sweet link
β rad tests 1m26s sweet link
`, "\x1b"),
wantErr: "",
},
{
name: "watch some failing with fail fast tty",
tty: true,
watch: true,
failFast: true,
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.FileResponse("./fixtures/someFailing.json"),
)
},
wantOut: heredoc.Docf(`
%[1]s[?1049h%[1]s[0;0H%[1]s[JRefreshing checks status every 0 seconds. Press Ctrl+C to quit.
Some checks were not successful
0 cancelled, 1 failing, 1 successful, 0 skipped, and 1 pending checks
NAME DESCRIPTION ELAPSED URL
X sad tests 1m26s sweet link
β cool tests 1m26s sweet link
* slow tests 1m26s sweet link
%[1]s[?1049lSome checks were not successful
0 cancelled, 1 failing, 1 successful, 0 skipped, and 1 pending checks
NAME DESCRIPTION ELAPSED URL
X sad tests 1m26s sweet link
β cool tests 1m26s sweet link
* slow tests 1m26s sweet link
`, "\x1b"),
wantErr: "SilentError",
},
{
name: "with statuses tty",
tty: true,
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.FileResponse("./fixtures/withStatuses.json"),
)
},
wantOut: heredoc.Doc(`
Some checks were not successful
0 cancelled, 1 failing, 2 successful, 0 skipped, and 0 pending checks
NAME DESCRIPTION ELAPSED URL
X a status sweet link
β cool tests 1m26s sweet link
β rad tests 1m26s sweet link
`),
wantErr: "SilentError",
},
{
name: "no commits",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.StringResponse(`{"data":{"node":{}}}`),
)
},
wantOut: "",
wantErr: "no commit found on the pull request",
},
{
name: "no checks",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.StringResponse(`{"data":{"node":{"statusCheckRollup":{"nodes":[{"commit":{"oid": "abc"}}]}}}}`),
)
},
wantOut: "",
wantErr: "no checks reported on the 'trunk' branch",
},
{
name: "some failing",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.FileResponse("./fixtures/someFailing.json"),
)
},
wantOut: "sad tests\tfail\t1m26s\tsweet link\t\ncool tests\tpass\t1m26s\tsweet link\t\nslow tests\tpending\t1m26s\tsweet link\t\n",
wantErr: "SilentError",
},
{
name: "some pending",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.FileResponse("./fixtures/somePending.json"),
)
},
wantOut: "cool tests\tpass\t1m26s\tsweet link\t\nrad tests\tpass\t1m26s\tsweet link\t\nslow tests\tpending\t1m26s\tsweet link\t\nsad tests\tfail\t1m26s\tsweet link\t\n",
wantErr: "PendingError",
},
{
name: "all passing",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.FileResponse("./fixtures/allPassing.json"),
)
},
wantOut: "awesome tests\tpass\t1m26s\tsweet link\t\ncool tests\tpass\t1m26s\tsweet link\t\nrad tests\tpass\t1m26s\tsweet link\t\n",
wantErr: "",
},
{
name: "with statuses",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.FileResponse("./fixtures/withStatuses.json"),
)
},
wantOut: "a status\tfail\t0\tsweet link\t\ncool tests\tpass\t1m26s\tsweet link\t\nrad tests\tpass\t1m26s\tsweet link\t\n",
wantErr: "SilentError",
},
{
name: "some skipped tty",
tty: true,
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.FileResponse("./fixtures/someSkipping.json"),
)
},
wantOut: heredoc.Doc(`
All checks were successful
0 cancelled, 0 failing, 1 successful, 2 skipped, and 0 pending checks
NAME DESCRIPTION ELAPSED URL
β cool tests 1m26s sweet link
- rad tests 1m26s sweet link
- skip tests 1m26s sweet link
`),
wantErr: "",
},
{
name: "some skipped",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.FileResponse("./fixtures/someSkipping.json"),
)
},
wantOut: "cool tests\tpass\t1m26s\tsweet link\t\nrad tests\tskipping\t1m26s\tsweet link\t\nskip tests\tskipping\t1m26s\tsweet link\t\n",
wantErr: "",
},
{
name: "only required tty",
tty: true,
required: true,
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.FileResponse("./fixtures/onlyRequired.json"),
)
},
wantOut: heredoc.Doc(`
All checks were successful
0 cancelled, 0 failing, 1 successful, 0 skipped, and 0 pending checks
NAME DESCRIPTION ELAPSED URL
β cool tests 1m26s sweet link
`),
wantErr: "",
},
{
name: "only required",
required: true,
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.FileResponse("./fixtures/onlyRequired.json"),
)
},
wantOut: "cool tests\tpass\t1m26s\tsweet link\t\n",
wantErr: "",
},
{
name: "only required but no required checks tty",
tty: true,
required: true,
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.FileResponse("./fixtures/someSkipping.json"),
)
},
wantOut: "",
wantErr: "no required checks reported on the 'trunk' branch",
},
{
name: "only required but no required checks",
required: true,
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.FileResponse("./fixtures/someSkipping.json"),
)
},
wantOut: "",
wantErr: "no required checks reported on the 'trunk' branch",
},
{
name: "descriptions tty",
tty: true,
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.FileResponse("./fixtures/withDescriptions.json"),
)
},
wantOut: heredoc.Doc(`
All checks were successful
0 cancelled, 0 failing, 3 successful, 0 skipped, and 0 pending checks
NAME DESCRIPTION ELAPSED URL
β awesome tests awesome description 1m26s sweet link
β cool tests cool description 1m26s sweet link
β rad tests rad description 1m26s sweet link
`),
wantErr: "",
},
{
name: "descriptions",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.FileResponse("./fixtures/withDescriptions.json"),
)
},
wantOut: "awesome tests\tpass\t1m26s\tsweet link\tawesome description\ncool tests\tpass\t1m26s\tsweet link\tcool description\nrad tests\tpass\t1m26s\tsweet link\trad description\n",
wantErr: "",
},
{
name: "events tty",
tty: true,
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.FileResponse("./fixtures/withEvents.json"),
)
},
wantOut: heredoc.Doc(`
All checks were successful
0 cancelled, 0 failing, 2 successful, 0 skipped, and 0 pending checks
NAME DESCRIPTION ELAPSED URL
β tests/cool tests (pull_request) cool description 1m26s sweet link
β tests/cool tests (push) cool description 1m26s sweet link
`),
wantErr: "",
},
{
name: "events not supported tty",
tty: true,
disableDetector: true,
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.FileResponse("./fixtures/withoutEvents.json"),
)
},
wantOut: heredoc.Doc(`
All checks were successful
0 cancelled, 0 failing, 1 successful, 0 skipped, and 0 pending checks
NAME DESCRIPTION ELAPSED URL
β tests/cool tests cool description 1m26s sweet link
`),
wantErr: "",
},
{
name: "events",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.FileResponse("./fixtures/withEvents.json"),
)
},
wantOut: "cool tests\tpass\t1m26s\tsweet link\tcool description\ncool tests\tpass\t1m26s\tsweet link\tcool description\n",
wantErr: "",
},
{
name: "events not supported",
disableDetector: true,
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query PullRequestStatusChecks\b`),
httpmock.FileResponse("./fixtures/withoutEvents.json"),
)
},
wantOut: "cool tests\tpass\t1m26s\tsweet link\tcool description\n",
wantErr: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(tt.tty)
ios.SetAlternateScreenBufferEnabled(tt.tty)
reg := &httpmock.Registry{}
defer reg.Verify(t)
if tt.httpStubs != nil {
tt.httpStubs(reg)
}
var detector fd.Detector
detector = &fd.EnabledDetectorMock{}
if tt.disableDetector {
detector = &fd.DisabledDetectorMock{}
}
response := &api.PullRequest{Number: 123, HeadRefName: "trunk"}
opts := &ChecksOptions{
HttpClient: func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
},
IO: ios,
SelectorArg: "123",
Finder: shared.NewMockFinder("123", response, ghrepo.New("OWNER", "REPO")),
Detector: detector,
Watch: tt.watch,
FailFast: tt.failFast,
Required: tt.required,
}
err := checksRun(opts)
if tt.wantErr != "" {
assert.EqualError(t, err, tt.wantErr)
} else {
assert.NoError(t, err)
}
assert.Equal(t, tt.wantOut, stdout.String())
})
}
}
func TestChecksRun_web(t *testing.T) {
tests := []struct {
name string
isTTY bool
wantStderr string
wantStdout string
wantBrowse string
}{
{
name: "tty",
isTTY: true,
wantStderr: "Opening https://github.com/OWNER/REPO/pull/123/checks in your browser.\n",
wantStdout: "",
wantBrowse: "https://github.com/OWNER/REPO/pull/123/checks",
},
{
name: "nontty",
isTTY: false,
wantStderr: "",
wantStdout: "",
wantBrowse: "https://github.com/OWNER/REPO/pull/123/checks",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
browser := &browser.Stub{}
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdoutTTY(tc.isTTY)
ios.SetStdinTTY(tc.isTTY)
ios.SetStderrTTY(tc.isTTY)
_, teardown := run.Stub()
defer teardown(t)
err := checksRunWebMode(&ChecksOptions{
IO: ios,
Browser: browser,
WebMode: true,
SelectorArg: "123",
Finder: shared.NewMockFinder("123", &api.PullRequest{Number: 123}, ghrepo.New("OWNER", "REPO")),
})
assert.NoError(t, err)
assert.Equal(t, tc.wantStdout, stdout.String())
assert.Equal(t, tc.wantStderr, stderr.String())
browser.Verify(t, tc.wantBrowse)
})
}
}
func TestEliminateDuplicates(t *testing.T) {
tests := []struct {
name string
checkContexts []api.CheckContext
want []api.CheckContext
}{
{
name: "duplicate CheckRun (lint)",
checkContexts: []api.CheckContext{
{
TypeName: "CheckRun",
Name: "build (ubuntu-latest)",
Status: "COMPLETED",
Conclusion: "SUCCESS",
StartedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
CompletedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
DetailsURL: "https://github.com/cli/cli/runs/1",
},
{
TypeName: "CheckRun",
Name: "lint",
Status: "COMPLETED",
Conclusion: "FAILURE",
StartedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
CompletedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
DetailsURL: "https://github.com/cli/cli/runs/2",
},
{
TypeName: "CheckRun",
Name: "lint",
Status: "COMPLETED",
Conclusion: "SUCCESS",
StartedAt: time.Date(2022, 2, 2, 2, 2, 2, 2, time.UTC),
CompletedAt: time.Date(2022, 2, 2, 2, 2, 2, 2, time.UTC),
DetailsURL: "https://github.com/cli/cli/runs/3",
},
},
want: []api.CheckContext{
{
TypeName: "CheckRun",
Name: "lint",
Status: "COMPLETED",
Conclusion: "SUCCESS",
StartedAt: time.Date(2022, 2, 2, 2, 2, 2, 2, time.UTC),
CompletedAt: time.Date(2022, 2, 2, 2, 2, 2, 2, time.UTC),
DetailsURL: "https://github.com/cli/cli/runs/3",
},
{
TypeName: "CheckRun",
Name: "build (ubuntu-latest)",
Status: "COMPLETED",
Conclusion: "SUCCESS",
StartedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
CompletedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
DetailsURL: "https://github.com/cli/cli/runs/1",
},
},
},
{
name: "duplicate StatusContext (Windows GPU)",
checkContexts: []api.CheckContext{
{
TypeName: "StatusContext",
Name: "",
Context: "Windows GPU",
State: "FAILURE",
Status: "",
Conclusion: "",
StartedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
CompletedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
DetailsURL: "",
TargetURL: "https://github.com/cli/cli/2",
},
{
TypeName: "StatusContext",
Name: "",
Context: "Windows GPU",
State: "SUCCESS",
Status: "",
Conclusion: "",
StartedAt: time.Date(2022, 2, 2, 2, 2, 2, 2, time.UTC),
CompletedAt: time.Date(2022, 2, 2, 2, 2, 2, 2, time.UTC),
DetailsURL: "",
TargetURL: "https://github.com/cli/cli/3",
},
{
TypeName: "StatusContext",
Name: "",
Context: "Linux GPU",
State: "SUCCESS",
Status: "",
Conclusion: "",
StartedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
CompletedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
DetailsURL: "",
TargetURL: "https://github.com/cli/cli/1",
},
},
want: []api.CheckContext{
{
TypeName: "StatusContext",
Name: "",
Context: "Windows GPU",
State: "SUCCESS",
Status: "",
Conclusion: "",
StartedAt: time.Date(2022, 2, 2, 2, 2, 2, 2, time.UTC),
CompletedAt: time.Date(2022, 2, 2, 2, 2, 2, 2, time.UTC),
DetailsURL: "",
TargetURL: "https://github.com/cli/cli/3",
},
{
TypeName: "StatusContext",
Name: "",
Context: "Linux GPU",
State: "SUCCESS",
Status: "",
Conclusion: "",
StartedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
CompletedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
DetailsURL: "",
TargetURL: "https://github.com/cli/cli/1",
},
},
},
{
name: "unique CheckContext",
checkContexts: []api.CheckContext{
{
TypeName: "CheckRun",
Name: "build (ubuntu-latest)",
Status: "COMPLETED",
Conclusion: "SUCCESS",
StartedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
CompletedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
DetailsURL: "https://github.com/cli/cli/runs/1",
},
{
TypeName: "StatusContext",
Name: "",
Context: "Windows GPU",
State: "SUCCESS",
Status: "",
Conclusion: "",
StartedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
CompletedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
DetailsURL: "",
TargetURL: "https://github.com/cli/cli/2",
},
{
TypeName: "StatusContext",
Name: "",
Context: "Linux GPU",
State: "SUCCESS",
Status: "",
Conclusion: "",
StartedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
CompletedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
DetailsURL: "",
TargetURL: "https://github.com/cli/cli/3",
},
},
want: []api.CheckContext{
{
TypeName: "CheckRun",
Name: "build (ubuntu-latest)",
Status: "COMPLETED",
Conclusion: "SUCCESS",
StartedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
CompletedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
DetailsURL: "https://github.com/cli/cli/runs/1",
},
{
TypeName: "StatusContext",
Name: "",
Context: "Windows GPU",
State: "SUCCESS",
Status: "",
Conclusion: "",
StartedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
CompletedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
DetailsURL: "",
TargetURL: "https://github.com/cli/cli/2",
},
{
TypeName: "StatusContext",
Name: "",
Context: "Linux GPU",
State: "SUCCESS",
Status: "",
Conclusion: "",
StartedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
CompletedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
DetailsURL: "",
TargetURL: "https://github.com/cli/cli/3",
},
},
},
{
name: "unique workflow name",
checkContexts: []api.CheckContext{
{
TypeName: "CheckRun",
Name: "build (ubuntu-latest)",
Status: "COMPLETED",
Conclusion: "SUCCESS",
StartedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
CompletedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
DetailsURL: "https://github.com/cli/cli/runs/1",
CheckSuite: api.CheckSuite{
WorkflowRun: api.WorkflowRun{
Event: "push",
Workflow: api.Workflow{
Name: "some builds",
},
},
},
},
{
TypeName: "CheckRun",
Name: "build (ubuntu-latest)",
Status: "COMPLETED",
Conclusion: "SUCCESS",
StartedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
CompletedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
DetailsURL: "https://github.com/cli/cli/runs/2",
CheckSuite: api.CheckSuite{
WorkflowRun: api.WorkflowRun{
Event: "push",
Workflow: api.Workflow{
Name: "some other builds",
},
},
},
},
},
want: []api.CheckContext{
{
TypeName: "CheckRun",
Name: "build (ubuntu-latest)",
Status: "COMPLETED",
Conclusion: "SUCCESS",
StartedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
CompletedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
DetailsURL: "https://github.com/cli/cli/runs/1",
CheckSuite: api.CheckSuite{
WorkflowRun: api.WorkflowRun{
Event: "push",
Workflow: api.Workflow{
Name: "some builds",
},
},
},
},
{
TypeName: "CheckRun",
Name: "build (ubuntu-latest)",
Status: "COMPLETED",
Conclusion: "SUCCESS",
StartedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
CompletedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
DetailsURL: "https://github.com/cli/cli/runs/2",
CheckSuite: api.CheckSuite{
WorkflowRun: api.WorkflowRun{
Event: "push",
Workflow: api.Workflow{
Name: "some other builds",
},
},
},
},
},
},
{
name: "unique workflow run event",
checkContexts: []api.CheckContext{
{
TypeName: "CheckRun",
Name: "build (ubuntu-latest)",
Status: "COMPLETED",
Conclusion: "SUCCESS",
StartedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
CompletedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
DetailsURL: "https://github.com/cli/cli/runs/1",
CheckSuite: api.CheckSuite{
WorkflowRun: api.WorkflowRun{
Event: "push",
Workflow: api.Workflow{
Name: "builds",
},
},
},
},
{
TypeName: "CheckRun",
Name: "build (ubuntu-latest)",
Status: "COMPLETED",
Conclusion: "SUCCESS",
StartedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
CompletedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
DetailsURL: "https://github.com/cli/cli/runs/2",
CheckSuite: api.CheckSuite{
WorkflowRun: api.WorkflowRun{
Event: "pull_request",
Workflow: api.Workflow{
Name: "builds",
},
},
},
},
},
want: []api.CheckContext{
{
TypeName: "CheckRun",
Name: "build (ubuntu-latest)",
Status: "COMPLETED",
Conclusion: "SUCCESS",
StartedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
CompletedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
DetailsURL: "https://github.com/cli/cli/runs/1",
CheckSuite: api.CheckSuite{
WorkflowRun: api.WorkflowRun{
Event: "push",
Workflow: api.Workflow{
Name: "builds",
},
},
},
},
{
TypeName: "CheckRun",
Name: "build (ubuntu-latest)",
Status: "COMPLETED",
Conclusion: "SUCCESS",
StartedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
CompletedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
DetailsURL: "https://github.com/cli/cli/runs/2",
CheckSuite: api.CheckSuite{
WorkflowRun: api.WorkflowRun{
Event: "pull_request",
Workflow: api.Workflow{
Name: "builds",
},
},
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := eliminateDuplicates(tt.checkContexts)
if !reflect.DeepEqual(tt.want, got) {
t.Errorf("got eliminateDuplicates %+v, want %+v\n", got, tt.want)
}
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/checks/output.go | pkg/cmd/pr/checks/output.go | package checks
import (
"fmt"
"sort"
"github.com/cli/cli/v2/internal/tableprinter"
"github.com/cli/cli/v2/pkg/iostreams"
)
func addRow(tp *tableprinter.TablePrinter, io *iostreams.IOStreams, o check) {
cs := io.ColorScheme()
elapsed := ""
if !o.StartedAt.IsZero() && !o.CompletedAt.IsZero() {
e := o.CompletedAt.Sub(o.StartedAt)
if e > 0 {
elapsed = e.String()
}
}
mark := "β"
markColor := cs.Green
switch o.Bucket {
case "fail":
mark = "X"
markColor = cs.Red
case "pending":
mark = "*"
markColor = cs.Yellow
case "skipping", "cancel":
mark = "-"
markColor = cs.Muted
}
if io.IsStdoutTTY() {
var name string
if o.Workflow != "" {
name += fmt.Sprintf("%s/", o.Workflow)
}
name += o.Name
if o.Event != "" {
name += fmt.Sprintf(" (%s)", o.Event)
}
tp.AddField(mark, tableprinter.WithColor(markColor))
tp.AddField(name)
tp.AddField(o.Description)
tp.AddField(elapsed)
tp.AddField(o.Link)
} else {
tp.AddField(o.Name)
if o.Bucket == "cancel" {
tp.AddField("fail")
} else {
tp.AddField(o.Bucket)
}
if elapsed == "" {
tp.AddField("0")
} else {
tp.AddField(elapsed)
}
tp.AddField(o.Link)
tp.AddField(o.Description)
}
tp.EndRow()
}
func printSummary(io *iostreams.IOStreams, counts checkCounts) {
summary := ""
if counts.Failed+counts.Passed+counts.Skipping+counts.Pending > 0 {
if counts.Failed > 0 {
summary = "Some checks were not successful"
} else if counts.Pending > 0 {
summary = "Some checks are still pending"
} else if counts.Canceled > 0 {
summary = "Some checks were cancelled"
} else {
summary = "All checks were successful"
}
tallies := fmt.Sprintf("%d cancelled, %d failing, %d successful, %d skipped, and %d pending checks",
counts.Canceled, counts.Failed, counts.Passed, counts.Skipping, counts.Pending)
summary = fmt.Sprintf("%s\n%s", io.ColorScheme().Bold(summary), tallies)
}
if io.IsStdoutTTY() {
fmt.Fprintln(io.Out, summary)
fmt.Fprintln(io.Out)
}
}
func printTable(io *iostreams.IOStreams, checks []check) error {
var headers []string
if io.IsStdoutTTY() {
headers = []string{"", "NAME", "DESCRIPTION", "ELAPSED", "URL"}
} else {
headers = []string{"NAME", "STATUS", "ELAPSED", "URL", "DESCRIPTION"}
}
tp := tableprinter.New(io, tableprinter.WithHeader(headers...))
sort.Slice(checks, func(i, j int) bool {
b0 := checks[i].Bucket
n0 := checks[i].Name
l0 := checks[i].Link
b1 := checks[j].Bucket
n1 := checks[j].Name
l1 := checks[j].Link
if b0 == b1 {
if n0 == n1 {
return l0 < l1
}
return n0 < n1
}
return (b0 == "fail") || (b0 == "pending" && b1 == "success")
})
for _, o := range checks {
addRow(tp, io, o)
}
err := tp.Render()
if err != nil {
return err
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/checks/aggregate.go | pkg/cmd/pr/checks/aggregate.go | package checks
import (
"fmt"
"sort"
"time"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/pkg/cmdutil"
)
type check struct {
Name string `json:"name"`
State string `json:"state"`
StartedAt time.Time `json:"startedAt"`
CompletedAt time.Time `json:"completedAt"`
Link string `json:"link"`
Bucket string `json:"bucket"`
Event string `json:"event"`
Workflow string `json:"workflow"`
Description string `json:"description"`
}
type checkCounts struct {
Failed int
Passed int
Pending int
Skipping int
Canceled int
}
func (ch *check) ExportData(fields []string) map[string]interface{} {
return cmdutil.StructExportData(ch, fields)
}
func aggregateChecks(checkContexts []api.CheckContext, requiredChecks bool) (checks []check, counts checkCounts) {
for _, c := range eliminateDuplicates(checkContexts) {
if requiredChecks && !c.IsRequired {
continue
}
state := string(c.State)
if state == "" {
if c.Status == "COMPLETED" {
state = string(c.Conclusion)
} else {
state = c.Status
}
}
link := c.DetailsURL
if link == "" {
link = c.TargetURL
}
name := c.Name
if name == "" {
name = c.Context
}
item := check{
Name: name,
State: state,
StartedAt: c.StartedAt,
CompletedAt: c.CompletedAt,
Link: link,
Event: c.CheckSuite.WorkflowRun.Event,
Workflow: c.CheckSuite.WorkflowRun.Workflow.Name,
Description: c.Description,
}
switch state {
case "SUCCESS":
item.Bucket = "pass"
counts.Passed++
case "SKIPPED", "NEUTRAL":
item.Bucket = "skipping"
counts.Skipping++
case "ERROR", "FAILURE", "TIMED_OUT", "ACTION_REQUIRED":
item.Bucket = "fail"
counts.Failed++
case "CANCELLED":
item.Bucket = "cancel"
counts.Canceled++
default: // "EXPECTED", "REQUESTED", "WAITING", "QUEUED", "PENDING", "IN_PROGRESS", "STALE"
item.Bucket = "pending"
counts.Pending++
}
checks = append(checks, item)
}
return
}
// eliminateDuplicates filters a set of checks to only the most recent ones if the set includes repeated runs
func eliminateDuplicates(checkContexts []api.CheckContext) []api.CheckContext {
sort.Slice(checkContexts, func(i, j int) bool { return checkContexts[i].StartedAt.After(checkContexts[j].StartedAt) })
mapChecks := make(map[string]struct{})
mapContexts := make(map[string]struct{})
unique := make([]api.CheckContext, 0, len(checkContexts))
for _, ctx := range checkContexts {
if ctx.Context != "" {
if _, exists := mapContexts[ctx.Context]; exists {
continue
}
mapContexts[ctx.Context] = struct{}{}
} else {
key := fmt.Sprintf("%s/%s/%s", ctx.Name, ctx.CheckSuite.WorkflowRun.Workflow.Name, ctx.CheckSuite.WorkflowRun.Event)
if _, exists := mapChecks[key]; exists {
continue
}
mapChecks[key] = struct{}{}
}
unique = append(unique, ctx)
}
return unique
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/mock_api.go | pkg/cmd/codespace/mock_api.go | // Code generated by moq; DO NOT EDIT.
// github.com/matryer/moq
package codespace
import (
"context"
"net/http"
"sync"
codespacesAPI "github.com/cli/cli/v2/internal/codespaces/api"
)
// apiClientMock is a mock implementation of apiClient.
//
// func TestSomethingThatUsesapiClient(t *testing.T) {
//
// // make and configure a mocked apiClient
// mockedapiClient := &apiClientMock{
// CreateCodespaceFunc: func(ctx context.Context, params *codespacesAPI.CreateCodespaceParams) (*codespacesAPI.Codespace, error) {
// panic("mock out the CreateCodespace method")
// },
// DeleteCodespaceFunc: func(ctx context.Context, name string, orgName string, userName string) error {
// panic("mock out the DeleteCodespace method")
// },
// EditCodespaceFunc: func(ctx context.Context, codespaceName string, params *codespacesAPI.EditCodespaceParams) (*codespacesAPI.Codespace, error) {
// panic("mock out the EditCodespace method")
// },
// GetCodespaceFunc: func(ctx context.Context, name string, includeConnection bool) (*codespacesAPI.Codespace, error) {
// panic("mock out the GetCodespace method")
// },
// GetCodespaceBillableOwnerFunc: func(ctx context.Context, nwo string) (*codespacesAPI.User, error) {
// panic("mock out the GetCodespaceBillableOwner method")
// },
// GetCodespaceRepoSuggestionsFunc: func(ctx context.Context, partialSearch string, params codespacesAPI.RepoSearchParameters) ([]string, error) {
// panic("mock out the GetCodespaceRepoSuggestions method")
// },
// GetCodespaceRepositoryContentsFunc: func(ctx context.Context, codespace *codespacesAPI.Codespace, path string) ([]byte, error) {
// panic("mock out the GetCodespaceRepositoryContents method")
// },
// GetCodespacesMachinesFunc: func(ctx context.Context, repoID int, branch string, location string, devcontainerPath string) ([]*codespacesAPI.Machine, error) {
// panic("mock out the GetCodespacesMachines method")
// },
// GetCodespacesPermissionsCheckFunc: func(ctx context.Context, repoID int, branch string, devcontainerPath string) (bool, error) {
// panic("mock out the GetCodespacesPermissionsCheck method")
// },
// GetOrgMemberCodespaceFunc: func(ctx context.Context, orgName string, userName string, codespaceName string) (*codespacesAPI.Codespace, error) {
// panic("mock out the GetOrgMemberCodespace method")
// },
// GetRepositoryFunc: func(ctx context.Context, nwo string) (*codespacesAPI.Repository, error) {
// panic("mock out the GetRepository method")
// },
// GetUserFunc: func(ctx context.Context) (*codespacesAPI.User, error) {
// panic("mock out the GetUser method")
// },
// HTTPClientFunc: func() (*http.Client, error) {
// panic("mock out the HTTPClient method")
// },
// ListCodespacesFunc: func(ctx context.Context, opts codespacesAPI.ListCodespacesOptions) ([]*codespacesAPI.Codespace, error) {
// panic("mock out the ListCodespaces method")
// },
// ListDevContainersFunc: func(ctx context.Context, repoID int, branch string, limit int) ([]codespacesAPI.DevContainerEntry, error) {
// panic("mock out the ListDevContainers method")
// },
// ServerURLFunc: func() string {
// panic("mock out the ServerURL method")
// },
// StartCodespaceFunc: func(ctx context.Context, name string) error {
// panic("mock out the StartCodespace method")
// },
// StopCodespaceFunc: func(ctx context.Context, name string, orgName string, userName string) error {
// panic("mock out the StopCodespace method")
// },
// }
//
// // use mockedapiClient in code that requires apiClient
// // and then make assertions.
//
// }
type apiClientMock struct {
// CreateCodespaceFunc mocks the CreateCodespace method.
CreateCodespaceFunc func(ctx context.Context, params *codespacesAPI.CreateCodespaceParams) (*codespacesAPI.Codespace, error)
// DeleteCodespaceFunc mocks the DeleteCodespace method.
DeleteCodespaceFunc func(ctx context.Context, name string, orgName string, userName string) error
// EditCodespaceFunc mocks the EditCodespace method.
EditCodespaceFunc func(ctx context.Context, codespaceName string, params *codespacesAPI.EditCodespaceParams) (*codespacesAPI.Codespace, error)
// GetCodespaceFunc mocks the GetCodespace method.
GetCodespaceFunc func(ctx context.Context, name string, includeConnection bool) (*codespacesAPI.Codespace, error)
// GetCodespaceBillableOwnerFunc mocks the GetCodespaceBillableOwner method.
GetCodespaceBillableOwnerFunc func(ctx context.Context, nwo string) (*codespacesAPI.User, error)
// GetCodespaceRepoSuggestionsFunc mocks the GetCodespaceRepoSuggestions method.
GetCodespaceRepoSuggestionsFunc func(ctx context.Context, partialSearch string, params codespacesAPI.RepoSearchParameters) ([]string, error)
// GetCodespaceRepositoryContentsFunc mocks the GetCodespaceRepositoryContents method.
GetCodespaceRepositoryContentsFunc func(ctx context.Context, codespace *codespacesAPI.Codespace, path string) ([]byte, error)
// GetCodespacesMachinesFunc mocks the GetCodespacesMachines method.
GetCodespacesMachinesFunc func(ctx context.Context, repoID int, branch string, location string, devcontainerPath string) ([]*codespacesAPI.Machine, error)
// GetCodespacesPermissionsCheckFunc mocks the GetCodespacesPermissionsCheck method.
GetCodespacesPermissionsCheckFunc func(ctx context.Context, repoID int, branch string, devcontainerPath string) (bool, error)
// GetOrgMemberCodespaceFunc mocks the GetOrgMemberCodespace method.
GetOrgMemberCodespaceFunc func(ctx context.Context, orgName string, userName string, codespaceName string) (*codespacesAPI.Codespace, error)
// GetRepositoryFunc mocks the GetRepository method.
GetRepositoryFunc func(ctx context.Context, nwo string) (*codespacesAPI.Repository, error)
// GetUserFunc mocks the GetUser method.
GetUserFunc func(ctx context.Context) (*codespacesAPI.User, error)
// HTTPClientFunc mocks the HTTPClient method.
HTTPClientFunc func() (*http.Client, error)
// ListCodespacesFunc mocks the ListCodespaces method.
ListCodespacesFunc func(ctx context.Context, opts codespacesAPI.ListCodespacesOptions) ([]*codespacesAPI.Codespace, error)
// ListDevContainersFunc mocks the ListDevContainers method.
ListDevContainersFunc func(ctx context.Context, repoID int, branch string, limit int) ([]codespacesAPI.DevContainerEntry, error)
// ServerURLFunc mocks the ServerURL method.
ServerURLFunc func() string
// StartCodespaceFunc mocks the StartCodespace method.
StartCodespaceFunc func(ctx context.Context, name string) error
// StopCodespaceFunc mocks the StopCodespace method.
StopCodespaceFunc func(ctx context.Context, name string, orgName string, userName string) error
// calls tracks calls to the methods.
calls struct {
// CreateCodespace holds details about calls to the CreateCodespace method.
CreateCodespace []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Params is the params argument value.
Params *codespacesAPI.CreateCodespaceParams
}
// DeleteCodespace holds details about calls to the DeleteCodespace method.
DeleteCodespace []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Name is the name argument value.
Name string
// OrgName is the orgName argument value.
OrgName string
// UserName is the userName argument value.
UserName string
}
// EditCodespace holds details about calls to the EditCodespace method.
EditCodespace []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// CodespaceName is the codespaceName argument value.
CodespaceName string
// Params is the params argument value.
Params *codespacesAPI.EditCodespaceParams
}
// GetCodespace holds details about calls to the GetCodespace method.
GetCodespace []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Name is the name argument value.
Name string
// IncludeConnection is the includeConnection argument value.
IncludeConnection bool
}
// GetCodespaceBillableOwner holds details about calls to the GetCodespaceBillableOwner method.
GetCodespaceBillableOwner []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Nwo is the nwo argument value.
Nwo string
}
// GetCodespaceRepoSuggestions holds details about calls to the GetCodespaceRepoSuggestions method.
GetCodespaceRepoSuggestions []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// PartialSearch is the partialSearch argument value.
PartialSearch string
// Params is the params argument value.
Params codespacesAPI.RepoSearchParameters
}
// GetCodespaceRepositoryContents holds details about calls to the GetCodespaceRepositoryContents method.
GetCodespaceRepositoryContents []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Codespace is the codespace argument value.
Codespace *codespacesAPI.Codespace
// Path is the path argument value.
Path string
}
// GetCodespacesMachines holds details about calls to the GetCodespacesMachines method.
GetCodespacesMachines []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// RepoID is the repoID argument value.
RepoID int
// Branch is the branch argument value.
Branch string
// Location is the location argument value.
Location string
// DevcontainerPath is the devcontainerPath argument value.
DevcontainerPath string
}
// GetCodespacesPermissionsCheck holds details about calls to the GetCodespacesPermissionsCheck method.
GetCodespacesPermissionsCheck []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// RepoID is the repoID argument value.
RepoID int
// Branch is the branch argument value.
Branch string
// DevcontainerPath is the devcontainerPath argument value.
DevcontainerPath string
}
// GetOrgMemberCodespace holds details about calls to the GetOrgMemberCodespace method.
GetOrgMemberCodespace []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// OrgName is the orgName argument value.
OrgName string
// UserName is the userName argument value.
UserName string
// CodespaceName is the codespaceName argument value.
CodespaceName string
}
// GetRepository holds details about calls to the GetRepository method.
GetRepository []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Nwo is the nwo argument value.
Nwo string
}
// GetUser holds details about calls to the GetUser method.
GetUser []struct {
// Ctx is the ctx argument value.
Ctx context.Context
}
// HTTPClient holds details about calls to the HTTPClient method.
HTTPClient []struct {
}
// ListCodespaces holds details about calls to the ListCodespaces method.
ListCodespaces []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Opts is the opts argument value.
Opts codespacesAPI.ListCodespacesOptions
}
// ListDevContainers holds details about calls to the ListDevContainers method.
ListDevContainers []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// RepoID is the repoID argument value.
RepoID int
// Branch is the branch argument value.
Branch string
// Limit is the limit argument value.
Limit int
}
// ServerURL holds details about calls to the ServerURL method.
ServerURL []struct {
}
// StartCodespace holds details about calls to the StartCodespace method.
StartCodespace []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Name is the name argument value.
Name string
}
// StopCodespace holds details about calls to the StopCodespace method.
StopCodespace []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Name is the name argument value.
Name string
// OrgName is the orgName argument value.
OrgName string
// UserName is the userName argument value.
UserName string
}
}
lockCreateCodespace sync.RWMutex
lockDeleteCodespace sync.RWMutex
lockEditCodespace sync.RWMutex
lockGetCodespace sync.RWMutex
lockGetCodespaceBillableOwner sync.RWMutex
lockGetCodespaceRepoSuggestions sync.RWMutex
lockGetCodespaceRepositoryContents sync.RWMutex
lockGetCodespacesMachines sync.RWMutex
lockGetCodespacesPermissionsCheck sync.RWMutex
lockGetOrgMemberCodespace sync.RWMutex
lockGetRepository sync.RWMutex
lockGetUser sync.RWMutex
lockHTTPClient sync.RWMutex
lockListCodespaces sync.RWMutex
lockListDevContainers sync.RWMutex
lockServerURL sync.RWMutex
lockStartCodespace sync.RWMutex
lockStopCodespace sync.RWMutex
}
// CreateCodespace calls CreateCodespaceFunc.
func (mock *apiClientMock) CreateCodespace(ctx context.Context, params *codespacesAPI.CreateCodespaceParams) (*codespacesAPI.Codespace, error) {
if mock.CreateCodespaceFunc == nil {
panic("apiClientMock.CreateCodespaceFunc: method is nil but apiClient.CreateCodespace was just called")
}
callInfo := struct {
Ctx context.Context
Params *codespacesAPI.CreateCodespaceParams
}{
Ctx: ctx,
Params: params,
}
mock.lockCreateCodespace.Lock()
mock.calls.CreateCodespace = append(mock.calls.CreateCodespace, callInfo)
mock.lockCreateCodespace.Unlock()
return mock.CreateCodespaceFunc(ctx, params)
}
// CreateCodespaceCalls gets all the calls that were made to CreateCodespace.
// Check the length with:
//
// len(mockedapiClient.CreateCodespaceCalls())
func (mock *apiClientMock) CreateCodespaceCalls() []struct {
Ctx context.Context
Params *codespacesAPI.CreateCodespaceParams
} {
var calls []struct {
Ctx context.Context
Params *codespacesAPI.CreateCodespaceParams
}
mock.lockCreateCodespace.RLock()
calls = mock.calls.CreateCodespace
mock.lockCreateCodespace.RUnlock()
return calls
}
// DeleteCodespace calls DeleteCodespaceFunc.
func (mock *apiClientMock) DeleteCodespace(ctx context.Context, name string, orgName string, userName string) error {
if mock.DeleteCodespaceFunc == nil {
panic("apiClientMock.DeleteCodespaceFunc: method is nil but apiClient.DeleteCodespace was just called")
}
callInfo := struct {
Ctx context.Context
Name string
OrgName string
UserName string
}{
Ctx: ctx,
Name: name,
OrgName: orgName,
UserName: userName,
}
mock.lockDeleteCodespace.Lock()
mock.calls.DeleteCodespace = append(mock.calls.DeleteCodespace, callInfo)
mock.lockDeleteCodespace.Unlock()
return mock.DeleteCodespaceFunc(ctx, name, orgName, userName)
}
// DeleteCodespaceCalls gets all the calls that were made to DeleteCodespace.
// Check the length with:
//
// len(mockedapiClient.DeleteCodespaceCalls())
func (mock *apiClientMock) DeleteCodespaceCalls() []struct {
Ctx context.Context
Name string
OrgName string
UserName string
} {
var calls []struct {
Ctx context.Context
Name string
OrgName string
UserName string
}
mock.lockDeleteCodespace.RLock()
calls = mock.calls.DeleteCodespace
mock.lockDeleteCodespace.RUnlock()
return calls
}
// EditCodespace calls EditCodespaceFunc.
func (mock *apiClientMock) EditCodespace(ctx context.Context, codespaceName string, params *codespacesAPI.EditCodespaceParams) (*codespacesAPI.Codespace, error) {
if mock.EditCodespaceFunc == nil {
panic("apiClientMock.EditCodespaceFunc: method is nil but apiClient.EditCodespace was just called")
}
callInfo := struct {
Ctx context.Context
CodespaceName string
Params *codespacesAPI.EditCodespaceParams
}{
Ctx: ctx,
CodespaceName: codespaceName,
Params: params,
}
mock.lockEditCodespace.Lock()
mock.calls.EditCodespace = append(mock.calls.EditCodespace, callInfo)
mock.lockEditCodespace.Unlock()
return mock.EditCodespaceFunc(ctx, codespaceName, params)
}
// EditCodespaceCalls gets all the calls that were made to EditCodespace.
// Check the length with:
//
// len(mockedapiClient.EditCodespaceCalls())
func (mock *apiClientMock) EditCodespaceCalls() []struct {
Ctx context.Context
CodespaceName string
Params *codespacesAPI.EditCodespaceParams
} {
var calls []struct {
Ctx context.Context
CodespaceName string
Params *codespacesAPI.EditCodespaceParams
}
mock.lockEditCodespace.RLock()
calls = mock.calls.EditCodespace
mock.lockEditCodespace.RUnlock()
return calls
}
// GetCodespace calls GetCodespaceFunc.
func (mock *apiClientMock) GetCodespace(ctx context.Context, name string, includeConnection bool) (*codespacesAPI.Codespace, error) {
if mock.GetCodespaceFunc == nil {
panic("apiClientMock.GetCodespaceFunc: method is nil but apiClient.GetCodespace was just called")
}
callInfo := struct {
Ctx context.Context
Name string
IncludeConnection bool
}{
Ctx: ctx,
Name: name,
IncludeConnection: includeConnection,
}
mock.lockGetCodespace.Lock()
mock.calls.GetCodespace = append(mock.calls.GetCodespace, callInfo)
mock.lockGetCodespace.Unlock()
return mock.GetCodespaceFunc(ctx, name, includeConnection)
}
// GetCodespaceCalls gets all the calls that were made to GetCodespace.
// Check the length with:
//
// len(mockedapiClient.GetCodespaceCalls())
func (mock *apiClientMock) GetCodespaceCalls() []struct {
Ctx context.Context
Name string
IncludeConnection bool
} {
var calls []struct {
Ctx context.Context
Name string
IncludeConnection bool
}
mock.lockGetCodespace.RLock()
calls = mock.calls.GetCodespace
mock.lockGetCodespace.RUnlock()
return calls
}
// GetCodespaceBillableOwner calls GetCodespaceBillableOwnerFunc.
func (mock *apiClientMock) GetCodespaceBillableOwner(ctx context.Context, nwo string) (*codespacesAPI.User, error) {
if mock.GetCodespaceBillableOwnerFunc == nil {
panic("apiClientMock.GetCodespaceBillableOwnerFunc: method is nil but apiClient.GetCodespaceBillableOwner was just called")
}
callInfo := struct {
Ctx context.Context
Nwo string
}{
Ctx: ctx,
Nwo: nwo,
}
mock.lockGetCodespaceBillableOwner.Lock()
mock.calls.GetCodespaceBillableOwner = append(mock.calls.GetCodespaceBillableOwner, callInfo)
mock.lockGetCodespaceBillableOwner.Unlock()
return mock.GetCodespaceBillableOwnerFunc(ctx, nwo)
}
// GetCodespaceBillableOwnerCalls gets all the calls that were made to GetCodespaceBillableOwner.
// Check the length with:
//
// len(mockedapiClient.GetCodespaceBillableOwnerCalls())
func (mock *apiClientMock) GetCodespaceBillableOwnerCalls() []struct {
Ctx context.Context
Nwo string
} {
var calls []struct {
Ctx context.Context
Nwo string
}
mock.lockGetCodespaceBillableOwner.RLock()
calls = mock.calls.GetCodespaceBillableOwner
mock.lockGetCodespaceBillableOwner.RUnlock()
return calls
}
// GetCodespaceRepoSuggestions calls GetCodespaceRepoSuggestionsFunc.
func (mock *apiClientMock) GetCodespaceRepoSuggestions(ctx context.Context, partialSearch string, params codespacesAPI.RepoSearchParameters) ([]string, error) {
if mock.GetCodespaceRepoSuggestionsFunc == nil {
panic("apiClientMock.GetCodespaceRepoSuggestionsFunc: method is nil but apiClient.GetCodespaceRepoSuggestions was just called")
}
callInfo := struct {
Ctx context.Context
PartialSearch string
Params codespacesAPI.RepoSearchParameters
}{
Ctx: ctx,
PartialSearch: partialSearch,
Params: params,
}
mock.lockGetCodespaceRepoSuggestions.Lock()
mock.calls.GetCodespaceRepoSuggestions = append(mock.calls.GetCodespaceRepoSuggestions, callInfo)
mock.lockGetCodespaceRepoSuggestions.Unlock()
return mock.GetCodespaceRepoSuggestionsFunc(ctx, partialSearch, params)
}
// GetCodespaceRepoSuggestionsCalls gets all the calls that were made to GetCodespaceRepoSuggestions.
// Check the length with:
//
// len(mockedapiClient.GetCodespaceRepoSuggestionsCalls())
func (mock *apiClientMock) GetCodespaceRepoSuggestionsCalls() []struct {
Ctx context.Context
PartialSearch string
Params codespacesAPI.RepoSearchParameters
} {
var calls []struct {
Ctx context.Context
PartialSearch string
Params codespacesAPI.RepoSearchParameters
}
mock.lockGetCodespaceRepoSuggestions.RLock()
calls = mock.calls.GetCodespaceRepoSuggestions
mock.lockGetCodespaceRepoSuggestions.RUnlock()
return calls
}
// GetCodespaceRepositoryContents calls GetCodespaceRepositoryContentsFunc.
func (mock *apiClientMock) GetCodespaceRepositoryContents(ctx context.Context, codespace *codespacesAPI.Codespace, path string) ([]byte, error) {
if mock.GetCodespaceRepositoryContentsFunc == nil {
panic("apiClientMock.GetCodespaceRepositoryContentsFunc: method is nil but apiClient.GetCodespaceRepositoryContents was just called")
}
callInfo := struct {
Ctx context.Context
Codespace *codespacesAPI.Codespace
Path string
}{
Ctx: ctx,
Codespace: codespace,
Path: path,
}
mock.lockGetCodespaceRepositoryContents.Lock()
mock.calls.GetCodespaceRepositoryContents = append(mock.calls.GetCodespaceRepositoryContents, callInfo)
mock.lockGetCodespaceRepositoryContents.Unlock()
return mock.GetCodespaceRepositoryContentsFunc(ctx, codespace, path)
}
// GetCodespaceRepositoryContentsCalls gets all the calls that were made to GetCodespaceRepositoryContents.
// Check the length with:
//
// len(mockedapiClient.GetCodespaceRepositoryContentsCalls())
func (mock *apiClientMock) GetCodespaceRepositoryContentsCalls() []struct {
Ctx context.Context
Codespace *codespacesAPI.Codespace
Path string
} {
var calls []struct {
Ctx context.Context
Codespace *codespacesAPI.Codespace
Path string
}
mock.lockGetCodespaceRepositoryContents.RLock()
calls = mock.calls.GetCodespaceRepositoryContents
mock.lockGetCodespaceRepositoryContents.RUnlock()
return calls
}
// GetCodespacesMachines calls GetCodespacesMachinesFunc.
func (mock *apiClientMock) GetCodespacesMachines(ctx context.Context, repoID int, branch string, location string, devcontainerPath string) ([]*codespacesAPI.Machine, error) {
if mock.GetCodespacesMachinesFunc == nil {
panic("apiClientMock.GetCodespacesMachinesFunc: method is nil but apiClient.GetCodespacesMachines was just called")
}
callInfo := struct {
Ctx context.Context
RepoID int
Branch string
Location string
DevcontainerPath string
}{
Ctx: ctx,
RepoID: repoID,
Branch: branch,
Location: location,
DevcontainerPath: devcontainerPath,
}
mock.lockGetCodespacesMachines.Lock()
mock.calls.GetCodespacesMachines = append(mock.calls.GetCodespacesMachines, callInfo)
mock.lockGetCodespacesMachines.Unlock()
return mock.GetCodespacesMachinesFunc(ctx, repoID, branch, location, devcontainerPath)
}
// GetCodespacesMachinesCalls gets all the calls that were made to GetCodespacesMachines.
// Check the length with:
//
// len(mockedapiClient.GetCodespacesMachinesCalls())
func (mock *apiClientMock) GetCodespacesMachinesCalls() []struct {
Ctx context.Context
RepoID int
Branch string
Location string
DevcontainerPath string
} {
var calls []struct {
Ctx context.Context
RepoID int
Branch string
Location string
DevcontainerPath string
}
mock.lockGetCodespacesMachines.RLock()
calls = mock.calls.GetCodespacesMachines
mock.lockGetCodespacesMachines.RUnlock()
return calls
}
// GetCodespacesPermissionsCheck calls GetCodespacesPermissionsCheckFunc.
func (mock *apiClientMock) GetCodespacesPermissionsCheck(ctx context.Context, repoID int, branch string, devcontainerPath string) (bool, error) {
if mock.GetCodespacesPermissionsCheckFunc == nil {
panic("apiClientMock.GetCodespacesPermissionsCheckFunc: method is nil but apiClient.GetCodespacesPermissionsCheck was just called")
}
callInfo := struct {
Ctx context.Context
RepoID int
Branch string
DevcontainerPath string
}{
Ctx: ctx,
RepoID: repoID,
Branch: branch,
DevcontainerPath: devcontainerPath,
}
mock.lockGetCodespacesPermissionsCheck.Lock()
mock.calls.GetCodespacesPermissionsCheck = append(mock.calls.GetCodespacesPermissionsCheck, callInfo)
mock.lockGetCodespacesPermissionsCheck.Unlock()
return mock.GetCodespacesPermissionsCheckFunc(ctx, repoID, branch, devcontainerPath)
}
// GetCodespacesPermissionsCheckCalls gets all the calls that were made to GetCodespacesPermissionsCheck.
// Check the length with:
//
// len(mockedapiClient.GetCodespacesPermissionsCheckCalls())
func (mock *apiClientMock) GetCodespacesPermissionsCheckCalls() []struct {
Ctx context.Context
RepoID int
Branch string
DevcontainerPath string
} {
var calls []struct {
Ctx context.Context
RepoID int
Branch string
DevcontainerPath string
}
mock.lockGetCodespacesPermissionsCheck.RLock()
calls = mock.calls.GetCodespacesPermissionsCheck
mock.lockGetCodespacesPermissionsCheck.RUnlock()
return calls
}
// GetOrgMemberCodespace calls GetOrgMemberCodespaceFunc.
func (mock *apiClientMock) GetOrgMemberCodespace(ctx context.Context, orgName string, userName string, codespaceName string) (*codespacesAPI.Codespace, error) {
if mock.GetOrgMemberCodespaceFunc == nil {
panic("apiClientMock.GetOrgMemberCodespaceFunc: method is nil but apiClient.GetOrgMemberCodespace was just called")
}
callInfo := struct {
Ctx context.Context
OrgName string
UserName string
CodespaceName string
}{
Ctx: ctx,
OrgName: orgName,
UserName: userName,
CodespaceName: codespaceName,
}
mock.lockGetOrgMemberCodespace.Lock()
mock.calls.GetOrgMemberCodespace = append(mock.calls.GetOrgMemberCodespace, callInfo)
mock.lockGetOrgMemberCodespace.Unlock()
return mock.GetOrgMemberCodespaceFunc(ctx, orgName, userName, codespaceName)
}
// GetOrgMemberCodespaceCalls gets all the calls that were made to GetOrgMemberCodespace.
// Check the length with:
//
// len(mockedapiClient.GetOrgMemberCodespaceCalls())
func (mock *apiClientMock) GetOrgMemberCodespaceCalls() []struct {
Ctx context.Context
OrgName string
UserName string
CodespaceName string
} {
var calls []struct {
Ctx context.Context
OrgName string
UserName string
CodespaceName string
}
mock.lockGetOrgMemberCodespace.RLock()
calls = mock.calls.GetOrgMemberCodespace
mock.lockGetOrgMemberCodespace.RUnlock()
return calls
}
// GetRepository calls GetRepositoryFunc.
func (mock *apiClientMock) GetRepository(ctx context.Context, nwo string) (*codespacesAPI.Repository, error) {
if mock.GetRepositoryFunc == nil {
panic("apiClientMock.GetRepositoryFunc: method is nil but apiClient.GetRepository was just called")
}
callInfo := struct {
Ctx context.Context
Nwo string
}{
Ctx: ctx,
Nwo: nwo,
}
mock.lockGetRepository.Lock()
mock.calls.GetRepository = append(mock.calls.GetRepository, callInfo)
mock.lockGetRepository.Unlock()
return mock.GetRepositoryFunc(ctx, nwo)
}
// GetRepositoryCalls gets all the calls that were made to GetRepository.
// Check the length with:
//
// len(mockedapiClient.GetRepositoryCalls())
func (mock *apiClientMock) GetRepositoryCalls() []struct {
Ctx context.Context
Nwo string
} {
var calls []struct {
Ctx context.Context
Nwo string
}
mock.lockGetRepository.RLock()
calls = mock.calls.GetRepository
mock.lockGetRepository.RUnlock()
return calls
}
// GetUser calls GetUserFunc.
func (mock *apiClientMock) GetUser(ctx context.Context) (*codespacesAPI.User, error) {
if mock.GetUserFunc == nil {
panic("apiClientMock.GetUserFunc: method is nil but apiClient.GetUser was just called")
}
callInfo := struct {
Ctx context.Context
}{
Ctx: ctx,
}
mock.lockGetUser.Lock()
mock.calls.GetUser = append(mock.calls.GetUser, callInfo)
mock.lockGetUser.Unlock()
return mock.GetUserFunc(ctx)
}
// GetUserCalls gets all the calls that were made to GetUser.
// Check the length with:
//
// len(mockedapiClient.GetUserCalls())
func (mock *apiClientMock) GetUserCalls() []struct {
Ctx context.Context
} {
var calls []struct {
Ctx context.Context
}
mock.lockGetUser.RLock()
calls = mock.calls.GetUser
mock.lockGetUser.RUnlock()
return calls
}
// HTTPClient calls HTTPClientFunc.
func (mock *apiClientMock) HTTPClient() (*http.Client, error) {
if mock.HTTPClientFunc == nil {
panic("apiClientMock.HTTPClientFunc: method is nil but apiClient.HTTPClient was just called")
}
callInfo := struct {
}{}
mock.lockHTTPClient.Lock()
mock.calls.HTTPClient = append(mock.calls.HTTPClient, callInfo)
mock.lockHTTPClient.Unlock()
return mock.HTTPClientFunc()
}
// HTTPClientCalls gets all the calls that were made to HTTPClient.
// Check the length with:
//
// len(mockedapiClient.HTTPClientCalls())
func (mock *apiClientMock) HTTPClientCalls() []struct {
} {
var calls []struct {
}
mock.lockHTTPClient.RLock()
calls = mock.calls.HTTPClient
mock.lockHTTPClient.RUnlock()
return calls
}
// ListCodespaces calls ListCodespacesFunc.
func (mock *apiClientMock) ListCodespaces(ctx context.Context, opts codespacesAPI.ListCodespacesOptions) ([]*codespacesAPI.Codespace, error) {
if mock.ListCodespacesFunc == nil {
panic("apiClientMock.ListCodespacesFunc: method is nil but apiClient.ListCodespaces was just called")
}
callInfo := struct {
Ctx context.Context
Opts codespacesAPI.ListCodespacesOptions
}{
Ctx: ctx,
Opts: opts,
}
mock.lockListCodespaces.Lock()
mock.calls.ListCodespaces = append(mock.calls.ListCodespaces, callInfo)
mock.lockListCodespaces.Unlock()
return mock.ListCodespacesFunc(ctx, opts)
}
// ListCodespacesCalls gets all the calls that were made to ListCodespaces.
// Check the length with:
//
// len(mockedapiClient.ListCodespacesCalls())
func (mock *apiClientMock) ListCodespacesCalls() []struct {
Ctx context.Context
Opts codespacesAPI.ListCodespacesOptions
} {
var calls []struct {
Ctx context.Context
Opts codespacesAPI.ListCodespacesOptions
}
mock.lockListCodespaces.RLock()
calls = mock.calls.ListCodespaces
mock.lockListCodespaces.RUnlock()
return calls
}
// ListDevContainers calls ListDevContainersFunc.
func (mock *apiClientMock) ListDevContainers(ctx context.Context, repoID int, branch string, limit int) ([]codespacesAPI.DevContainerEntry, error) {
if mock.ListDevContainersFunc == nil {
panic("apiClientMock.ListDevContainersFunc: method is nil but apiClient.ListDevContainers was just called")
}
callInfo := struct {
Ctx context.Context
RepoID int
Branch string
Limit int
}{
Ctx: ctx,
RepoID: repoID,
Branch: branch,
Limit: limit,
}
mock.lockListDevContainers.Lock()
mock.calls.ListDevContainers = append(mock.calls.ListDevContainers, callInfo)
mock.lockListDevContainers.Unlock()
return mock.ListDevContainersFunc(ctx, repoID, branch, limit)
}
// ListDevContainersCalls gets all the calls that were made to ListDevContainers.
// Check the length with:
//
// len(mockedapiClient.ListDevContainersCalls())
func (mock *apiClientMock) ListDevContainersCalls() []struct {
Ctx context.Context
RepoID int
Branch string
Limit int
} {
var calls []struct {
Ctx context.Context
RepoID int
Branch string
Limit int
}
mock.lockListDevContainers.RLock()
calls = mock.calls.ListDevContainers
mock.lockListDevContainers.RUnlock()
return calls
}
// ServerURL calls ServerURLFunc.
func (mock *apiClientMock) ServerURL() string {
if mock.ServerURLFunc == nil {
panic("apiClientMock.ServerURLFunc: method is nil but apiClient.ServerURL was just called")
}
callInfo := struct {
}{}
mock.lockServerURL.Lock()
mock.calls.ServerURL = append(mock.calls.ServerURL, callInfo)
mock.lockServerURL.Unlock()
return mock.ServerURLFunc()
}
// ServerURLCalls gets all the calls that were made to ServerURL.
// Check the length with:
//
// len(mockedapiClient.ServerURLCalls())
func (mock *apiClientMock) ServerURLCalls() []struct {
} {
var calls []struct {
}
mock.lockServerURL.RLock()
calls = mock.calls.ServerURL
mock.lockServerURL.RUnlock()
return calls
}
// StartCodespace calls StartCodespaceFunc.
func (mock *apiClientMock) StartCodespace(ctx context.Context, name string) error {
if mock.StartCodespaceFunc == nil {
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | true |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/ports.go | pkg/cmd/codespace/ports.go | package codespace
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/codespaces"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/cli/cli/v2/internal/codespaces/portforwarder"
"github.com/cli/cli/v2/internal/tableprinter"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/microsoft/dev-tunnels/go/tunnels"
"github.com/muhammadmuzzammil1998/jsonc"
"github.com/spf13/cobra"
"golang.org/x/sync/errgroup"
)
// newPortsCmd returns a Cobra "ports" command that displays a table of available ports,
// according to the specified flags.
func newPortsCmd(app *App) *cobra.Command {
var (
selector *CodespaceSelector
exporter cmdutil.Exporter
)
portsCmd := &cobra.Command{
Use: "ports",
Short: "List ports in a codespace",
Args: noArgsConstraint,
RunE: func(cmd *cobra.Command, args []string) error {
return app.ListPorts(cmd.Context(), selector, exporter)
},
}
selector = AddCodespaceSelector(portsCmd, app.apiClient)
cmdutil.AddJSONFlags(portsCmd, &exporter, portFields)
portsCmd.AddCommand(newPortsForwardCmd(app, selector))
portsCmd.AddCommand(newPortsVisibilityCmd(app, selector))
return portsCmd
}
// ListPorts lists known ports in a codespace.
func (a *App) ListPorts(ctx context.Context, selector *CodespaceSelector, exporter cmdutil.Exporter) (err error) {
codespace, err := selector.Select(ctx)
if err != nil {
return err
}
devContainerCh := getDevContainer(ctx, a.apiClient, codespace)
codespaceConnection, err := codespaces.GetCodespaceConnection(ctx, a, a.apiClient, codespace)
if err != nil {
return fmt.Errorf("error connecting to codespace: %w", err)
}
fwd, err := portforwarder.NewPortForwarder(ctx, codespaceConnection)
if err != nil {
return fmt.Errorf("failed to create port forwarder: %w", err)
}
defer safeClose(fwd, &err)
var ports []*tunnels.TunnelPort
err = a.RunWithProgress("Fetching ports", func() (err error) {
ports, err = fwd.ListPorts(ctx)
return
})
if err != nil {
return fmt.Errorf("error getting ports of shared servers: %w", err)
}
devContainerResult := <-devContainerCh
if devContainerResult.err != nil {
// Warn about failure to read the devcontainer file. Not a codespace command error.
a.errLogger.Printf("Failed to get port names: %v", devContainerResult.err.Error())
}
var portInfos []*portInfo
for _, p := range ports {
// filter out internal ports from list
if portforwarder.IsInternalPort(p) {
continue
}
portInfos = append(portInfos, &portInfo{
Port: p,
codespace: codespace,
devContainer: devContainerResult.devContainer,
})
}
if err := a.io.StartPager(); err != nil {
a.errLogger.Printf("error starting pager: %v", err)
}
defer a.io.StopPager()
if exporter != nil {
return exporter.Write(a.io, portInfos)
}
cs := a.io.ColorScheme()
tp := tableprinter.New(a.io, tableprinter.WithHeader("LABEL", "PORT", "VISIBILITY", "BROWSE URL"))
for _, port := range portInfos {
// Convert the ACE to a friendly visibility string (private, org, public)
visibility := portforwarder.AccessControlEntriesToVisibility(port.Port.AccessControl.Entries)
tp.AddField(port.Label())
tp.AddField(cs.Yellow(fmt.Sprintf("%d", port.Port.PortNumber)))
tp.AddField(visibility)
tp.AddField(port.BrowseURL())
tp.EndRow()
}
return tp.Render()
}
type portInfo struct {
Port *tunnels.TunnelPort
codespace *api.Codespace
devContainer *devContainer
}
func (pi *portInfo) BrowseURL() string {
return fmt.Sprintf("https://%s-%d.app.github.dev", pi.codespace.Name, pi.Port.PortNumber)
}
func (pi *portInfo) Label() string {
if pi.devContainer != nil {
portStr := strconv.Itoa(int(pi.Port.PortNumber))
if attributes, ok := pi.devContainer.PortAttributes[portStr]; ok {
return attributes.Label
}
}
return ""
}
var portFields = []string{
"sourcePort",
"visibility",
"label",
"browseUrl",
}
func (pi *portInfo) ExportData(fields []string) map[string]interface{} {
data := map[string]interface{}{}
for _, f := range fields {
switch f {
case "sourcePort":
data[f] = pi.Port.PortNumber
case "visibility":
data[f] = portforwarder.AccessControlEntriesToVisibility(pi.Port.AccessControl.Entries)
case "label":
data[f] = pi.Label()
case "browseUrl":
data[f] = pi.BrowseURL()
default:
panic("unknown field: " + f)
}
}
return data
}
type devContainerResult struct {
devContainer *devContainer
err error
}
type devContainer struct {
PortAttributes map[string]portAttribute `json:"portsAttributes"`
}
type portAttribute struct {
Label string `json:"label"`
}
func getDevContainer(ctx context.Context, apiClient apiClient, codespace *api.Codespace) <-chan devContainerResult {
ch := make(chan devContainerResult, 1)
go func() {
contents, err := apiClient.GetCodespaceRepositoryContents(ctx, codespace, ".devcontainer/devcontainer.json")
if err != nil {
ch <- devContainerResult{nil, fmt.Errorf("error getting content: %w", err)}
return
}
if contents == nil {
ch <- devContainerResult{nil, nil}
return
}
convertedJSON := normalizeJSON(jsonc.ToJSON(contents))
if !jsonc.Valid(convertedJSON) {
ch <- devContainerResult{nil, errors.New("failed to convert json to standard json")}
return
}
var container devContainer
if err := json.Unmarshal(convertedJSON, &container); err != nil {
ch <- devContainerResult{nil, fmt.Errorf("error unmarshalling: %w", err)}
return
}
ch <- devContainerResult{&container, nil}
}()
return ch
}
func newPortsVisibilityCmd(app *App, selector *CodespaceSelector) *cobra.Command {
return &cobra.Command{
Use: "visibility <port>:{public|private|org}...",
Short: "Change the visibility of the forwarded port",
Example: heredoc.Doc(`
$ gh codespace ports visibility 80:org 3000:private 8000:public
`),
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return app.UpdatePortVisibility(cmd.Context(), selector, args)
},
}
}
func (a *App) UpdatePortVisibility(ctx context.Context, selector *CodespaceSelector, args []string) (err error) {
ports, err := a.parsePortVisibilities(args)
if err != nil {
return fmt.Errorf("error parsing port arguments: %w", err)
}
codespace, err := selector.Select(ctx)
if err != nil {
return err
}
codespaceConnection, err := codespaces.GetCodespaceConnection(ctx, a, a.apiClient, codespace)
if err != nil {
return fmt.Errorf("error connecting to codespace: %w", err)
}
fwd, err := portforwarder.NewPortForwarder(ctx, codespaceConnection)
if err != nil {
return fmt.Errorf("failed to create port forwarder: %w", err)
}
defer safeClose(fwd, &err)
// TODO: check if port visibility can be updated in parallel instead of sequentially
for _, port := range ports {
err := a.RunWithProgress(fmt.Sprintf("Updating port %d visibility to: %s", port.number, port.visibility), func() (err error) {
// wait for success or failure
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
err = fwd.UpdatePortVisibility(ctx, port.number, port.visibility)
if err != nil {
return fmt.Errorf("error updating port %d to %s: %w", port.number, port.visibility, err)
}
return nil
})
if err != nil {
return err
}
}
return nil
}
type portVisibility struct {
number int
visibility string
}
func (a *App) parsePortVisibilities(args []string) ([]portVisibility, error) {
ports := make([]portVisibility, 0, len(args))
for _, a := range args {
fields := strings.Split(a, ":")
if len(fields) != 2 {
return nil, fmt.Errorf("invalid port visibility format for %q", a)
}
portStr, visibility := fields[0], fields[1]
portNumber, err := strconv.Atoi(portStr)
if err != nil {
return nil, fmt.Errorf("invalid port number: %w", err)
}
ports = append(ports, portVisibility{portNumber, visibility})
}
return ports, nil
}
// NewPortsForwardCmd returns a Cobra "ports forward" subcommand, which forwards a set of
// port pairs from the codespace to localhost.
func newPortsForwardCmd(app *App, selector *CodespaceSelector) *cobra.Command {
return &cobra.Command{
Use: "forward <remote-port>:<local-port>...",
Short: "Forward ports",
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return app.ForwardPorts(cmd.Context(), selector, args)
},
}
}
func (a *App) ForwardPorts(ctx context.Context, selector *CodespaceSelector, ports []string) (err error) {
portPairs, err := getPortPairs(ports)
if err != nil {
return fmt.Errorf("get port pairs: %w", err)
}
codespace, err := selector.Select(ctx)
if err != nil {
return err
}
codespaceConnection, err := codespaces.GetCodespaceConnection(ctx, a, a.apiClient, codespace)
if err != nil {
return fmt.Errorf("error connecting to codespace: %w", err)
}
// Run forwarding of all ports concurrently, aborting all of
// them at the first failure, including cancellation of the context.
group, ctx := errgroup.WithContext(ctx)
for _, pair := range portPairs {
group.Go(func() error {
listen, _, err := codespaces.ListenTCP(pair.local, true)
if err != nil {
return err
}
defer listen.Close()
a.errLogger.Printf("Forwarding ports: remote %d <=> local %d", pair.remote, pair.local)
fwd, err := portforwarder.NewPortForwarder(ctx, codespaceConnection)
if err != nil {
return fmt.Errorf("failed to create port forwarder: %w", err)
}
defer safeClose(fwd, &err)
opts := portforwarder.ForwardPortOpts{
Port: pair.remote,
}
return fwd.ForwardPortToListener(ctx, opts, listen)
})
}
return group.Wait() // first error
}
type portPair struct {
remote, local int
}
// getPortPairs parses a list of strings of form "%d:%d" into pairs of (remote, local) numbers.
func getPortPairs(ports []string) ([]portPair, error) {
pp := make([]portPair, 0, len(ports))
for _, portString := range ports {
parts := strings.Split(portString, ":")
if len(parts) < 2 {
return nil, fmt.Errorf("port pair: %q is not valid", portString)
}
remote, err := strconv.Atoi(parts[0])
if err != nil {
return pp, fmt.Errorf("convert remote port to int: %w", err)
}
local, err := strconv.Atoi(parts[1])
if err != nil {
return pp, fmt.Errorf("convert local port to int: %w", err)
}
pp = append(pp, portPair{remote, local})
}
return pp, nil
}
func normalizeJSON(j []byte) []byte {
// remove trailing commas
return bytes.ReplaceAll(j, []byte("},}"), []byte("}}"))
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/stop.go | pkg/cmd/codespace/stop.go | package codespace
import (
"context"
"errors"
"fmt"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/spf13/cobra"
)
type stopOptions struct {
selector *CodespaceSelector
orgName string
userName string
}
func newStopCmd(app *App) *cobra.Command {
opts := &stopOptions{}
stopCmd := &cobra.Command{
Use: "stop",
Short: "Stop a running codespace",
Args: noArgsConstraint,
RunE: func(cmd *cobra.Command, args []string) error {
if opts.orgName != "" && opts.selector.codespaceName != "" && opts.userName == "" {
return cmdutil.FlagErrorf("using `--org` with `--codespace` requires `--user`")
}
return app.StopCodespace(cmd.Context(), opts)
},
}
opts.selector = AddCodespaceSelector(stopCmd, app.apiClient)
stopCmd.Flags().StringVarP(&opts.orgName, "org", "o", "", "The `login` handle of the organization (admin-only)")
stopCmd.Flags().StringVarP(&opts.userName, "user", "u", "", "The `username` to stop codespace for (used with --org)")
return stopCmd
}
func (a *App) StopCodespace(ctx context.Context, opts *stopOptions) error {
var (
codespaceName = opts.selector.codespaceName
repoName = opts.selector.repoName
ownerName = opts.userName
)
if codespaceName == "" {
var codespaces []*api.Codespace
err := a.RunWithProgress("Fetching codespaces", func() (err error) {
codespaces, err = a.apiClient.ListCodespaces(ctx, api.ListCodespacesOptions{
RepoName: repoName,
OrgName: opts.orgName,
UserName: ownerName,
})
return
})
if err != nil {
return fmt.Errorf("failed to list codespaces: %w", err)
}
var runningCodespaces []*api.Codespace
for _, c := range codespaces {
cs := codespace{c}
if cs.running() {
runningCodespaces = append(runningCodespaces, c)
}
}
if len(runningCodespaces) == 0 {
return errors.New("no running codespaces")
}
includeOwner := opts.orgName != ""
skipPromptForSingleOption := repoName != ""
codespace, err := chooseCodespaceFromList(ctx, runningCodespaces, includeOwner, skipPromptForSingleOption)
if err != nil {
return fmt.Errorf("failed to choose codespace: %w", err)
}
codespaceName = codespace.Name
ownerName = codespace.Owner.Login
} else {
var c *api.Codespace
err := a.RunWithProgress("Fetching codespace", func() (err error) {
if opts.orgName == "" {
c, err = a.apiClient.GetCodespace(ctx, codespaceName, false)
} else {
c, err = a.apiClient.GetOrgMemberCodespace(ctx, opts.orgName, ownerName, codespaceName)
}
return
})
if err != nil {
return fmt.Errorf("failed to get codespace: %q: %w", codespaceName, err)
}
cs := codespace{c}
if !cs.running() {
return fmt.Errorf("codespace %q is not running", codespaceName)
}
}
err := a.RunWithProgress("Stopping codespace", func() (err error) {
err = a.apiClient.StopCodespace(ctx, codespaceName, opts.orgName, ownerName)
return
})
if err != nil {
return fmt.Errorf("failed to stop codespace: %w", err)
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/view.go | pkg/cmd/codespace/view.go | package codespace
import (
"context"
"fmt"
"os"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/cli/cli/v2/internal/tableprinter"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/spf13/cobra"
)
const (
minutesInDay = 1440
)
type viewOptions struct {
selector *CodespaceSelector
exporter cmdutil.Exporter
}
func newViewCmd(app *App) *cobra.Command {
opts := &viewOptions{}
viewCmd := &cobra.Command{
Use: "view",
Short: "View details about a codespace",
Example: heredoc.Doc(`
# Select a codespace from a list of all codespaces you own
$ gh cs view
# View the details of a specific codespace
$ gh cs view -c codespace-name-12345
# View the list of all available fields for a codespace
$ gh cs view --json
# View specific fields for a codespace
$ gh cs view --json displayName,machineDisplayName,state
`),
Args: noArgsConstraint,
RunE: func(cmd *cobra.Command, args []string) error {
return app.ViewCodespace(cmd.Context(), opts)
},
}
opts.selector = AddCodespaceSelector(viewCmd, app.apiClient)
cmdutil.AddJSONFlags(viewCmd, &opts.exporter, api.ViewCodespaceFields)
return viewCmd
}
func (a *App) ViewCodespace(ctx context.Context, opts *viewOptions) error {
// If we are in a codespace and a codespace name wasn't provided, show the details for the codespace we are connected to
if (os.Getenv("CODESPACES") == "true") && opts.selector.codespaceName == "" {
codespaceName := os.Getenv("CODESPACE_NAME")
opts.selector.codespaceName = codespaceName
}
selectedCodespace, err := opts.selector.Select(ctx)
if err != nil {
return err
}
if err := a.io.StartPager(); err != nil {
a.errLogger.Printf("error starting pager: %v", err)
}
defer a.io.StopPager()
if opts.exporter != nil {
return opts.exporter.Write(a.io, selectedCodespace)
}
//nolint:staticcheck // SA1019: Showing NAME|VALUE headers adds nothing to table.
tp := tableprinter.New(a.io, tableprinter.NoHeader)
c := codespace{selectedCodespace}
formattedName := formatNameForVSCSTarget(c.Name, c.VSCSTarget)
// Create an array of fields to display in the table with their values
fields := []struct {
name string
value string
}{
{"Name", formattedName},
{"State", c.State},
{"Repository", c.Repository.FullName},
{"Git Status", formatGitStatus(c)},
{"Devcontainer Path", c.DevContainerPath},
{"Machine Display Name", c.Machine.DisplayName},
{"Idle Timeout", fmt.Sprintf("%d minutes", c.IdleTimeoutMinutes)},
{"Created At", c.CreatedAt},
{"Retention Period", formatRetentionPeriodDays(c)},
}
for _, field := range fields {
// Don't display the field if it is empty and we are printing to a TTY
if !a.io.IsStdoutTTY() || field.value != "" {
tp.AddField(field.name)
tp.AddField(field.value)
tp.EndRow()
}
}
err = tp.Render()
if err != nil {
return err
}
return nil
}
func formatGitStatus(codespace codespace) string {
branchWithGitStatus := codespace.branchWithGitStatus()
// Format the commits ahead/behind with proper pluralization
commitsAhead := text.Pluralize(codespace.GitStatus.Ahead, "commit")
commitsBehind := text.Pluralize(codespace.GitStatus.Behind, "commit")
return fmt.Sprintf("%s - %s ahead, %s behind", branchWithGitStatus, commitsAhead, commitsBehind)
}
func formatRetentionPeriodDays(codespace codespace) string {
days := codespace.RetentionPeriodMinutes / minutesInDay
// Don't display the retention period if it is 0 days
if days == 0 {
return ""
} else if days == 1 {
return "1 day"
}
return fmt.Sprintf("%d days", days)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/root.go | pkg/cmd/codespace/root.go | package codespace
import (
codespacesAPI "github.com/cli/cli/v2/internal/codespaces/api"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/spf13/cobra"
)
func NewCmdCodespace(f *cmdutil.Factory) *cobra.Command {
root := &cobra.Command{
Use: "codespace",
Short: "Connect to and manage codespaces",
Aliases: []string{"cs"},
GroupID: "core",
}
app := NewApp(
f.IOStreams,
f,
codespacesAPI.New(f),
f.Browser,
f.Remotes,
)
root.AddCommand(newCodeCmd(app))
root.AddCommand(newCreateCmd(app))
root.AddCommand(newEditCmd(app))
root.AddCommand(newDeleteCmd(app))
root.AddCommand(newJupyterCmd(app))
root.AddCommand(newListCmd(app))
root.AddCommand(newViewCmd(app))
root.AddCommand(newLogsCmd(app))
root.AddCommand(newPortsCmd(app))
root.AddCommand(newSSHCmd(app))
root.AddCommand(newCpCmd(app))
root.AddCommand(newStopCmd(app))
root.AddCommand(newSelectCmd(app))
root.AddCommand(newRebuildCmd(app))
return root
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/common_test.go | pkg/cmd/codespace/common_test.go | package codespace
import (
"reflect"
"testing"
"github.com/cli/cli/v2/internal/codespaces/api"
)
func Test_codespace_displayName(t *testing.T) {
type fields struct {
Codespace *api.Codespace
}
type args struct {
includeOwner bool
}
tests := []struct {
name string
args args
fields fields
want string
}{
{
name: "No included name or gitstatus",
args: args{},
fields: fields{
Codespace: &api.Codespace{
GitStatus: api.CodespaceGitStatus{
Ref: "trunk",
},
Repository: api.Repository{
FullName: "cli/cli",
},
DisplayName: "scuba steve",
},
},
want: "cli/cli [trunk]: scuba steve",
},
{
name: "No included name - included gitstatus - no unsaved changes",
args: args{},
fields: fields{
Codespace: &api.Codespace{
GitStatus: api.CodespaceGitStatus{
Ref: "trunk",
},
Repository: api.Repository{
FullName: "cli/cli",
},
DisplayName: "scuba steve",
},
},
want: "cli/cli [trunk]: scuba steve",
},
{
name: "No included name - included gitstatus - unsaved changes",
args: args{},
fields: fields{
Codespace: &api.Codespace{
GitStatus: api.CodespaceGitStatus{
Ref: "trunk",
HasUncommittedChanges: true,
},
Repository: api.Repository{
FullName: "cli/cli",
},
DisplayName: "scuba steve",
},
},
want: "cli/cli [trunk*]: scuba steve",
},
{
name: "Included name - included gitstatus - unsaved changes",
args: args{},
fields: fields{
Codespace: &api.Codespace{
GitStatus: api.CodespaceGitStatus{
Ref: "trunk",
HasUncommittedChanges: true,
},
Repository: api.Repository{
FullName: "cli/cli",
},
DisplayName: "scuba steve",
},
},
want: "cli/cli [trunk*]: scuba steve",
},
{
name: "Included name - included gitstatus - no unsaved changes",
args: args{},
fields: fields{
Codespace: &api.Codespace{
GitStatus: api.CodespaceGitStatus{
Ref: "trunk",
HasUncommittedChanges: false,
},
Repository: api.Repository{
FullName: "cli/cli",
},
DisplayName: "scuba steve",
},
},
want: "cli/cli [trunk]: scuba steve",
},
{
name: "with includeOwner true, prefixes the codespace owner",
args: args{
includeOwner: true,
},
fields: fields{
Codespace: &api.Codespace{
Owner: api.User{
Login: "jimmy",
},
GitStatus: api.CodespaceGitStatus{
Ref: "trunk",
HasUncommittedChanges: false,
},
Repository: api.Repository{
FullName: "cli/cli",
},
DisplayName: "scuba steve",
},
},
want: "jimmy cli/cli [trunk]: scuba steve",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := codespace{
Codespace: tt.fields.Codespace,
}
if got := c.displayName(tt.args.includeOwner); got != tt.want {
t.Errorf("codespace.displayName(includeOwnewr) = %v, want %v", got, tt.want)
}
})
}
}
func Test_formatCodespacesForSelect(t *testing.T) {
type args struct {
codespaces []*api.Codespace
}
tests := []struct {
name string
args args
wantCodespacesNames []string
}{
{
name: "One codespace: Shows only repo and branch name",
args: args{
codespaces: []*api.Codespace{
{
GitStatus: api.CodespaceGitStatus{
Ref: "trunk",
},
Repository: api.Repository{
FullName: "cli/cli",
},
DisplayName: "scuba steve",
},
},
},
wantCodespacesNames: []string{
"cli/cli [trunk]: scuba steve",
},
},
{
name: "Two codespaces on the same repo/branch: Adds the codespace's display name",
args: args{
codespaces: []*api.Codespace{
{
GitStatus: api.CodespaceGitStatus{
Ref: "trunk",
},
Repository: api.Repository{
FullName: "cli/cli",
},
DisplayName: "scuba steve",
},
{
GitStatus: api.CodespaceGitStatus{
Ref: "trunk",
},
Repository: api.Repository{
FullName: "cli/cli",
},
DisplayName: "flappy bird",
},
},
},
wantCodespacesNames: []string{
"cli/cli [trunk]: scuba steve",
"cli/cli [trunk]: flappy bird",
},
},
{
name: "Two codespaces on the different branches: Shows only repo and branch name",
args: args{
codespaces: []*api.Codespace{
{
GitStatus: api.CodespaceGitStatus{
Ref: "trunk",
},
Repository: api.Repository{
FullName: "cli/cli",
},
DisplayName: "scuba steve",
},
{
GitStatus: api.CodespaceGitStatus{
Ref: "feature",
},
Repository: api.Repository{
FullName: "cli/cli",
},
DisplayName: "flappy bird",
},
},
},
wantCodespacesNames: []string{
"cli/cli [trunk]: scuba steve",
"cli/cli [feature]: flappy bird",
},
},
{
name: "Two codespaces on the different repos: Shows only repo and branch name",
args: args{
codespaces: []*api.Codespace{
{
GitStatus: api.CodespaceGitStatus{
Ref: "trunk",
},
Repository: api.Repository{
FullName: "github/cli",
},
DisplayName: "scuba steve",
},
{
GitStatus: api.CodespaceGitStatus{
Ref: "trunk",
},
Repository: api.Repository{
FullName: "cli/cli",
},
DisplayName: "flappy bird",
},
},
},
wantCodespacesNames: []string{
"github/cli [trunk]: scuba steve",
"cli/cli [trunk]: flappy bird",
},
},
{
name: "Two codespaces on the same repo/branch, one dirty: Adds the codespace's display name and *",
args: args{
codespaces: []*api.Codespace{
{
GitStatus: api.CodespaceGitStatus{
Ref: "trunk",
},
Repository: api.Repository{
FullName: "cli/cli",
},
DisplayName: "scuba steve",
},
{
GitStatus: api.CodespaceGitStatus{
Ref: "trunk",
HasUncommittedChanges: true,
},
Repository: api.Repository{
FullName: "cli/cli",
},
DisplayName: "flappy bird",
},
},
},
wantCodespacesNames: []string{
"cli/cli [trunk]: scuba steve",
"cli/cli [trunk*]: flappy bird",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotCodespacesNames := formatCodespacesForSelect(tt.args.codespaces, false)
if !reflect.DeepEqual(gotCodespacesNames, tt.wantCodespacesNames) {
t.Errorf("codespacesNames: got %v, want %v", gotCodespacesNames, tt.wantCodespacesNames)
}
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/create.go | pkg/cmd/codespace/create.go | package codespace
import (
"context"
"errors"
"fmt"
"os"
"time"
"github.com/AlecAivazis/survey/v2"
"github.com/cli/cli/v2/internal/codespaces"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/spf13/cobra"
)
const (
DEVCONTAINER_PROMPT_DEFAULT = "Default Codespaces configuration"
)
const (
permissionsPollingInterval = 5 * time.Second
permissionsPollingTimeout = 1 * time.Minute
)
const (
displayNameMaxLength = 48 // 48 is the max length of the display name in the API
)
var (
DEFAULT_DEVCONTAINER_DEFINITIONS = []string{".devcontainer.json", ".devcontainer/devcontainer.json"}
)
type NullableDuration struct {
*time.Duration
}
func (d *NullableDuration) String() string {
if d.Duration != nil {
return d.Duration.String()
}
return ""
}
func (d *NullableDuration) Set(str string) error {
duration, err := time.ParseDuration(str)
if err != nil {
return fmt.Errorf("error parsing duration: %w", err)
}
d.Duration = &duration
return nil
}
func (d *NullableDuration) Type() string {
return "duration"
}
func (d *NullableDuration) Minutes() *int {
if d.Duration != nil {
retentionMinutes := int(d.Duration.Minutes())
return &retentionMinutes
}
return nil
}
type createOptions struct {
repo string
branch string
location string
machine string
showStatus bool
permissionsOptOut bool
devContainerPath string
idleTimeout time.Duration
retentionPeriod NullableDuration
displayName string
useWeb bool
}
func newCreateCmd(app *App) *cobra.Command {
opts := createOptions{}
createCmd := &cobra.Command{
Use: "create",
Short: "Create a codespace",
Args: noArgsConstraint,
PreRunE: func(cmd *cobra.Command, args []string) error {
return cmdutil.MutuallyExclusive(
"using --web with --display-name, --idle-timeout, or --retention-period is not supported",
opts.useWeb,
opts.displayName != "" || opts.idleTimeout != 0 || opts.retentionPeriod.Duration != nil,
)
},
RunE: func(cmd *cobra.Command, args []string) error {
return app.Create(cmd.Context(), opts)
},
}
createCmd.Flags().BoolVarP(&opts.useWeb, "web", "w", false, "Create codespace from browser, cannot be used with --display-name, --idle-timeout, or --retention-period")
createCmd.Flags().StringVarP(&opts.repo, "repo", "R", "", "Repository name with owner: user/repo")
if err := addDeprecatedRepoShorthand(createCmd, &opts.repo); err != nil {
fmt.Fprintf(app.io.ErrOut, "%v\n", err)
}
createCmd.Flags().StringVarP(&opts.branch, "branch", "b", "", "Repository branch")
createCmd.Flags().StringVarP(&opts.location, "location", "l", "", "Location: {EastUs|SouthEastAsia|WestEurope|WestUs2} (determined automatically if not provided)")
createCmd.Flags().StringVarP(&opts.machine, "machine", "m", "", "Hardware specifications for the VM")
createCmd.Flags().BoolVarP(&opts.permissionsOptOut, "default-permissions", "", false, "Do not prompt to accept additional permissions requested by the codespace")
createCmd.Flags().BoolVarP(&opts.showStatus, "status", "s", false, "Show status of post-create command and dotfiles")
createCmd.Flags().DurationVar(&opts.idleTimeout, "idle-timeout", 0, "Allowed inactivity before codespace is stopped, e.g. \"10m\", \"1h\"")
createCmd.Flags().Var(&opts.retentionPeriod, "retention-period", "Allowed time after shutting down before the codespace is automatically deleted (maximum 30 days), e.g. \"1h\", \"72h\"")
createCmd.Flags().StringVar(&opts.devContainerPath, "devcontainer-path", "", "Path to the devcontainer.json file to use when creating codespace")
createCmd.Flags().StringVarP(&opts.displayName, "display-name", "d", "", fmt.Sprintf("Display name for the codespace (%d characters or less)", displayNameMaxLength))
return createCmd
}
// Create creates a new Codespace
func (a *App) Create(ctx context.Context, opts createOptions) error {
// Overrides for Codespace developers to target test environments
vscsLocation := os.Getenv("VSCS_LOCATION")
vscsTarget := os.Getenv("VSCS_TARGET")
vscsTargetUrl := os.Getenv("VSCS_TARGET_URL")
userInputs := struct {
Repository string
Branch string
Location string
}{
Repository: opts.repo,
Branch: opts.branch,
Location: opts.location,
}
if opts.useWeb && userInputs.Repository == "" {
return a.browser.Browse(fmt.Sprintf("%s/codespaces/new", a.apiClient.ServerURL()))
}
prompter := &Prompter{}
promptForRepoAndBranch := userInputs.Repository == "" && !opts.useWeb
if promptForRepoAndBranch {
var defaultRepo string
if remotes, _ := a.remotes(); remotes != nil {
if defaultRemote, _ := remotes.ResolvedRemote(); defaultRemote != nil {
// this is a remote explicitly chosen via `repo set-default`
defaultRepo = ghrepo.FullName(defaultRemote)
} else if len(remotes) > 0 {
// as a fallback, just pick the first remote
defaultRepo = ghrepo.FullName(remotes[0])
}
}
repoQuestions := []*survey.Question{
{
Name: "repository",
Prompt: &survey.Input{
Message: "Repository:",
Help: "Search for repos by name. To search within an org or user, or to see private repos, enter at least ':user/'.",
Default: defaultRepo,
Suggest: func(toComplete string) []string {
return getRepoSuggestions(ctx, a.apiClient, toComplete)
},
},
Validate: survey.Required,
},
}
if err := prompter.Ask(repoQuestions, &userInputs); err != nil {
return fmt.Errorf("failed to prompt: %w", err)
}
}
if userInputs.Location == "" && vscsLocation != "" {
userInputs.Location = vscsLocation
}
var repository *api.Repository
err := a.RunWithProgress("Fetching repository", func() (err error) {
repository, err = a.apiClient.GetRepository(ctx, userInputs.Repository)
return
})
if err != nil {
return fmt.Errorf("error getting repository: %w", err)
}
var billableOwner *api.User
err = a.RunWithProgress("Validating repository for codespaces", func() (err error) {
billableOwner, err = a.apiClient.GetCodespaceBillableOwner(ctx, userInputs.Repository)
return
})
if err != nil {
return fmt.Errorf("error checking codespace ownership: %w", err)
} else if billableOwner != nil && (billableOwner.Type == "Organization" || billableOwner.Type == "User") {
cs := a.io.ColorScheme()
fmt.Fprintln(a.io.ErrOut, cs.Blue(" β Codespaces usage for this repository is paid for by "+billableOwner.Login))
}
if promptForRepoAndBranch {
branchPrompt := "Branch (leave blank for default branch):"
if userInputs.Branch != "" {
branchPrompt = "Branch:"
}
branchQuestions := []*survey.Question{
{
Name: "branch",
Prompt: &survey.Input{
Message: branchPrompt,
Default: userInputs.Branch,
},
},
}
if err := prompter.Ask(branchQuestions, &userInputs); err != nil {
return fmt.Errorf("failed to prompt: %w", err)
}
}
branch := userInputs.Branch
if branch == "" {
branch = repository.DefaultBranch
}
devContainerPath := opts.devContainerPath
// now that we have repo+branch, we can list available devcontainer.json files (if any)
if opts.devContainerPath == "" {
var devcontainers []api.DevContainerEntry
err = a.RunWithProgress("Fetching devcontainer.json files", func() (err error) {
devcontainers, err = a.apiClient.ListDevContainers(ctx, repository.ID, branch, 100)
return
})
if err != nil {
return fmt.Errorf("error getting devcontainer.json paths: %w", err)
}
if len(devcontainers) > 0 {
// if there is only one devcontainer.json file and it is one of the default paths we can auto-select it
if len(devcontainers) == 1 && stringInSlice(devcontainers[0].Path, DEFAULT_DEVCONTAINER_DEFINITIONS) {
devContainerPath = devcontainers[0].Path
} else {
promptOptions := []string{}
if !stringInSlice(devcontainers[0].Path, DEFAULT_DEVCONTAINER_DEFINITIONS) {
promptOptions = []string{DEVCONTAINER_PROMPT_DEFAULT}
}
for _, devcontainer := range devcontainers {
promptOptions = append(promptOptions, devcontainer.Path)
}
devContainerPathQuestion := &survey.Question{
Name: "devContainerPath",
Prompt: &survey.Select{
Message: "Devcontainer definition file:",
Options: promptOptions,
},
}
if err := prompter.Ask([]*survey.Question{devContainerPathQuestion}, &devContainerPath); err != nil {
return fmt.Errorf("failed to prompt: %w", err)
}
}
}
if devContainerPath == DEVCONTAINER_PROMPT_DEFAULT {
// special arg allows users to opt out of devcontainer.json selection
devContainerPath = ""
}
}
machine := opts.machine
// skip this if we have useWeb and no machine name provided,
// because web UI will select default machine type if none is provided
// web UI also provide a way to select machine type
// therefore we let the user choose from the web UI instead of prompting from CLI
if !(opts.useWeb && opts.machine == "") {
machine, err = getMachineName(ctx, a.apiClient, prompter, repository.ID, opts.machine, branch, userInputs.Location, devContainerPath)
if err != nil {
return fmt.Errorf("error getting machine type: %w", err)
}
if machine == "" {
return errors.New("there are no available machine types for this repository")
}
}
if len(opts.displayName) > displayNameMaxLength {
return fmt.Errorf("error creating codespace: display name should contain a maximum of %d characters", displayNameMaxLength)
}
createParams := &api.CreateCodespaceParams{
RepositoryID: repository.ID,
Branch: branch,
Machine: machine,
Location: userInputs.Location,
VSCSTarget: vscsTarget,
VSCSTargetURL: vscsTargetUrl,
IdleTimeoutMinutes: int(opts.idleTimeout.Minutes()),
RetentionPeriodMinutes: opts.retentionPeriod.Minutes(),
DevContainerPath: devContainerPath,
PermissionsOptOut: opts.permissionsOptOut,
DisplayName: opts.displayName,
}
if opts.useWeb {
return a.browser.Browse(fmt.Sprintf("%s/codespaces/new?repo=%d&ref=%s&machine=%s&location=%s", a.apiClient.ServerURL(), createParams.RepositoryID, createParams.Branch, createParams.Machine, createParams.Location))
}
var codespace *api.Codespace
err = a.RunWithProgress("Creating codespace", func() (err error) {
codespace, err = a.apiClient.CreateCodespace(ctx, createParams)
return
})
if err != nil {
var aerr api.AcceptPermissionsRequiredError
if !errors.As(err, &aerr) || aerr.AllowPermissionsURL == "" {
return fmt.Errorf("error creating codespace: %w", err)
}
codespace, err = a.handleAdditionalPermissions(ctx, prompter, createParams, aerr.AllowPermissionsURL)
if err != nil {
// this error could be a cmdutil.SilentError (in the case that the user opened the browser) so we don't want to wrap it
return err
}
}
if opts.showStatus {
if err := a.showStatus(ctx, codespace); err != nil {
return fmt.Errorf("show status: %w", err)
}
}
cs := a.io.ColorScheme()
fmt.Fprintln(a.io.Out, codespace.Name)
if a.io.IsStderrTTY() && codespace.IdleTimeoutNotice != "" {
fmt.Fprintln(a.io.ErrOut, cs.Yellow("Notice:"), codespace.IdleTimeoutNotice)
}
return nil
}
func (a *App) handleAdditionalPermissions(ctx context.Context, prompter SurveyPrompter, createParams *api.CreateCodespaceParams, allowPermissionsURL string) (*api.Codespace, error) {
var (
isInteractive = a.io.CanPrompt()
cs = a.io.ColorScheme()
)
fmt.Fprintf(a.io.ErrOut, "You must authorize or deny additional permissions requested by this codespace before continuing.\n")
if !isInteractive {
fmt.Fprintf(a.io.ErrOut, "%s in your browser to review and authorize additional permissions: %s\n", cs.Bold("Open this URL"), allowPermissionsURL)
fmt.Fprintf(a.io.ErrOut, "Alternatively, you can run %q with the %q option to continue without authorizing additional permissions.\n", a.io.ColorScheme().Bold("create"), cs.Bold("--default-permissions"))
return nil, cmdutil.SilentError
}
choices := []string{
"Continue in browser to review and authorize additional permissions (Recommended)",
"Continue without authorizing additional permissions",
}
permsSurvey := []*survey.Question{
{
Name: "accept",
Prompt: &survey.Select{
Message: "What would you like to do?",
Options: choices,
Default: choices[0],
},
Validate: survey.Required,
},
}
var answers struct {
Accept string
}
if err := prompter.Ask(permsSurvey, &answers); err != nil {
return nil, fmt.Errorf("error getting answers: %w", err)
}
// if the user chose to continue in the browser, open the URL
if answers.Accept == choices[0] {
if err := a.browser.Browse(allowPermissionsURL); err != nil {
return nil, fmt.Errorf("error opening browser: %w", err)
}
// Poll until the user has accepted the permissions or timeout
if err := a.pollForPermissions(ctx, createParams); err != nil {
return nil, fmt.Errorf("error polling for permissions: %w", err)
}
} else {
// If the user chose to create the codespace without the permissions,
// we can continue with the create opting out of the additional permissions
createParams.PermissionsOptOut = true
}
var codespace *api.Codespace
err := a.RunWithProgress("Creating codespace", func() (err error) {
codespace, err = a.apiClient.CreateCodespace(ctx, createParams)
return
})
if err != nil {
return nil, fmt.Errorf("error creating codespace: %w", err)
}
return codespace, nil
}
func (a *App) pollForPermissions(ctx context.Context, createParams *api.CreateCodespaceParams) error {
return a.RunWithProgress("Waiting for permissions to be accepted in the browser", func() (err error) {
ctx, cancel := context.WithTimeout(ctx, permissionsPollingTimeout)
defer cancel()
done := make(chan error, 1)
go func() {
for {
accepted, err := a.apiClient.GetCodespacesPermissionsCheck(ctx, createParams.RepositoryID, createParams.Branch, createParams.DevContainerPath)
if err != nil {
done <- err
return
}
if accepted {
done <- nil
return
}
// Wait before polling again
time.Sleep(permissionsPollingInterval)
}
}()
select {
case err := <-done:
return err
case <-ctx.Done():
return fmt.Errorf("timed out waiting for permissions to be accepted in the browser")
}
})
}
// showStatus polls the codespace for a list of post create states and their status. It will keep polling
// until all states have finished. Once all states have finished, we poll once more to check if any new
// states have been introduced and stop polling otherwise.
func (a *App) showStatus(ctx context.Context, codespace *api.Codespace) error {
var (
lastState codespaces.PostCreateState
breakNextState bool
)
finishedStates := make(map[string]bool)
ctx, stopPolling := context.WithCancel(ctx)
defer stopPolling()
poller := func(states []codespaces.PostCreateState) {
var inProgress bool
for _, state := range states {
if _, found := finishedStates[state.Name]; found {
continue // skip this state as we've processed it already
}
if state.Name != lastState.Name {
a.StartProgressIndicatorWithLabel(state.Name)
if state.Status == codespaces.PostCreateStateRunning {
inProgress = true
lastState = state
break
}
finishedStates[state.Name] = true
a.StopProgressIndicator()
} else {
if state.Status == codespaces.PostCreateStateRunning {
inProgress = true
break
}
finishedStates[state.Name] = true
a.StopProgressIndicator()
lastState = codespaces.PostCreateState{} // reset the value
}
}
if !inProgress {
if breakNextState {
stopPolling()
return
}
breakNextState = true
}
}
err := codespaces.PollPostCreateStates(ctx, a, a.apiClient, codespace, poller)
if err != nil {
if errors.Is(err, context.Canceled) && breakNextState {
return nil // we cancelled the context to stop polling, we can ignore the error
}
return fmt.Errorf("failed to poll state changes from codespace: %w", err)
}
return nil
}
// getMachineName prompts the user to select the machine type, or validates the machine if non-empty.
func getMachineName(ctx context.Context, apiClient apiClient, prompter SurveyPrompter, repoID int, machine, branch, location string, devcontainerPath string) (string, error) {
machines, err := apiClient.GetCodespacesMachines(ctx, repoID, branch, location, devcontainerPath)
if err != nil {
return "", fmt.Errorf("error requesting machine instance types: %w", err)
}
// if user supplied a machine type, it must be valid
// if no machine type was supplied, we don't error if there are no machine types for the current repo
if machine != "" {
for _, m := range machines {
if machine == m.Name {
return machine, nil
}
}
availableMachines := make([]string, len(machines))
for i := 0; i < len(machines); i++ {
availableMachines[i] = machines[i].Name
}
return "", fmt.Errorf("there is no such machine for the repository: %s\nAvailable machines: %v", machine, availableMachines)
} else if len(machines) == 0 {
return "", nil
}
if len(machines) == 1 {
// VS Code does not prompt for machine if there is only one, this makes us consistent with that behavior
return machines[0].Name, nil
}
machineNames := make([]string, 0, len(machines))
machineByName := make(map[string]*api.Machine)
for _, m := range machines {
machineName := buildDisplayName(m.DisplayName, m.PrebuildAvailability)
machineNames = append(machineNames, machineName)
machineByName[machineName] = m
}
machineSurvey := []*survey.Question{
{
Name: "machine",
Prompt: &survey.Select{
Message: "Choose Machine Type:",
Options: machineNames,
Default: machineNames[0],
},
Validate: survey.Required,
},
}
var machineAnswers struct{ Machine string }
if err := prompter.Ask(machineSurvey, &machineAnswers); err != nil {
return "", fmt.Errorf("error getting machine: %w", err)
}
selectedMachine := machineByName[machineAnswers.Machine]
return selectedMachine.Name, nil
}
func getRepoSuggestions(ctx context.Context, apiClient apiClient, partialSearch string) []string {
searchParams := api.RepoSearchParameters{
// The prompt shows 7 items so 7 effectively turns off scrolling which is similar behavior to other clients
MaxRepos: 7,
Sort: "repo",
}
repos, err := apiClient.GetCodespaceRepoSuggestions(ctx, partialSearch, searchParams)
if err != nil {
return nil
}
return repos
}
// buildDisplayName returns display name to be used in the machine survey prompt.
// prebuildAvailability will be migrated to use enum values: "none", "ready", "in_progress" before Prebuild GA
func buildDisplayName(displayName string, prebuildAvailability string) string {
switch prebuildAvailability {
case "ready":
return displayName + " (Prebuild ready)"
case "in_progress":
return displayName + " (Prebuild in progress)"
default:
return displayName
}
}
func stringInSlice(a string, slice []string) bool {
for _, b := range slice {
if b == a {
return true
}
}
return false
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/stop_test.go | pkg/cmd/codespace/stop_test.go | package codespace
import (
"context"
"fmt"
"testing"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/stretchr/testify/assert"
)
func TestApp_StopCodespace(t *testing.T) {
type fields struct {
apiClient apiClient
}
tests := []struct {
name string
fields fields
opts *stopOptions
}{
{
name: "Stop a codespace I own",
opts: &stopOptions{
selector: &CodespaceSelector{codespaceName: "test-codespace"},
},
fields: fields{
apiClient: &apiClientMock{
GetCodespaceFunc: func(ctx context.Context, name string, includeConnection bool) (*api.Codespace, error) {
if name != "test-codespace" {
return nil, fmt.Errorf("got codespace name %s, wanted %s", name, "test-codespace")
}
return &api.Codespace{
State: api.CodespaceStateAvailable,
}, nil
},
StopCodespaceFunc: func(ctx context.Context, name string, orgName string, userName string) error {
if name != "test-codespace" {
return fmt.Errorf("got codespace name %s, wanted %s", name, "test-codespace")
}
if orgName != "" {
return fmt.Errorf("got orgName %s, expected none", orgName)
}
return nil
},
},
},
},
{
name: "Stop a codespace as an org admin",
opts: &stopOptions{
selector: &CodespaceSelector{codespaceName: "test-codespace"},
orgName: "test-org",
userName: "test-user",
},
fields: fields{
apiClient: &apiClientMock{
GetOrgMemberCodespaceFunc: func(ctx context.Context, orgName string, userName string, codespaceName string) (*api.Codespace, error) {
if codespaceName != "test-codespace" {
return nil, fmt.Errorf("got codespace name %s, wanted %s", codespaceName, "test-codespace")
}
if orgName != "test-org" {
return nil, fmt.Errorf("got org name %s, wanted %s", orgName, "test-org")
}
if userName != "test-user" {
return nil, fmt.Errorf("got user name %s, wanted %s", userName, "test-user")
}
return &api.Codespace{
State: api.CodespaceStateAvailable,
}, nil
},
StopCodespaceFunc: func(ctx context.Context, codespaceName string, orgName string, userName string) error {
if codespaceName != "test-codespace" {
return fmt.Errorf("got codespace name %s, wanted %s", codespaceName, "test-codespace")
}
if orgName != "test-org" {
return fmt.Errorf("got org name %s, wanted %s", orgName, "test-org")
}
if userName != "test-user" {
return fmt.Errorf("got user name %s, wanted %s", userName, "test-user")
}
return nil
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
a := &App{
io: ios,
apiClient: tt.fields.apiClient,
}
err := a.StopCodespace(context.Background(), tt.opts)
assert.NoError(t, err)
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/rebuild.go | pkg/cmd/codespace/rebuild.go | package codespace
import (
"context"
"fmt"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/codespaces"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/cli/cli/v2/internal/codespaces/portforwarder"
"github.com/cli/cli/v2/internal/codespaces/rpc"
"github.com/spf13/cobra"
)
func newRebuildCmd(app *App) *cobra.Command {
var (
selector *CodespaceSelector
fullRebuild bool
)
rebuildCmd := &cobra.Command{
Use: "rebuild",
Short: "Rebuild a codespace",
Long: heredoc.Doc(`
Rebuilding recreates your codespace.
Your code and any current changes will be preserved. Your codespace will be rebuilt using
your working directory's dev container. A full rebuild also removes cached Docker images.
`),
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return app.Rebuild(cmd.Context(), selector, fullRebuild)
},
}
selector = AddCodespaceSelector(rebuildCmd, app.apiClient)
rebuildCmd.Flags().BoolVar(&fullRebuild, "full", false, "Perform a full rebuild")
return rebuildCmd
}
func (a *App) Rebuild(ctx context.Context, selector *CodespaceSelector, full bool) (err error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
codespace, err := selector.Select(ctx)
if err != nil {
return err
}
// There's no need to rebuild again because users can't modify their codespace while it rebuilds
if codespace.State == api.CodespaceStateRebuilding {
fmt.Fprintf(a.io.Out, "%s is already rebuilding\n", codespace.Name)
return nil
}
codespaceConnection, err := codespaces.GetCodespaceConnection(ctx, a, a.apiClient, codespace)
if err != nil {
return fmt.Errorf("error connecting to codespace: %w", err)
}
fwd, err := portforwarder.NewPortForwarder(ctx, codespaceConnection)
if err != nil {
return fmt.Errorf("failed to create port forwarder: %w", err)
}
defer safeClose(fwd, &err)
invoker, err := rpc.CreateInvoker(ctx, fwd)
if err != nil {
return err
}
defer safeClose(invoker, &err)
err = invoker.RebuildContainer(ctx, full)
if err != nil {
return fmt.Errorf("rebuilding codespace via session: %w", err)
}
fmt.Fprintf(a.io.Out, "%s is rebuilding\n", codespace.Name)
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/select.go | pkg/cmd/codespace/select.go | package codespace
import (
"context"
"fmt"
"os"
"github.com/spf13/cobra"
)
type selectOptions struct {
filePath string
selector *CodespaceSelector
}
func newSelectCmd(app *App) *cobra.Command {
var (
opts selectOptions
)
selectCmd := &cobra.Command{
Use: "select",
Short: "Select a Codespace",
Hidden: true,
Args: noArgsConstraint,
RunE: func(cmd *cobra.Command, args []string) error {
return app.Select(cmd.Context(), opts)
},
}
opts.selector = AddCodespaceSelector(selectCmd, app.apiClient)
selectCmd.Flags().StringVarP(&opts.filePath, "file", "f", "", "Output file path")
return selectCmd
}
// Hidden codespace `select` command allows to reuse existing codespace selection
// dialog by external GH CLI extensions. By default output selected codespace name
// into `stdout`. Pass `--file`(`-f`) flag along with a file path to output selected
// codespace name into a file instead.
//
// ## Examples
//
// With `stdout` output:
//
// ```shell
//
// gh codespace select
//
// ```
//
// With `into-a-file` output:
//
// ```shell
//
// gh codespace select --file /tmp/selected_codespace.txt
//
// ```
func (a *App) Select(ctx context.Context, opts selectOptions) (err error) {
codespace, err := opts.selector.Select(ctx)
if err != nil {
return err
}
if opts.filePath != "" {
f, err := os.Create(opts.filePath)
if err != nil {
return fmt.Errorf("failed to create output file: %w", err)
}
defer safeClose(f, &err)
_, err = f.WriteString(codespace.Name)
if err != nil {
return fmt.Errorf("failed to write codespace name to output file: %w", err)
}
return nil
}
fmt.Fprintln(a.io.Out, codespace.Name)
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/delete.go | pkg/cmd/codespace/delete.go | package codespace
import (
"context"
"errors"
"fmt"
"strings"
"sync/atomic"
"time"
"github.com/AlecAivazis/survey/v2"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/spf13/cobra"
"golang.org/x/sync/errgroup"
)
type deleteOptions struct {
deleteAll bool
skipConfirm bool
codespaceName string
repoFilter string
keepDays uint16
orgName string
userName string
repoOwner string
isInteractive bool
now func() time.Time
prompter prompter
}
//go:generate moq -fmt goimports -rm -skip-ensure -out mock_prompter.go . prompter
type prompter interface {
Confirm(message string) (bool, error)
}
func newDeleteCmd(app *App) *cobra.Command {
opts := deleteOptions{
isInteractive: hasTTY,
now: time.Now,
prompter: &surveyPrompter{},
}
var selector *CodespaceSelector
deleteCmd := &cobra.Command{
Use: "delete",
Short: "Delete codespaces",
Long: heredoc.Doc(`
Delete codespaces based on selection criteria.
All codespaces for the authenticated user can be deleted, as well as codespaces for a
specific repository. Alternatively, only codespaces older than N days can be deleted.
Organization administrators may delete any codespace billed to the organization.
`),
Args: noArgsConstraint,
RunE: func(cmd *cobra.Command, args []string) error {
// TODO: ideally we would use the selector directly, but the logic here is too intertwined with other flags to do so elegantly
// After the admin subcommand is added (see https://github.com/cli/cli/pull/6944#issuecomment-1419553639) we can revisit this.
opts.codespaceName = selector.codespaceName
opts.repoFilter = selector.repoName
opts.repoOwner = selector.repoOwner
if opts.deleteAll && opts.repoFilter != "" {
return cmdutil.FlagErrorf("both `--all` and `--repo` is not supported")
}
if opts.orgName != "" && opts.codespaceName != "" && opts.userName == "" {
return cmdutil.FlagErrorf("using `--org` with `--codespace` requires `--user`")
}
return app.Delete(cmd.Context(), opts)
},
}
selector = AddCodespaceSelector(deleteCmd, app.apiClient)
if err := addDeprecatedRepoShorthand(deleteCmd, &selector.repoName); err != nil {
fmt.Fprintf(app.io.ErrOut, "%v\n", err)
}
deleteCmd.Flags().BoolVar(&opts.deleteAll, "all", false, "Delete all codespaces")
deleteCmd.Flags().BoolVarP(&opts.skipConfirm, "force", "f", false, "Skip confirmation for codespaces that contain unsaved changes")
deleteCmd.Flags().Uint16Var(&opts.keepDays, "days", 0, "Delete codespaces older than `N` days")
deleteCmd.Flags().StringVarP(&opts.orgName, "org", "o", "", "The `login` handle of the organization (admin-only)")
deleteCmd.Flags().StringVarP(&opts.userName, "user", "u", "", "The `username` to delete codespaces for (used with --org)")
return deleteCmd
}
func (a *App) Delete(ctx context.Context, opts deleteOptions) (err error) {
var codespaces []*api.Codespace
nameFilter := opts.codespaceName
if nameFilter == "" {
err = a.RunWithProgress("Fetching codespaces", func() (fetchErr error) {
userName := opts.userName
if userName == "" && opts.orgName != "" {
currentUser, fetchErr := a.apiClient.GetUser(ctx)
if fetchErr != nil {
return fetchErr
}
userName = currentUser.Login
}
codespaces, fetchErr = a.apiClient.ListCodespaces(ctx, api.ListCodespacesOptions{OrgName: opts.orgName, UserName: userName})
if opts.repoOwner != "" {
codespaces = filterCodespacesByRepoOwner(codespaces, opts.repoOwner)
}
return
})
if err != nil {
return fmt.Errorf("error getting codespaces: %w", err)
}
if !opts.deleteAll && opts.repoFilter == "" {
includeUsername := opts.orgName != ""
c, err := chooseCodespaceFromList(ctx, codespaces, includeUsername, false)
if err != nil {
return fmt.Errorf("error choosing codespace: %w", err)
}
nameFilter = c.Name
}
} else {
var codespace *api.Codespace
err := a.RunWithProgress("Fetching codespace", func() (fetchErr error) {
if opts.orgName == "" || opts.userName == "" {
codespace, fetchErr = a.apiClient.GetCodespace(ctx, nameFilter, false)
} else {
codespace, fetchErr = a.apiClient.GetOrgMemberCodespace(ctx, opts.orgName, opts.userName, opts.codespaceName)
}
return
})
if err != nil {
return fmt.Errorf("error fetching codespace information: %w", err)
}
codespaces = []*api.Codespace{codespace}
}
codespacesToDelete := make([]*api.Codespace, 0, len(codespaces))
lastUpdatedCutoffTime := opts.now().AddDate(0, 0, -int(opts.keepDays))
for _, c := range codespaces {
if nameFilter != "" && c.Name != nameFilter {
continue
}
if opts.repoFilter != "" && !strings.EqualFold(c.Repository.FullName, opts.repoFilter) {
continue
}
if opts.keepDays > 0 {
t, err := time.Parse(time.RFC3339, c.LastUsedAt)
if err != nil {
return fmt.Errorf("error parsing last_used_at timestamp %q: %w", c.LastUsedAt, err)
}
if t.After(lastUpdatedCutoffTime) {
continue
}
}
if !opts.skipConfirm {
confirmed, err := confirmDeletion(opts.prompter, c, opts.isInteractive)
if err != nil {
return fmt.Errorf("unable to confirm: %w", err)
}
if !confirmed {
continue
}
}
codespacesToDelete = append(codespacesToDelete, c)
}
if len(codespacesToDelete) == 0 {
return errors.New("no codespaces to delete")
}
progressLabel := "Deleting codespace"
if len(codespacesToDelete) > 1 {
progressLabel = "Deleting codespaces"
}
var deletedCodespaces uint32
err = a.RunWithProgress(progressLabel, func() error {
var g errgroup.Group
for _, c := range codespacesToDelete {
codespaceName := c.Name
g.Go(func() error {
if err := a.apiClient.DeleteCodespace(ctx, codespaceName, opts.orgName, opts.userName); err != nil {
a.errLogger.Printf("error deleting codespace %q: %v\n", codespaceName, err)
return err
}
atomic.AddUint32(&deletedCodespaces, 1)
return nil
})
}
if err := g.Wait(); err != nil {
return fmt.Errorf("%d codespace(s) failed to delete", len(codespacesToDelete)-int(deletedCodespaces))
}
return nil
})
if a.io.IsStdoutTTY() && deletedCodespaces > 0 {
successMsg := fmt.Sprintf("%d codespace(s) deleted successfully\n", deletedCodespaces)
fmt.Fprint(a.io.ErrOut, successMsg)
}
return err
}
func confirmDeletion(p prompter, apiCodespace *api.Codespace, isInteractive bool) (bool, error) {
cs := codespace{apiCodespace}
if !cs.hasUnsavedChanges() {
return true, nil
}
if !isInteractive {
return false, fmt.Errorf("codespace %s has unsaved changes (use --force to override)", cs.Name)
}
return p.Confirm(fmt.Sprintf("Codespace %s has unsaved changes. OK to delete?", cs.Name))
}
type surveyPrompter struct{}
func (p *surveyPrompter) Confirm(message string) (bool, error) {
prompter := &Prompter{}
var confirmed struct {
Confirmed bool
}
q := []*survey.Question{
{
Name: "confirmed",
Prompt: &survey.Confirm{
Message: message,
},
},
}
if err := prompter.Ask(q, &confirmed); err != nil {
return false, fmt.Errorf("failed to prompt: %w", err)
}
return confirmed.Confirmed, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/create_test.go | pkg/cmd/codespace/create_test.go | package codespace
import (
"bytes"
"context"
"fmt"
"testing"
"time"
"github.com/AlecAivazis/survey/v2"
"github.com/cli/cli/v2/internal/browser"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
)
func TestCreateCmdFlagError(t *testing.T) {
tests := []struct {
name string
args string
wantsErr error
}{
{
name: "return error when using web flag with display-name, idle-timeout, or retention-period flags",
args: "--web --display-name foo --idle-timeout 30m",
wantsErr: fmt.Errorf("using --web with --display-name, --idle-timeout, or --retention-period is not supported"),
},
{
name: "return error when using web flag with one of display-name, idle-timeout or retention-period flags",
args: "--web --idle-timeout 30m",
wantsErr: fmt.Errorf("using --web with --display-name, --idle-timeout, or --retention-period is not supported"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
a := &App{
io: ios,
}
cmd := newCreateCmd(a)
args, _ := shlex.Split(tt.args)
cmd.SetArgs(args)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
_, err := cmd.ExecuteC()
assert.Error(t, err)
assert.EqualError(t, err, tt.wantsErr.Error())
})
}
}
func TestApp_Create(t *testing.T) {
type fields struct {
apiClient apiClient
}
tests := []struct {
name string
fields fields
opts createOptions
wantErr error
wantStdout string
wantStderr string
wantURL string
isTTY bool
}{
{
name: "create codespace with default branch and 30m idle timeout",
fields: fields{
apiClient: apiCreateDefaults(&apiClientMock{
CreateCodespaceFunc: func(ctx context.Context, params *api.CreateCodespaceParams) (*api.Codespace, error) {
if params.Branch != "main" {
return nil, fmt.Errorf("got branch %q, want %q", params.Branch, "main")
}
if params.IdleTimeoutMinutes != 30 {
return nil, fmt.Errorf("idle timeout minutes was %v", params.IdleTimeoutMinutes)
}
if *params.RetentionPeriodMinutes != 2880 {
return nil, fmt.Errorf("retention period minutes expected 2880, was %v", params.RetentionPeriodMinutes)
}
if params.DisplayName != "" {
return nil, fmt.Errorf("display name was %q, expected empty", params.DisplayName)
}
return &api.Codespace{
Name: "monalisa-dotfiles-abcd1234",
}, nil
},
}),
},
opts: createOptions{
repo: "monalisa/dotfiles",
branch: "",
machine: "GIGA",
showStatus: false,
idleTimeout: 30 * time.Minute,
retentionPeriod: NullableDuration{durationPtr(48 * time.Hour)},
},
wantStdout: "monalisa-dotfiles-abcd1234\n",
wantStderr: " β Codespaces usage for this repository is paid for by monalisa\n",
},
{
name: "create with explicit display name",
fields: fields{
apiClient: apiCreateDefaults(&apiClientMock{
CreateCodespaceFunc: func(ctx context.Context, params *api.CreateCodespaceParams) (*api.Codespace, error) {
if params.DisplayName != "funky flute" {
return nil, fmt.Errorf("expected display name %q, got %q", "funky flute", params.DisplayName)
}
return &api.Codespace{
Name: "monalisa-dotfiles-abcd1234",
}, nil
},
}),
},
opts: createOptions{
repo: "monalisa/dotfiles",
branch: "main",
displayName: "funky flute",
},
wantStdout: "monalisa-dotfiles-abcd1234\n",
wantStderr: " β Codespaces usage for this repository is paid for by monalisa\n",
},
{
name: "create codespace with default branch shows idle timeout notice if present",
fields: fields{
apiClient: apiCreateDefaults(&apiClientMock{
CreateCodespaceFunc: func(ctx context.Context, params *api.CreateCodespaceParams) (*api.Codespace, error) {
if params.Branch != "main" {
return nil, fmt.Errorf("got branch %q, want %q", params.Branch, "main")
}
if params.IdleTimeoutMinutes != 30 {
return nil, fmt.Errorf("idle timeout minutes was %v", params.IdleTimeoutMinutes)
}
if params.RetentionPeriodMinutes != nil {
return nil, fmt.Errorf("retention period minutes expected nil, was %v", params.RetentionPeriodMinutes)
}
if params.DevContainerPath != ".devcontainer/foobar/devcontainer.json" {
return nil, fmt.Errorf("got dev container path %q, want %q", params.DevContainerPath, ".devcontainer/foobar/devcontainer.json")
}
return &api.Codespace{
Name: "monalisa-dotfiles-abcd1234",
}, nil
},
}),
},
opts: createOptions{
repo: "monalisa/dotfiles",
branch: "",
machine: "GIGA",
showStatus: false,
idleTimeout: 30 * time.Minute,
devContainerPath: ".devcontainer/foobar/devcontainer.json",
},
wantStdout: "monalisa-dotfiles-abcd1234\n",
wantStderr: " β Codespaces usage for this repository is paid for by monalisa\n",
},
{
name: "create codespace with nonexistent machine results in error",
fields: fields{
apiClient: apiCreateDefaults(&apiClientMock{
GetCodespacesMachinesFunc: func(ctx context.Context, repoID int, branch, location string, devcontainerPath string) ([]*api.Machine, error) {
return []*api.Machine{
{
Name: "GIGA",
DisplayName: "Gigabits of a machine",
},
{
Name: "TERA",
DisplayName: "Terabits of a machine",
},
}, nil
},
}),
},
opts: createOptions{
repo: "monalisa/dotfiles",
machine: "MEGA",
},
wantStderr: " β Codespaces usage for this repository is paid for by monalisa\n",
wantErr: fmt.Errorf("error getting machine type: there is no such machine for the repository: %s\nAvailable machines: %v", "MEGA", []string{"GIGA", "TERA"}),
},
{
name: "create codespace with display name more than 48 characters results in error",
fields: fields{
apiClient: apiCreateDefaults(&apiClientMock{
CreateCodespaceFunc: func(ctx context.Context, params *api.CreateCodespaceParams) (*api.Codespace, error) {
return &api.Codespace{
Name: "monalisa-dotfiles-abcd1234",
}, nil
},
}),
},
opts: createOptions{
repo: "monalisa/dotfiles",
machine: "GIGA",
displayName: "this-is-very-long-display-name-with-49-characters",
},
wantStderr: " β Codespaces usage for this repository is paid for by monalisa\n",
wantErr: fmt.Errorf("error creating codespace: display name should contain a maximum of %d characters", displayNameMaxLength),
},
{
name: "create codespace with devcontainer path results in selecting the correct machine type",
fields: fields{
apiClient: apiCreateDefaults(&apiClientMock{
GetCodespacesMachinesFunc: func(ctx context.Context, repoID int, branch, location string, devcontainerPath string) ([]*api.Machine, error) {
if devcontainerPath == "" {
return []*api.Machine{
{
Name: "GIGA",
DisplayName: "Gigabits of a machine",
},
}, nil
} else {
return []*api.Machine{
{
Name: "MEGA",
DisplayName: "Megabits of a machine",
},
{
Name: "GIGA",
DisplayName: "Gigabits of a machine",
},
}, nil
}
},
CreateCodespaceFunc: func(ctx context.Context, params *api.CreateCodespaceParams) (*api.Codespace, error) {
if params.Branch != "main" {
return nil, fmt.Errorf("got branch %q, want %q", params.Branch, "main")
}
if params.IdleTimeoutMinutes != 30 {
return nil, fmt.Errorf("idle timeout minutes was %v", params.IdleTimeoutMinutes)
}
if params.RetentionPeriodMinutes != nil {
return nil, fmt.Errorf("retention period minutes expected nil, was %v", params.RetentionPeriodMinutes)
}
if params.DevContainerPath != ".devcontainer/foobar/devcontainer.json" {
return nil, fmt.Errorf("got dev container path %q, want %q", params.DevContainerPath, ".devcontainer/foobar/devcontainer.json")
}
if params.Machine != "MEGA" {
return nil, fmt.Errorf("want machine %q, got %q", "MEGA", params.Machine)
}
return &api.Codespace{
Name: "monalisa-dotfiles-abcd1234",
Machine: api.CodespaceMachine{
Name: "MEGA",
DisplayName: "Megabits of a machine",
},
}, nil
},
}),
},
opts: createOptions{
repo: "monalisa/dotfiles",
branch: "",
machine: "MEGA",
showStatus: false,
idleTimeout: 30 * time.Minute,
devContainerPath: ".devcontainer/foobar/devcontainer.json",
},
wantStdout: "monalisa-dotfiles-abcd1234\n",
wantStderr: " β Codespaces usage for this repository is paid for by monalisa\n",
},
{
name: "create codespace with default branch with default devcontainer if no path provided and no devcontainer files exist in the repo",
fields: fields{
apiClient: apiCreateDefaults(&apiClientMock{
ListDevContainersFunc: func(ctx context.Context, repoID int, branch string, limit int) ([]api.DevContainerEntry, error) {
return []api.DevContainerEntry{}, nil
},
CreateCodespaceFunc: func(ctx context.Context, params *api.CreateCodespaceParams) (*api.Codespace, error) {
if params.Branch != "main" {
return nil, fmt.Errorf("got branch %q, want %q", params.Branch, "main")
}
if params.IdleTimeoutMinutes != 30 {
return nil, fmt.Errorf("idle timeout minutes was %v", params.IdleTimeoutMinutes)
}
if params.DevContainerPath != "" {
return nil, fmt.Errorf("got dev container path %q, want %q", params.DevContainerPath, ".devcontainer/foobar/devcontainer.json")
}
return &api.Codespace{
Name: "monalisa-dotfiles-abcd1234",
IdleTimeoutNotice: "Idle timeout for this codespace is set to 10 minutes in compliance with your organization's policy",
}, nil
},
}),
},
opts: createOptions{
repo: "monalisa/dotfiles",
branch: "",
machine: "GIGA",
showStatus: false,
idleTimeout: 30 * time.Minute,
},
wantStdout: "monalisa-dotfiles-abcd1234\n",
wantStderr: " β Codespaces usage for this repository is paid for by monalisa\nNotice: Idle timeout for this codespace is set to 10 minutes in compliance with your organization's policy\n",
isTTY: true,
},
{
name: "returns error when getting devcontainer paths fails",
fields: fields{
apiClient: apiCreateDefaults(&apiClientMock{
ListDevContainersFunc: func(ctx context.Context, repoID int, branch string, limit int) ([]api.DevContainerEntry, error) {
return nil, fmt.Errorf("some error")
},
}),
},
opts: createOptions{
repo: "monalisa/dotfiles",
branch: "",
machine: "GIGA",
showStatus: false,
idleTimeout: 30 * time.Minute,
},
wantErr: fmt.Errorf("error getting devcontainer.json paths: some error"),
wantStderr: " β Codespaces usage for this repository is paid for by monalisa\n",
},
{
name: "create codespace with default branch does not show idle timeout notice if not conntected to terminal",
fields: fields{
apiClient: apiCreateDefaults(&apiClientMock{
CreateCodespaceFunc: func(ctx context.Context, params *api.CreateCodespaceParams) (*api.Codespace, error) {
if params.Branch != "main" {
return nil, fmt.Errorf("got branch %q, want %q", params.Branch, "main")
}
if params.IdleTimeoutMinutes != 30 {
return nil, fmt.Errorf("idle timeout minutes was %v", params.IdleTimeoutMinutes)
}
return &api.Codespace{
Name: "monalisa-dotfiles-abcd1234",
IdleTimeoutNotice: "Idle timeout for this codespace is set to 10 minutes in compliance with your organization's policy",
}, nil
},
}),
},
opts: createOptions{
repo: "monalisa/dotfiles",
branch: "",
machine: "GIGA",
showStatus: false,
idleTimeout: 30 * time.Minute,
},
wantStdout: "monalisa-dotfiles-abcd1234\n",
wantStderr: " β Codespaces usage for this repository is paid for by monalisa\n",
isTTY: false,
},
{
name: "create codespace that requires accepting additional permissions",
fields: fields{
apiClient: apiCreateDefaults(&apiClientMock{
CreateCodespaceFunc: func(ctx context.Context, params *api.CreateCodespaceParams) (*api.Codespace, error) {
if params.Branch != "main" {
return nil, fmt.Errorf("got branch %q, want %q", params.Branch, "main")
}
if params.IdleTimeoutMinutes != 30 {
return nil, fmt.Errorf("idle timeout minutes was %v", params.IdleTimeoutMinutes)
}
return &api.Codespace{}, api.AcceptPermissionsRequiredError{
AllowPermissionsURL: "https://example.com/permissions",
}
},
}),
},
opts: createOptions{
repo: "monalisa/dotfiles",
branch: "",
machine: "GIGA",
showStatus: false,
idleTimeout: 30 * time.Minute,
},
wantErr: cmdutil.SilentError,
wantStderr: ` β Codespaces usage for this repository is paid for by monalisa
You must authorize or deny additional permissions requested by this codespace before continuing.
Open this URL in your browser to review and authorize additional permissions: https://example.com/permissions
Alternatively, you can run "create" with the "--default-permissions" option to continue without authorizing additional permissions.
`,
},
{
name: "create codespace that requires accepting additional permissions for devcontainer path",
fields: fields{
apiClient: apiCreateDefaults(&apiClientMock{
CreateCodespaceFunc: func(ctx context.Context, params *api.CreateCodespaceParams) (*api.Codespace, error) {
if params.Branch != "feature-branch" {
return nil, fmt.Errorf("got branch %q, want %q", params.Branch, "main")
}
if params.IdleTimeoutMinutes != 30 {
return nil, fmt.Errorf("idle timeout minutes was %v", params.IdleTimeoutMinutes)
}
return &api.Codespace{}, api.AcceptPermissionsRequiredError{
AllowPermissionsURL: "https://example.com/permissions?ref=feature-branch&devcontainer_path=.devcontainer/actions/devcontainer.json",
}
},
}),
},
opts: createOptions{
repo: "monalisa/dotfiles",
branch: "feature-branch",
devContainerPath: ".devcontainer/actions/devcontainer.json",
machine: "GIGA",
showStatus: false,
idleTimeout: 30 * time.Minute,
},
wantErr: cmdutil.SilentError,
wantStderr: ` β Codespaces usage for this repository is paid for by monalisa
You must authorize or deny additional permissions requested by this codespace before continuing.
Open this URL in your browser to review and authorize additional permissions: https://example.com/permissions?ref=feature-branch&devcontainer_path=.devcontainer/actions/devcontainer.json
Alternatively, you can run "create" with the "--default-permissions" option to continue without authorizing additional permissions.
`,
},
{
name: "returns error when user can't create codepaces for a repository",
fields: fields{
apiClient: apiCreateDefaults(&apiClientMock{
GetCodespaceBillableOwnerFunc: func(ctx context.Context, nwo string) (*api.User, error) {
return nil, fmt.Errorf("some error")
},
}),
},
opts: createOptions{
repo: "megacorp/private",
branch: "",
machine: "GIGA",
showStatus: false,
idleTimeout: 30 * time.Minute,
},
wantErr: fmt.Errorf("error checking codespace ownership: some error"),
},
{
name: "mentions User as billable owner when org does not cover codepaces for a repository",
fields: fields{
apiClient: apiCreateDefaults(&apiClientMock{
GetCodespaceBillableOwnerFunc: func(ctx context.Context, nwo string) (*api.User, error) {
return &api.User{
Type: "User",
Login: "monalisa",
}, nil
},
CreateCodespaceFunc: func(ctx context.Context, params *api.CreateCodespaceParams) (*api.Codespace, error) {
return &api.Codespace{
Name: "monalisa-dotfiles-abcd1234",
}, nil
},
}),
},
opts: createOptions{
repo: "monalisa/dotfiles",
branch: "main",
},
wantStderr: " β Codespaces usage for this repository is paid for by monalisa\n",
wantStdout: "monalisa-dotfiles-abcd1234\n",
},
{
name: "mentions Organization as billable owner when org covers codepaces for a repository",
fields: fields{
apiClient: apiCreateDefaults(&apiClientMock{
GetCodespaceBillableOwnerFunc: func(ctx context.Context, nwo string) (*api.User, error) {
return &api.User{
Type: "Organization",
Login: "megacorp",
}, nil
},
CreateCodespaceFunc: func(ctx context.Context, params *api.CreateCodespaceParams) (*api.Codespace, error) {
return &api.Codespace{
Name: "megacorp-private-abcd1234",
}, nil
},
}),
},
opts: createOptions{
repo: "megacorp/private",
branch: "",
machine: "GIGA",
showStatus: false,
idleTimeout: 30 * time.Minute,
},
wantStderr: " β Codespaces usage for this repository is paid for by megacorp\n",
wantStdout: "megacorp-private-abcd1234\n",
},
{
name: "does not mention billable owner when not an expected type",
fields: fields{
apiClient: apiCreateDefaults(&apiClientMock{
GetCodespaceBillableOwnerFunc: func(ctx context.Context, nwo string) (*api.User, error) {
return &api.User{
Type: "UnexpectedBillableOwnerType",
Login: "mega-owner",
}, nil
},
CreateCodespaceFunc: func(ctx context.Context, params *api.CreateCodespaceParams) (*api.Codespace, error) {
return &api.Codespace{
Name: "megacorp-private-abcd1234",
}, nil
},
}),
},
opts: createOptions{
repo: "megacorp/private",
},
wantStdout: "megacorp-private-abcd1234\n",
},
{
name: "return default url when using web flag without other flags",
fields: fields{
apiClient: apiCreateDefaults(&apiClientMock{
ServerURLFunc: func() string {
return "https://github.com"
},
}),
},
opts: createOptions{
useWeb: true,
},
wantURL: "https://github.com/codespaces/new",
},
{
name: "return custom server url when using web flag",
fields: fields{
apiClient: apiCreateDefaults(&apiClientMock{
ServerURLFunc: func() string {
return "https://github.mycompany.com"
},
}),
},
opts: createOptions{
useWeb: true,
},
wantURL: "https://github.mycompany.com/codespaces/new",
},
{
name: "skip machine check when using web flag and no machine provided",
fields: fields{
apiClient: apiCreateDefaults(&apiClientMock{
GetRepositoryFunc: func(ctx context.Context, nwo string) (*api.Repository, error) {
return &api.Repository{
ID: 123,
DefaultBranch: "main",
}, nil
},
CreateCodespaceFunc: func(ctx context.Context, params *api.CreateCodespaceParams) (*api.Codespace, error) {
return &api.Codespace{
Name: "monalisa-dotfiles-abcd1234",
}, nil
},
ServerURLFunc: func() string {
return "https://github.com"
},
}),
},
opts: createOptions{
repo: "monalisa/dotfiles",
useWeb: true,
branch: "custom",
location: "EastUS",
},
wantStderr: " β Codespaces usage for this repository is paid for by monalisa\n",
wantURL: fmt.Sprintf("https://github.com/codespaces/new?repo=%d&ref=%s&machine=%s&location=%s", 123, "custom", "", "EastUS"),
},
{
name: "return correct url with correct params when using web flag and repo flag",
fields: fields{
apiClient: apiCreateDefaults(&apiClientMock{
GetRepositoryFunc: func(ctx context.Context, nwo string) (*api.Repository, error) {
return &api.Repository{
ID: 123,
DefaultBranch: "main",
}, nil
},
CreateCodespaceFunc: func(ctx context.Context, params *api.CreateCodespaceParams) (*api.Codespace, error) {
return &api.Codespace{
Name: "monalisa-dotfiles-abcd1234",
}, nil
},
ServerURLFunc: func() string {
return "https://github.com"
},
}),
},
opts: createOptions{
repo: "monalisa/dotfiles",
useWeb: true,
},
wantStderr: " β Codespaces usage for this repository is paid for by monalisa\n",
wantURL: fmt.Sprintf("https://github.com/codespaces/new?repo=%d&ref=%s&machine=%s&location=%s", 123, "main", "", ""),
},
{
name: "return correct url with correct params when using web flag, repo, branch, location, machine flag",
fields: fields{
apiClient: apiCreateDefaults(&apiClientMock{
GetRepositoryFunc: func(ctx context.Context, nwo string) (*api.Repository, error) {
return &api.Repository{
ID: 123,
DefaultBranch: "main",
}, nil
},
CreateCodespaceFunc: func(ctx context.Context, params *api.CreateCodespaceParams) (*api.Codespace, error) {
return &api.Codespace{
Name: "monalisa-dotfiles-abcd1234",
Machine: api.CodespaceMachine{Name: "GIGA"},
}, nil
},
ServerURLFunc: func() string {
return "https://github.com"
},
}),
},
opts: createOptions{
repo: "monalisa/dotfiles",
machine: "GIGA",
branch: "custom",
location: "EastUS",
useWeb: true,
},
wantStderr: " β Codespaces usage for this repository is paid for by monalisa\n",
wantURL: fmt.Sprintf("https://github.com/codespaces/new?repo=%d&ref=%s&machine=%s&location=%s", 123, "custom", "GIGA", "EastUS"),
},
}
var a *App
var b *browser.Stub
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdoutTTY(tt.isTTY)
ios.SetStdinTTY(tt.isTTY)
ios.SetStderrTTY(tt.isTTY)
if tt.opts.useWeb {
b = &browser.Stub{}
a = &App{
io: ios,
apiClient: tt.fields.apiClient,
browser: b,
}
} else {
a = &App{
io: ios,
apiClient: tt.fields.apiClient,
}
}
err := a.Create(context.Background(), tt.opts)
if err != nil && tt.wantErr != nil {
assert.EqualError(t, err, tt.wantErr.Error())
}
if err != nil && tt.wantErr == nil {
t.Log(err.Error())
}
if got := stdout.String(); got != tt.wantStdout {
t.Log(t.Name())
t.Errorf(" stdout = %v, want %v", got, tt.wantStdout)
}
if got := stderr.String(); got != tt.wantStderr {
t.Log(t.Name())
t.Errorf(" stderr = %v, want %v", got, tt.wantStderr)
}
if tt.opts.useWeb {
b.Verify(t, tt.wantURL)
}
})
}
}
func TestBuildDisplayName(t *testing.T) {
tests := []struct {
name string
prebuildAvailability string
expectedDisplayName string
}{
{
name: "prebuild availability is none",
prebuildAvailability: "none",
expectedDisplayName: "4 cores, 8 GB RAM, 32 GB storage",
},
{
name: "prebuild availability is empty",
prebuildAvailability: "",
expectedDisplayName: "4 cores, 8 GB RAM, 32 GB storage",
},
{
name: "prebuild availability is ready",
prebuildAvailability: "ready",
expectedDisplayName: "4 cores, 8 GB RAM, 32 GB storage (Prebuild ready)",
},
{
name: "prebuild availability is in_progress",
prebuildAvailability: "in_progress",
expectedDisplayName: "4 cores, 8 GB RAM, 32 GB storage (Prebuild in progress)",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
displayName := buildDisplayName("4 cores, 8 GB RAM, 32 GB storage", tt.prebuildAvailability)
if displayName != tt.expectedDisplayName {
t.Errorf("displayName = %q, expectedDisplayName %q", displayName, tt.expectedDisplayName)
}
})
}
}
type MockSurveyPrompter struct {
AskFunc func(qs []*survey.Question, response interface{}) error
}
func (m *MockSurveyPrompter) Ask(qs []*survey.Question, response interface{}) error {
return m.AskFunc(qs, response)
}
type MockBrowser struct {
Err error
}
func (b *MockBrowser) Browse(url string) error {
if b.Err != nil {
return b.Err
}
return nil
}
func TestHandleAdditionalPermissions(t *testing.T) {
tests := []struct {
name string
isInteractive bool
accept string
permissionsOptOut bool
browserErr error
pollForPermissionsErr error
createCodespaceErr error
wantErr bool
}{
{
name: "non-interactive",
isInteractive: false,
permissionsOptOut: false,
wantErr: true,
},
{
name: "interactive, continue in browser, browser error",
isInteractive: true,
accept: "Continue in browser to review and authorize additional permissions (Recommended)",
permissionsOptOut: false,
browserErr: fmt.Errorf("browser error"),
wantErr: true,
},
{
name: "interactive, continue in browser, poll for permissions error",
isInteractive: true,
accept: "Continue in browser to review and authorize additional permissions (Recommended)",
permissionsOptOut: false,
pollForPermissionsErr: fmt.Errorf("poll for permissions error"),
wantErr: true,
},
{
name: "interactive, continue in browser, create codespace error",
isInteractive: true,
accept: "Continue in browser to review and authorize additional permissions (Recommended)",
permissionsOptOut: false,
createCodespaceErr: fmt.Errorf("create codespace error"),
wantErr: true,
},
{
name: "interactive, continue without authorizing",
isInteractive: true,
accept: "Continue without authorizing additional permissions",
permissionsOptOut: true,
createCodespaceErr: fmt.Errorf("create codespace error"),
wantErr: true,
},
{
name: "interactive, continue without authorizing, create codespace success",
isInteractive: true,
accept: "Continue without authorizing additional permissions",
permissionsOptOut: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
a := &App{
io: ios,
browser: &MockBrowser{
Err: tt.browserErr,
},
apiClient: &apiClientMock{
CreateCodespaceFunc: func(ctx context.Context, params *api.CreateCodespaceParams) (*api.Codespace, error) {
return nil, tt.createCodespaceErr
},
GetCodespacesPermissionsCheckFunc: func(ctx context.Context, repoID int, branch string, devcontainerPath string) (bool, error) {
if tt.pollForPermissionsErr != nil {
return false, tt.pollForPermissionsErr
}
return true, nil
},
},
}
if tt.isInteractive {
a.io.SetStdinTTY(true)
a.io.SetStdoutTTY(true)
a.io.SetStderrTTY(true)
}
params := &api.CreateCodespaceParams{}
_, err := a.handleAdditionalPermissions(context.Background(), &MockSurveyPrompter{
AskFunc: func(qs []*survey.Question, response interface{}) error {
*response.(*struct{ Accept string }) = struct{ Accept string }{Accept: tt.accept}
return nil
},
}, params, "http://example.com")
if (err != nil) != tt.wantErr {
t.Errorf("handleAdditionalPermissions() error = %v, wantErr %v", err, tt.wantErr)
}
if tt.permissionsOptOut != params.PermissionsOptOut {
t.Errorf("handleAdditionalPermissions() permissionsOptOut = %v, want %v", params.PermissionsOptOut, tt.permissionsOptOut)
}
})
}
}
func apiCreateDefaults(c *apiClientMock) *apiClientMock {
if c.GetRepositoryFunc == nil {
c.GetRepositoryFunc = func(ctx context.Context, nwo string) (*api.Repository, error) {
return &api.Repository{
ID: 1234,
FullName: nwo,
DefaultBranch: "main",
}, nil
}
}
if c.GetCodespaceBillableOwnerFunc == nil {
c.GetCodespaceBillableOwnerFunc = func(ctx context.Context, nwo string) (*api.User, error) {
return &api.User{
Login: "monalisa",
Type: "User",
}, nil
}
}
if c.ListDevContainersFunc == nil {
c.ListDevContainersFunc = func(ctx context.Context, repoID int, branch string, limit int) ([]api.DevContainerEntry, error) {
return []api.DevContainerEntry{{Path: ".devcontainer/devcontainer.json"}}, nil
}
}
if c.GetCodespacesMachinesFunc == nil {
c.GetCodespacesMachinesFunc = func(ctx context.Context, repoID int, branch, location string, devcontainerPath string) ([]*api.Machine, error) {
return []*api.Machine{
{
Name: "GIGA",
DisplayName: "Gigabits of a machine",
},
}, nil
}
}
return c
}
func durationPtr(d time.Duration) *time.Duration {
return &d
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/edit.go | pkg/cmd/codespace/edit.go | package codespace
import (
"context"
"errors"
"fmt"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/spf13/cobra"
)
type editOptions struct {
selector *CodespaceSelector
displayName string
machine string
}
func newEditCmd(app *App) *cobra.Command {
opts := editOptions{}
editCmd := &cobra.Command{
Use: "edit",
Short: "Edit a codespace",
Args: noArgsConstraint,
RunE: func(cmd *cobra.Command, args []string) error {
if opts.displayName == "" && opts.machine == "" {
return cmdutil.FlagErrorf("must provide `--display-name` or `--machine`")
}
return app.Edit(cmd.Context(), opts)
},
}
opts.selector = AddCodespaceSelector(editCmd, app.apiClient)
editCmd.Flags().StringVarP(&opts.displayName, "display-name", "d", "", "Set the display name")
editCmd.Flags().StringVar(&opts.displayName, "displayName", "", "Display name")
if err := editCmd.Flags().MarkDeprecated("displayName", "use `--display-name` instead"); err != nil {
fmt.Fprintf(app.io.ErrOut, "error marking flag as deprecated: %v\n", err)
}
editCmd.Flags().StringVarP(&opts.machine, "machine", "m", "", "Set hardware specifications for the VM")
return editCmd
}
// Edits a codespace
func (a *App) Edit(ctx context.Context, opts editOptions) error {
codespaceName, err := opts.selector.SelectName(ctx)
if err != nil {
// TODO: is there a cleaner way to do this?
if errors.Is(err, errNoCodespaces) || errors.Is(err, errNoFilteredCodespaces) {
return err
}
return fmt.Errorf("error choosing codespace: %w", err)
}
err = a.RunWithProgress("Editing codespace", func() (err error) {
_, err = a.apiClient.EditCodespace(ctx, codespaceName, &api.EditCodespaceParams{
DisplayName: opts.displayName,
Machine: opts.machine,
})
return
})
if err != nil {
return fmt.Errorf("error editing codespace: %w", err)
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/code_test.go | pkg/cmd/codespace/code_test.go | package codespace
import (
"context"
"testing"
"github.com/cli/cli/v2/internal/browser"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/cli/cli/v2/pkg/iostreams"
)
func TestApp_VSCode(t *testing.T) {
type args struct {
codespaceName string
useInsiders bool
useWeb bool
}
tests := []struct {
name string
args args
wantErr bool
wantURL string
}{
{
name: "open VS Code",
args: args{
codespaceName: "monalisa-cli-cli-abcdef",
useInsiders: false,
},
wantErr: false,
wantURL: "vscode://github.codespaces/connect?name=monalisa-cli-cli-abcdef&windowId=_blank",
},
{
name: "open VS Code Insiders",
args: args{
codespaceName: "monalisa-cli-cli-abcdef",
useInsiders: true,
},
wantErr: false,
wantURL: "vscode-insiders://github.codespaces/connect?name=monalisa-cli-cli-abcdef&windowId=_blank",
},
{
name: "open VS Code web",
args: args{
codespaceName: "monalisa-cli-cli-abcdef",
useInsiders: false,
useWeb: true,
},
wantErr: false,
wantURL: "https://monalisa-cli-cli-abcdef.github.dev",
},
{
name: "open VS Code web with Insiders",
args: args{
codespaceName: "monalisa-cli-cli-abcdef",
useInsiders: true,
useWeb: true,
},
wantErr: false,
wantURL: "https://monalisa-cli-cli-abcdef.github.dev?vscodeChannel=insiders",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
b := &browser.Stub{}
ios, _, stdout, stderr := iostreams.Test()
a := &App{
browser: b,
apiClient: testCodeApiMock(),
io: ios,
}
selector := &CodespaceSelector{api: a.apiClient, codespaceName: tt.args.codespaceName}
if err := a.VSCode(context.Background(), selector, tt.args.useInsiders, tt.args.useWeb); (err != nil) != tt.wantErr {
t.Errorf("App.VSCode() error = %v, wantErr %v", err, tt.wantErr)
}
b.Verify(t, tt.wantURL)
if got := stdout.String(); got != "" {
t.Errorf("stdout = %q, want %q", got, "")
}
if got := stderr.String(); got != "" {
t.Errorf("stderr = %q, want %q", got, "")
}
})
}
}
func TestPendingOperationDisallowsCode(t *testing.T) {
app := testingCodeApp()
selector := &CodespaceSelector{api: app.apiClient, codespaceName: "disabledCodespace"}
if err := app.VSCode(context.Background(), selector, false, false); err != nil {
if err.Error() != "codespace is disabled while it has a pending operation: Some pending operation" {
t.Errorf("expected pending operation error, but got: %v", err)
}
} else {
t.Error("expected pending operation error, but got nothing")
}
}
func testingCodeApp() *App {
ios, _, _, _ := iostreams.Test()
return NewApp(ios, nil, testCodeApiMock(), nil, nil)
}
func testCodeApiMock() *apiClientMock {
testingCodespace := &api.Codespace{
Name: "monalisa-cli-cli-abcdef",
WebURL: "https://monalisa-cli-cli-abcdef.github.dev",
}
disabledCodespace := &api.Codespace{
Name: "disabledCodespace",
PendingOperation: true,
PendingOperationDisabledReason: "Some pending operation",
}
return &apiClientMock{
GetCodespaceFunc: func(_ context.Context, name string, _ bool) (*api.Codespace, error) {
if name == "disabledCodespace" {
return disabledCodespace, nil
}
return testingCodespace, nil
},
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/delete_test.go | pkg/cmd/codespace/delete_test.go | package codespace
import (
"context"
"errors"
"fmt"
"slices"
"sort"
"strings"
"testing"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/cli/cli/v2/pkg/iostreams"
)
func TestDelete(t *testing.T) {
now, _ := time.Parse(time.RFC3339, "2021-09-22T00:00:00Z")
daysAgo := func(n int) string {
return now.Add(time.Hour * -time.Duration(24*n)).Format(time.RFC3339)
}
tests := []struct {
name string
opts deleteOptions
codespaces []*api.Codespace
confirms map[string]bool
deleteErr error
wantErr string
wantDeleted []string
wantStdout string
wantStderr string
}{
{
name: "by name",
opts: deleteOptions{
codespaceName: "hubot-robawt-abc",
},
codespaces: []*api.Codespace{
{
Name: "hubot-robawt-abc",
},
},
wantDeleted: []string{"hubot-robawt-abc"},
wantStderr: "1 codespace(s) deleted successfully\n",
},
{
name: "by repo",
opts: deleteOptions{
repoFilter: "monalisa/spoon-knife",
},
codespaces: []*api.Codespace{
{
Name: "monalisa-spoonknife-123",
Repository: api.Repository{
FullName: "monalisa/Spoon-Knife",
},
},
{
Name: "hubot-robawt-abc",
Repository: api.Repository{
FullName: "hubot/ROBAWT",
},
},
{
Name: "monalisa-spoonknife-c4f3",
Repository: api.Repository{
FullName: "monalisa/Spoon-Knife",
},
},
},
wantDeleted: []string{"monalisa-spoonknife-123", "monalisa-spoonknife-c4f3"},
wantStderr: "2 codespace(s) deleted successfully\n",
},
{
name: "unused",
opts: deleteOptions{
deleteAll: true,
keepDays: 3,
},
codespaces: []*api.Codespace{
{
Name: "monalisa-spoonknife-123",
LastUsedAt: daysAgo(1),
},
{
Name: "hubot-robawt-abc",
LastUsedAt: daysAgo(4),
},
{
Name: "monalisa-spoonknife-c4f3",
LastUsedAt: daysAgo(10),
},
},
wantDeleted: []string{"hubot-robawt-abc", "monalisa-spoonknife-c4f3"},
wantStderr: "2 codespace(s) deleted successfully\n",
},
{
name: "deletion failed",
opts: deleteOptions{
deleteAll: true,
},
codespaces: []*api.Codespace{
{
Name: "monalisa-spoonknife-123",
},
{
Name: "hubot-robawt-abc",
},
},
deleteErr: errors.New("aborted by test"),
wantErr: "2 codespace(s) failed to delete",
wantDeleted: []string{"hubot-robawt-abc", "monalisa-spoonknife-123"},
wantStderr: heredoc.Doc(`
error deleting codespace "hubot-robawt-abc": aborted by test
error deleting codespace "monalisa-spoonknife-123": aborted by test
`),
wantStdout: "",
},
{
name: "with confirm",
opts: deleteOptions{
isInteractive: true,
deleteAll: true,
skipConfirm: false,
},
codespaces: []*api.Codespace{
{
Name: "monalisa-spoonknife-123",
GitStatus: api.CodespaceGitStatus{
HasUnpushedChanges: true,
},
},
{
Name: "hubot-robawt-abc",
GitStatus: api.CodespaceGitStatus{
HasUncommittedChanges: true,
},
},
{
Name: "monalisa-spoonknife-c4f3",
GitStatus: api.CodespaceGitStatus{
HasUnpushedChanges: false,
HasUncommittedChanges: false,
},
},
},
confirms: map[string]bool{
"Codespace monalisa-spoonknife-123 has unsaved changes. OK to delete?": false,
"Codespace hubot-robawt-abc has unsaved changes. OK to delete?": true,
},
wantDeleted: []string{"hubot-robawt-abc", "monalisa-spoonknife-c4f3"},
wantStderr: "2 codespace(s) deleted successfully\n",
},
{
name: "deletion for org codespace by admin succeeds",
opts: deleteOptions{
deleteAll: true,
orgName: "bookish",
userName: "monalisa",
codespaceName: "monalisa-spoonknife-123",
},
codespaces: []*api.Codespace{
{
Name: "monalisa-spoonknife-123",
Owner: api.User{Login: "monalisa"},
},
{
Name: "monalisa-spoonknife-123",
Owner: api.User{Login: "monalisa2"},
},
{
Name: "dont-delete-abc",
Owner: api.User{Login: "monalisa"},
},
},
wantDeleted: []string{"monalisa-spoonknife-123"},
wantStderr: "1 codespace(s) deleted successfully\n",
},
{
name: "deletion for org codespace by admin fails for codespace not found",
opts: deleteOptions{
deleteAll: true,
orgName: "bookish",
userName: "johnDoe",
codespaceName: "monalisa-spoonknife-123",
},
codespaces: []*api.Codespace{
{
Name: "monalisa-spoonknife-123",
Owner: api.User{Login: "monalisa"},
},
{
Name: "monalisa-spoonknife-123",
Owner: api.User{Login: "monalisa2"},
},
{
Name: "dont-delete-abc",
Owner: api.User{Login: "monalisa"},
},
},
wantDeleted: []string{},
wantStdout: "",
wantErr: "error fetching codespace information: " +
"codespace not found for user johnDoe with name monalisa-spoonknife-123",
},
{
name: "deletion for org codespace succeeds without username",
opts: deleteOptions{
deleteAll: true,
orgName: "bookish",
},
codespaces: []*api.Codespace{
{
Name: "monalisa-spoonknife-123",
Owner: api.User{Login: "monalisa"},
},
},
wantDeleted: []string{"monalisa-spoonknife-123"},
wantStderr: "1 codespace(s) deleted successfully\n",
},
{
name: "by repo owner",
opts: deleteOptions{
deleteAll: true,
repoOwner: "octocat",
},
codespaces: []*api.Codespace{
{
Name: "octocat-spoonknife-123",
Repository: api.Repository{
FullName: "octocat/Spoon-Knife",
Owner: api.RepositoryOwner{
Login: "octocat",
},
},
},
{
Name: "cli-robawt-abc",
Repository: api.Repository{
FullName: "cli/ROBAWT",
Owner: api.RepositoryOwner{
Login: "cli",
},
},
},
{
Name: "octocat-spoonknife-c4f3",
Repository: api.Repository{
FullName: "octocat/Spoon-Knife",
Owner: api.RepositoryOwner{
Login: "octocat",
},
},
},
},
wantDeleted: []string{"octocat-spoonknife-123", "octocat-spoonknife-c4f3"},
wantStderr: "2 codespace(s) deleted successfully\n",
wantStdout: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
apiMock := &apiClientMock{
GetUserFunc: func(_ context.Context) (*api.User, error) {
return &api.User{Login: "monalisa"}, nil
},
DeleteCodespaceFunc: func(_ context.Context, name string, orgName string, userName string) error {
if tt.deleteErr != nil {
return tt.deleteErr
}
return nil
},
}
if tt.opts.codespaceName == "" {
apiMock.ListCodespacesFunc = func(_ context.Context, _ api.ListCodespacesOptions) ([]*api.Codespace, error) {
return tt.codespaces, nil
}
} else {
if tt.opts.orgName != "" {
apiMock.GetOrgMemberCodespaceFunc = func(_ context.Context, orgName string, userName string, name string) (*api.Codespace, error) {
for _, codespace := range tt.codespaces {
if codespace.Name == name && codespace.Owner.Login == userName {
return codespace, nil
}
}
return nil, fmt.Errorf("codespace not found for user %s with name %s", userName, name)
}
} else {
apiMock.GetCodespaceFunc = func(_ context.Context, name string, includeConnection bool) (*api.Codespace, error) {
return tt.codespaces[0], nil
}
}
}
opts := tt.opts
opts.now = func() time.Time { return now }
opts.prompter = &prompterMock{
ConfirmFunc: func(msg string) (bool, error) {
res, found := tt.confirms[msg]
if !found {
return false, fmt.Errorf("unexpected prompt %q", msg)
}
return res, nil
},
}
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdinTTY(true)
ios.SetStdoutTTY(true)
app := NewApp(ios, nil, apiMock, nil, nil)
err := app.Delete(context.Background(), opts)
if (err != nil) && tt.wantErr != err.Error() {
t.Errorf("delete() error = %v, wantErr = %v", err, tt.wantErr)
}
for _, listArgs := range apiMock.ListCodespacesCalls() {
if listArgs.Opts.OrgName != "" && listArgs.Opts.UserName == "" {
t.Errorf("ListCodespaces() expected username option to be set")
}
}
var gotDeleted []string
for _, delArgs := range apiMock.DeleteCodespaceCalls() {
gotDeleted = append(gotDeleted, delArgs.Name)
}
sort.Strings(gotDeleted)
if !slices.Equal(gotDeleted, tt.wantDeleted) {
t.Errorf("deleted %q, want %q", gotDeleted, tt.wantDeleted)
}
if out := stdout.String(); out != tt.wantStdout {
t.Errorf("stdout = %q, want %q", out, tt.wantStdout)
}
if out := sortLines(stderr.String()); out != tt.wantStderr {
t.Errorf("stderr = %q, want %q", out, tt.wantStderr)
}
})
}
}
func sortLines(s string) string {
trailing := ""
if strings.HasSuffix(s, "\n") {
s = strings.TrimSuffix(s, "\n")
trailing = "\n"
}
lines := strings.Split(s, "\n")
sort.Strings(lines)
return strings.Join(lines, "\n") + trailing
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/ssh.go | pkg/cmd/codespace/ssh.go | package codespace
// This file defines the 'gh cs ssh' and 'gh cs cp' subcommands.
import (
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"sync"
"text/template"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/codespaces"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/cli/cli/v2/internal/codespaces/portforwarder"
"github.com/cli/cli/v2/internal/codespaces/rpc"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/ssh"
"github.com/cli/safeexec"
"github.com/spf13/cobra"
)
// In 2.13.0 these commands started automatically generating key pairs named 'codespaces' and 'codespaces.pub'
// which could collide with suggested the ssh config also named 'codespaces'. We now use 'codespaces.auto'
// and 'codespaces.auto.pub' in order to avoid that collision.
const automaticPrivateKeyNameOld = "codespaces"
const automaticPrivateKeyName = "codespaces.auto"
var errKeyFileNotFound = errors.New("SSH key file does not exist")
type sshOptions struct {
selector *CodespaceSelector
profile string
serverPort int
printConnDetails bool
debug bool
debugFile string
stdio bool
config bool
scpArgs []string // scp arguments, for 'cs cp' (nil for 'cs ssh')
}
func newSSHCmd(app *App) *cobra.Command {
var opts sshOptions
sshCmd := &cobra.Command{
Use: "ssh [<flags>...] [-- <ssh-flags>...] [<command>]",
Short: "SSH into a codespace",
Long: heredoc.Docf(`
The %[1]sssh%[1]s command is used to SSH into a codespace. In its simplest form, you can
run %[1]sgh cs ssh%[1]s, select a codespace interactively, and connect.
The %[1]sssh%[1]s command will automatically create a public/private ssh key pair in the
%[1]s~/.ssh%[1]s directory if you do not have an existing valid key pair. When selecting the
key pair to use, the preferred order is:
1. Key specified by %[1]s-i%[1]s in %[1]s<ssh-flags>%[1]s
2. Automatic key, if it already exists
3. First valid key pair in ssh config (according to %[1]sssh -G%[1]s)
4. Automatic key, newly created
The %[1]sssh%[1]s command also supports deeper integration with OpenSSH using a %[1]s--config%[1]s
option that generates per-codespace ssh configuration in OpenSSH format.
Including this configuration in your %[1]s~/.ssh/config%[1]s improves the user experience
of tools that integrate with OpenSSH, such as Bash/Zsh completion of ssh hostnames,
remote path completion for %[1]sscp/rsync/sshfs%[1]s, %[1]sgit%[1]s ssh remotes, and so on.
Once that is set up (see the second example below), you can ssh to codespaces as
if they were ordinary remote hosts (using %[1]sssh%[1]s, not %[1]sgh cs ssh%[1]s).
Note that the codespace you are connecting to must have an SSH server pre-installed.
If the docker image being used for the codespace does not have an SSH server,
install it in your %[1]sDockerfile%[1]s or, for codespaces that use Debian-based images,
you can add the following to your %[1]sdevcontainer.json%[1]s:
"features": {
"ghcr.io/devcontainers/features/sshd:1": {
"version": "latest"
}
}
`, "`"),
Example: heredoc.Doc(`
$ gh codespace ssh
$ gh codespace ssh --config > ~/.ssh/codespaces
$ printf 'Match all\nInclude ~/.ssh/codespaces\n' >> ~/.ssh/config
`),
PreRunE: func(c *cobra.Command, args []string) error {
if opts.stdio {
if opts.selector.codespaceName == "" {
return errors.New("`--stdio` requires explicit `--codespace`")
}
if opts.config {
return errors.New("cannot use `--stdio` with `--config`")
}
if opts.serverPort != 0 {
return errors.New("cannot use `--stdio` with `--server-port`")
}
if opts.profile != "" {
return errors.New("cannot use `--stdio` with `--profile`")
}
}
if opts.config {
if opts.profile != "" {
return errors.New("cannot use `--config` with `--profile`")
}
if opts.serverPort != 0 {
return errors.New("cannot use `--config` with `--server-port`")
}
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
if cmd.Flag("server-port").Changed {
opts.printConnDetails = true
}
if opts.config {
return app.printOpenSSHConfig(cmd.Context(), opts)
} else {
return app.SSH(cmd.Context(), args, opts)
}
},
DisableFlagsInUseLine: true,
}
sshCmd.Flags().StringVarP(&opts.profile, "profile", "", "", "Name of the SSH profile to use")
sshCmd.Flags().IntVarP(&opts.serverPort, "server-port", "", 0, "SSH server port number (0 => pick unused)")
opts.selector = AddCodespaceSelector(sshCmd, app.apiClient)
sshCmd.Flags().BoolVarP(&opts.debug, "debug", "d", false, "Log debug data to a file")
sshCmd.Flags().StringVarP(&opts.debugFile, "debug-file", "", "", "Path of the file log to")
sshCmd.Flags().BoolVarP(&opts.config, "config", "", false, "Write OpenSSH configuration to stdout")
sshCmd.Flags().BoolVar(&opts.stdio, "stdio", false, "Proxy sshd connection to stdio")
if err := sshCmd.Flags().MarkHidden("stdio"); err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
}
return sshCmd
}
type combinedReadWriteHalfCloser struct {
io.ReadCloser
io.WriteCloser
}
func (crwc *combinedReadWriteHalfCloser) Close() error {
werr := crwc.WriteCloser.Close()
rerr := crwc.ReadCloser.Close()
if werr != nil {
return werr
}
return rerr
}
func (crwc *combinedReadWriteHalfCloser) CloseWrite() error {
return crwc.WriteCloser.Close()
}
// SSH opens an ssh session or runs an ssh command in a codespace.
func (a *App) SSH(ctx context.Context, sshArgs []string, opts sshOptions) (err error) {
// Ensure all child tasks (e.g. port forwarding) terminate before return.
ctx, cancel := context.WithCancel(ctx)
defer cancel()
args := sshArgs
if opts.scpArgs != nil {
args = opts.scpArgs
}
sshContext := ssh.Context{}
startSSHOptions := rpc.StartSSHServerOptions{}
keyPair, shouldAddArg, err := selectSSHKeys(ctx, sshContext, args, opts)
if err != nil {
return fmt.Errorf("selecting ssh keys: %w", err)
}
startSSHOptions.UserPublicKeyFile = keyPair.PublicKeyPath
if shouldAddArg {
// For both cp and ssh, flags need to come first in the args (before a command in ssh and files in cp), so prepend this flag
args = append([]string{"-i", keyPair.PrivateKeyPath}, args...)
}
codespace, err := opts.selector.Select(ctx)
if err != nil {
return err
}
codespaceConnection, err := codespaces.GetCodespaceConnection(ctx, a, a.apiClient, codespace)
if err != nil {
return fmt.Errorf("error connecting to codespace: %w", err)
}
fwd, err := portforwarder.NewPortForwarder(ctx, codespaceConnection)
if err != nil {
return fmt.Errorf("failed to create port forwarder: %w", err)
}
defer safeClose(fwd, &err)
var (
invoker rpc.Invoker
remoteSSHServerPort int
sshUser string
)
err = a.RunWithProgress("Fetching SSH Details", func() (err error) {
invoker, err = rpc.CreateInvoker(ctx, fwd)
if err != nil {
return
}
remoteSSHServerPort, sshUser, err = invoker.StartSSHServerWithOptions(ctx, startSSHOptions)
return
})
if invoker != nil {
defer safeClose(invoker, &err)
}
if err != nil {
return fmt.Errorf("error getting ssh server details: %w", err)
}
if opts.stdio {
stdio := &combinedReadWriteHalfCloser{os.Stdin, os.Stdout}
opts := portforwarder.ForwardPortOpts{
Port: remoteSSHServerPort,
Internal: true,
KeepAlive: true,
}
// Forward the port
err = fwd.ForwardPort(ctx, opts)
if err != nil {
return fmt.Errorf("failed to forward port: %w", err)
}
// Connect to the forwarded port
err = fwd.ConnectToForwardedPort(ctx, stdio, opts)
if err != nil {
return fmt.Errorf("failed to connect to forwarded port: %w", err)
}
return fmt.Errorf("tunnel closed: %w", err)
}
localSSHServerPort := opts.serverPort
// Ensure local port is listening before client (Shell) connects.
// Unless the user specifies a server port, localSSHServerPort is 0
// and thus the client will pick a random port.
listen, localSSHServerPort, err := codespaces.ListenTCP(localSSHServerPort, false)
if err != nil {
return err
}
defer listen.Close()
connectDestination := opts.profile
if connectDestination == "" {
connectDestination = fmt.Sprintf("%s@localhost", sshUser)
}
tunnelClosed := make(chan error, 1)
go func() {
opts := portforwarder.ForwardPortOpts{
Port: remoteSSHServerPort,
Internal: true,
KeepAlive: true,
}
tunnelClosed <- fwd.ForwardPortToListener(ctx, opts, listen)
}()
shellClosed := make(chan error, 1)
go func() {
if opts.scpArgs != nil {
// args is the correct variable to use here, we just use scpArgs as the check for which command to run
shellClosed <- codespaces.Copy(ctx, args, localSSHServerPort, connectDestination)
} else {
// Parse the ssh args to determine if the user specified a command
args, command, err := codespaces.ParseSSHArgs(args)
if err != nil {
shellClosed <- err
return
}
// If the user specified a command, we need to keep the shell alive
// since it will be non-interactive and the codespace might shut down
// before the command finishes
if command != nil {
invoker.KeepAlive()
}
shellClosed <- codespaces.Shell(
ctx, a.errLogger, args, command, localSSHServerPort, connectDestination, opts.printConnDetails,
)
}
}()
select {
case err := <-tunnelClosed:
return fmt.Errorf("tunnel closed: %w", err)
case err := <-shellClosed:
if err != nil {
return fmt.Errorf("shell closed: %w", err)
}
return nil // success
}
}
// selectSSHKeys evaluates available key pairs and select which should be used to connect to the codespace
// using the precedence rules below. If there is no error, a keypair is always returned and additionally a
// bool flag is returned to specify if the private key need be appended to the ssh arguments (it doesn't need
// to be if the key was selected from a -i argument).
//
// Precedence rules:
// 1. Key which is specified by -i
// 2. Automatic key, if it already exists
// 3. First valid keypair in ssh config (according to ssh -G)
// 4. Automatic key, newly created
func selectSSHKeys(
ctx context.Context,
sshContext ssh.Context,
args []string,
opts sshOptions,
) (*ssh.KeyPair, bool, error) {
customConfigPath := ""
for i := 0; i < len(args); i += 1 {
arg := args[i]
if arg == "-i" {
if i+1 >= len(args) {
return nil, false, errors.New("missing value to -i argument")
}
privateKeyPath := args[i+1]
// The --config setup will set the automatic key with -i, but it might not actually be created, so we need to ensure that here
if automaticPrivateKeyPath, _ := automaticPrivateKeyPath(sshContext); automaticPrivateKeyPath == privateKeyPath {
_, err := generateAutomaticSSHKeys(sshContext)
if err != nil {
return nil, false, fmt.Errorf("generating automatic keypair: %w", err)
}
}
// User manually specified an identity file so just trust it is correct
return &ssh.KeyPair{
PrivateKeyPath: privateKeyPath,
PublicKeyPath: privateKeyPath + ".pub",
}, false, nil
}
if arg == "-F" && i+1 < len(args) {
// ssh only pays attention to that last specified -F value, so it's correct to overwrite here
customConfigPath = args[i+1]
}
}
if autoKeyPair := automaticSSHKeyPair(sshContext); autoKeyPair != nil {
// If the automatic keys already exist, just use them
return autoKeyPair, true, nil
}
keyPair, err := firstConfiguredKeyPair(ctx, customConfigPath, opts.profile)
if err != nil {
if !errors.Is(err, errKeyFileNotFound) {
return nil, false, fmt.Errorf("checking configured keys: %w", err)
}
// no valid key in ssh config, generate one
keyPair, err = generateAutomaticSSHKeys(sshContext)
if err != nil {
return nil, false, fmt.Errorf("generating automatic keypair: %w", err)
}
}
return keyPair, true, nil
}
// automaticSSHKeyPair returns the paths to the automatic key pair files, if they both exist
func automaticSSHKeyPair(sshContext ssh.Context) *ssh.KeyPair {
publicKeys, err := sshContext.LocalPublicKeys()
if err != nil {
// The error would be that the .ssh dir doesn't exist, which just means that the keypair also doesn't exist
return nil
}
for _, publicKey := range publicKeys {
if filepath.Base(publicKey) != automaticPrivateKeyName+".pub" {
continue
}
privateKey := strings.TrimSuffix(publicKey, ".pub")
_, err := os.Stat(privateKey)
if err == nil {
return &ssh.KeyPair{
PrivateKeyPath: privateKey,
PublicKeyPath: publicKey,
}
}
}
return nil
}
func generateAutomaticSSHKeys(sshContext ssh.Context) (*ssh.KeyPair, error) {
keyPair := checkAndUpdateOldKeyPair(sshContext)
if keyPair != nil {
return keyPair, nil
}
keyPair, err := sshContext.GenerateSSHKey(automaticPrivateKeyName, "")
if err != nil && !errors.Is(err, ssh.ErrKeyAlreadyExists) {
return nil, err
}
return keyPair, nil
}
// checkAndUpdateOldKeyPair handles backward compatibility with the old keypair names.
// If the old public and private keys both exist they are renamed to the new name.
// The return value is non-nil only if the rename happens.
func checkAndUpdateOldKeyPair(sshContext ssh.Context) *ssh.KeyPair {
publicKeys, err := sshContext.LocalPublicKeys()
if err != nil {
return nil
}
for _, publicKey := range publicKeys {
if filepath.Base(publicKey) != automaticPrivateKeyNameOld+".pub" {
continue
}
privateKey := strings.TrimSuffix(publicKey, ".pub")
_, err := os.Stat(privateKey)
if err != nil {
continue
}
// Both old public and private keys exist, rename them to the new name
sshDir := filepath.Dir(publicKey)
publicKeyNew := filepath.Join(sshDir, automaticPrivateKeyName+".pub")
err = os.Rename(publicKey, publicKeyNew)
if err != nil {
return nil
}
privateKeyNew := filepath.Join(sshDir, automaticPrivateKeyName)
err = os.Rename(privateKey, privateKeyNew)
if err != nil {
return nil
}
keyPair := &ssh.KeyPair{
PublicKeyPath: publicKeyNew,
PrivateKeyPath: privateKeyNew,
}
return keyPair
}
return nil
}
// firstConfiguredKeyPair reads the effective configuration for a localhost
// connection and returns the first valid key pair which would be tried for authentication
func firstConfiguredKeyPair(
ctx context.Context,
customConfigFile string,
customHost string,
) (*ssh.KeyPair, error) {
sshExe, err := safeexec.LookPath("ssh")
if err != nil {
return nil, fmt.Errorf("could not find ssh executable: %w", err)
}
// The -G option tells ssh to output the effective config for the given host, but not connect
sshGArgs := []string{"-G"}
if customConfigFile != "" {
sshGArgs = append(sshGArgs, "-F", customConfigFile)
}
if customHost != "" {
sshGArgs = append(sshGArgs, customHost)
} else {
sshGArgs = append(sshGArgs, "localhost")
}
sshGCmd := exec.CommandContext(ctx, sshExe, sshGArgs...)
configBytes, err := sshGCmd.Output()
if err != nil {
return nil, fmt.Errorf("could not load ssh configuration: %w", err)
}
configLines := strings.Split(string(configBytes), "\n")
for _, line := range configLines {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "identityfile ") {
privateKeyPath := strings.SplitN(line, " ", 2)[1]
keypair, err := keypairForPrivateKey(privateKeyPath)
if errors.Is(err, errKeyFileNotFound) {
continue
}
if err != nil {
return nil, fmt.Errorf("loading ssh config: %w", err)
}
return keypair, nil
}
}
return nil, errKeyFileNotFound
}
// keypairForPrivateKey returns the KeyPair with the specified private key if it and the public key both exist
func keypairForPrivateKey(privateKeyPath string) (*ssh.KeyPair, error) {
if strings.HasPrefix(privateKeyPath, "~") {
userHomeDir, err := os.UserHomeDir()
if err != nil {
return nil, fmt.Errorf("getting home dir: %w", err)
}
// os.Stat can't handle ~, so convert it to the real path
privateKeyPath = strings.Replace(privateKeyPath, "~", userHomeDir, 1)
}
// The default configuration includes standard keys like id_rsa or id_ed25519,
// but these may not actually exist
if _, err := os.Stat(privateKeyPath); err != nil {
return nil, errKeyFileNotFound
}
publicKeyPath := privateKeyPath + ".pub"
if _, err := os.Stat(publicKeyPath); err != nil {
return nil, errKeyFileNotFound
}
return &ssh.KeyPair{
PrivateKeyPath: privateKeyPath,
PublicKeyPath: publicKeyPath,
}, nil
}
func (a *App) printOpenSSHConfig(ctx context.Context, opts sshOptions) (err error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
var csList []*api.Codespace
if opts.selector.codespaceName == "" {
err = a.RunWithProgress("Fetching codespaces", func() (err error) {
csList, err = a.apiClient.ListCodespaces(ctx, api.ListCodespacesOptions{})
return
})
} else {
var codespace *api.Codespace
codespace, err = opts.selector.Select(ctx)
csList = []*api.Codespace{codespace}
}
if err != nil {
return fmt.Errorf("error getting codespace info: %w", err)
}
type sshResult struct {
codespace *api.Codespace
user string // on success, the remote ssh username; else nil
err error
}
sshUsers := make(chan sshResult, len(csList))
var wg sync.WaitGroup
var status error
for _, cs := range csList {
if cs.State != "Available" && opts.selector.codespaceName == "" {
fmt.Fprintf(os.Stderr, "skipping unavailable codespace %s: %s\n", cs.Name, cs.State)
status = cmdutil.SilentError
continue
}
wg.Add(1)
go func(cs *api.Codespace) {
result := sshResult{}
defer wg.Done()
codespaceConnection, err := codespaces.GetCodespaceConnection(ctx, a, a.apiClient, cs)
if err != nil {
result.err = fmt.Errorf("error connecting to codespace: %w", err)
sshUsers <- result
return
}
fwd, err := portforwarder.NewPortForwarder(ctx, codespaceConnection)
if err != nil {
result.err = fmt.Errorf("failed to create port forwarder: %w", err)
sshUsers <- result
return
}
defer safeClose(fwd, &err)
invoker, err := rpc.CreateInvoker(ctx, fwd)
if err != nil {
result.err = fmt.Errorf("error connecting to codespace: %w", err)
sshUsers <- result
return
}
defer safeClose(invoker, &err)
_, result.user, err = invoker.StartSSHServer(ctx)
if err != nil {
result.err = fmt.Errorf("error getting ssh server details: %w", err)
sshUsers <- result
return
}
result.codespace = cs
sshUsers <- result
}(cs)
}
go func() {
wg.Wait()
close(sshUsers)
}()
t, err := template.New("ssh_config").Parse(heredoc.Doc(`
Host cs.{{.Name}}.{{.EscapedRef}}
User {{.SSHUser}}
ProxyCommand {{.GHExec}} cs ssh -c {{.Name}} --stdio -- -i {{.AutomaticIdentityFilePath}}
UserKnownHostsFile=/dev/null
StrictHostKeyChecking no
LogLevel quiet
ControlMaster auto
IdentityFile {{.AutomaticIdentityFilePath}}
`))
if err != nil {
return fmt.Errorf("error formatting template: %w", err)
}
sshContext := ssh.Context{}
automaticIdentityFilePath, err := automaticPrivateKeyPath(sshContext)
if err != nil {
return fmt.Errorf("error finding .ssh directory: %w", err)
}
ghExec := a.executable.Executable()
for result := range sshUsers {
if result.err != nil {
fmt.Fprintf(os.Stderr, "%v\n", result.err)
status = cmdutil.SilentError
continue
}
// codespaceSSHConfig contains values needed to write an OpenSSH host
// configuration for a single codespace. For example:
//
// Host {{Name}}.{{EscapedRef}
// User {{SSHUser}
// ProxyCommand {{GHExec}} cs ssh -c {{Name}} --stdio
//
// EscapedRef is included in the name to help distinguish between codespaces
// when tab-completing ssh hostnames. '/' characters in EscapedRef are
// flattened to '-' to prevent problems with tab completion or when the
// hostname appears in ControlMaster socket paths.
type codespaceSSHConfig struct {
Name string // the codespace name, passed to `ssh -c`
EscapedRef string // the currently checked-out branch
SSHUser string // the remote ssh username
GHExec string // path used for invoking the current `gh` binary
AutomaticIdentityFilePath string // path used for automatic private key `gh cs ssh` would generate
}
conf := codespaceSSHConfig{
Name: result.codespace.Name,
EscapedRef: strings.ReplaceAll(result.codespace.GitStatus.Ref, "/", "-"),
SSHUser: result.user,
GHExec: ghExec,
AutomaticIdentityFilePath: automaticIdentityFilePath,
}
if err := t.Execute(a.io.Out, conf); err != nil {
return err
}
}
return status
}
func automaticPrivateKeyPath(sshContext ssh.Context) (string, error) {
sshDir, err := sshContext.SshDir()
if err != nil {
return "", err
}
return path.Join(sshDir, automaticPrivateKeyName), nil
}
type cpOptions struct {
sshOptions
recursive bool // -r
expand bool // -e
}
func newCpCmd(app *App) *cobra.Command {
var opts cpOptions
cpCmd := &cobra.Command{
Use: "cp [-e] [-r] [-- [<scp flags>...]] <sources>... <dest>",
Short: "Copy files between local and remote file systems",
Long: heredoc.Docf(`
The %[1]scp%[1]s command copies files between the local and remote file systems.
As with the UNIX %[1]scp%[1]s command, the first argument specifies the source and the last
specifies the destination; additional sources may be specified after the first,
if the destination is a directory.
The %[1]s--recursive%[1]s flag is required if any source is a directory.
A %[1]sremote:%[1]s prefix on any file name argument indicates that it refers to
the file system of the remote (Codespace) machine. It is resolved relative
to the home directory of the remote user.
By default, remote file names are interpreted literally. With the %[1]s--expand%[1]s flag,
each such argument is treated in the manner of %[1]sscp%[1]s, as a Bash expression to
be evaluated on the remote machine, subject to expansion of tildes, braces, globs,
environment variables, and backticks. For security, do not use this flag with arguments
provided by untrusted users; see <https://lwn.net/Articles/835962/> for discussion.
By default, the %[1]scp%[1]s command will create a public/private ssh key pair to authenticate with
the codespace inside the %[1]s~/.ssh directory%[1]s.
`, "`"),
Example: heredoc.Doc(`
$ gh codespace cp -e README.md 'remote:/workspaces/$RepositoryName/'
$ gh codespace cp -e 'remote:~/*.go' ./gofiles/
$ gh codespace cp -e 'remote:/workspaces/myproj/go.{mod,sum}' ./gofiles/
$ gh codespace cp -e -- -F ~/.ssh/codespaces_config 'remote:~/*.go' ./gofiles/
`),
RunE: func(cmd *cobra.Command, args []string) error {
return app.Copy(cmd.Context(), args, opts)
},
DisableFlagsInUseLine: true,
}
// We don't expose all sshOptions.
cpCmd.Flags().BoolVarP(&opts.recursive, "recursive", "r", false, "Recursively copy directories")
cpCmd.Flags().BoolVarP(&opts.expand, "expand", "e", false, "Expand remote file names on remote shell")
opts.selector = AddCodespaceSelector(cpCmd, app.apiClient)
cpCmd.Flags().StringVarP(&opts.profile, "profile", "p", "", "Name of the SSH profile to use")
return cpCmd
}
// Copy copies files between the local and remote file systems.
// The mechanics are similar to 'ssh' but using 'scp'.
func (a *App) Copy(ctx context.Context, args []string, opts cpOptions) error {
if len(args) < 2 {
return fmt.Errorf("cp requires source and destination arguments")
}
if opts.recursive {
opts.scpArgs = append(opts.scpArgs, "-r")
}
hasRemote := false
for _, arg := range args {
if rest := strings.TrimPrefix(arg, "remote:"); rest != arg {
hasRemote = true
// scp treats each filename argument as a shell expression,
// subjecting it to expansion of environment variables, braces,
// tilde, backticks, globs and so on. Because these present a
// security risk (see https://lwn.net/Articles/835962/), we
// disable them by shell-escaping the argument unless the user
// provided the -e flag.
if !opts.expand {
arg = `remote:'` + strings.Replace(rest, `'`, `'\''`, -1) + `'`
}
} else if !filepath.IsAbs(arg) {
// scp treats a colon in the first path segment as a host identifier.
// Escape it by prepending "./".
// TODO(adonovan): test on Windows, including with a c:\\foo path.
const sep = string(os.PathSeparator)
first := strings.Split(filepath.ToSlash(arg), sep)[0]
if strings.Contains(first, ":") {
arg = "." + sep + arg
}
}
opts.scpArgs = append(opts.scpArgs, arg)
}
if !hasRemote {
return cmdutil.FlagErrorf("at least one argument must have a 'remote:' prefix")
}
return a.SSH(ctx, nil, opts.sshOptions)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/ports_test.go | pkg/cmd/codespace/ports_test.go | package codespace
import (
"context"
"fmt"
"net/http"
"testing"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/cli/cli/v2/internal/codespaces/connection"
"github.com/cli/cli/v2/pkg/iostreams"
)
func TestListPorts(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
mockApi := GetMockApi(false)
ios, _, _, _ := iostreams.Test()
a := &App{
io: ios,
apiClient: mockApi,
}
selector := &CodespaceSelector{api: a.apiClient, codespaceName: "codespace-name"}
err := a.ListPorts(ctx, selector, nil)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
}
func TestPortsUpdateVisibilitySuccess(t *testing.T) {
portVisibilities := []portVisibility{
{
number: 80,
visibility: "org",
},
{
number: 9999,
visibility: "public",
},
}
err := runUpdateVisibilityTest(t, portVisibilities, true)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
}
func TestPortsUpdateVisibilityFailure(t *testing.T) {
portVisibilities := []portVisibility{
{
number: 9999,
visibility: "public",
},
{
number: 80,
visibility: "org",
},
}
err := runUpdateVisibilityTest(t, portVisibilities, false)
if err == nil {
t.Fatalf("runUpdateVisibilityTest succeeded unexpectedly")
}
}
func runUpdateVisibilityTest(t *testing.T, portVisibilities []portVisibility, allowOrgPorts bool) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
mockApi := GetMockApi(allowOrgPorts)
ios, _, _, _ := iostreams.Test()
a := &App{
io: ios,
apiClient: mockApi,
}
var portArgs []string
for _, pv := range portVisibilities {
portArgs = append(portArgs, fmt.Sprintf("%d:%s", pv.number, pv.visibility))
}
selector := &CodespaceSelector{api: a.apiClient, codespaceName: "codespace-name"}
return a.UpdatePortVisibility(ctx, selector, portArgs)
}
func TestPendingOperationDisallowsListPorts(t *testing.T) {
app := testingPortsApp()
selector := &CodespaceSelector{api: app.apiClient, codespaceName: "disabledCodespace"}
if err := app.ListPorts(context.Background(), selector, nil); err != nil {
if err.Error() != "codespace is disabled while it has a pending operation: Some pending operation" {
t.Errorf("expected pending operation error, but got: %v", err)
}
} else {
t.Error("expected pending operation error, but got nothing")
}
}
func TestPendingOperationDisallowsUpdatePortVisibility(t *testing.T) {
app := testingPortsApp()
selector := &CodespaceSelector{api: app.apiClient, codespaceName: "disabledCodespace"}
if err := app.UpdatePortVisibility(context.Background(), selector, nil); err != nil {
if err.Error() != "codespace is disabled while it has a pending operation: Some pending operation" {
t.Errorf("expected pending operation error, but got: %v", err)
}
} else {
t.Error("expected pending operation error, but got nothing")
}
}
func TestPendingOperationDisallowsForwardPorts(t *testing.T) {
app := testingPortsApp()
selector := &CodespaceSelector{api: app.apiClient, codespaceName: "disabledCodespace"}
if err := app.ForwardPorts(context.Background(), selector, nil); err != nil {
if err.Error() != "codespace is disabled while it has a pending operation: Some pending operation" {
t.Errorf("expected pending operation error, but got: %v", err)
}
} else {
t.Error("expected pending operation error, but got nothing")
}
}
func GetMockApi(allowOrgPorts bool) *apiClientMock {
return &apiClientMock{
GetCodespaceFunc: func(ctx context.Context, codespaceName string, includeConnection bool) (*api.Codespace, error) {
allowedPortPrivacySettings := []string{"public", "private"}
if allowOrgPorts {
allowedPortPrivacySettings = append(allowedPortPrivacySettings, "org")
}
return &api.Codespace{
Name: "codespace-name",
State: api.CodespaceStateAvailable,
Connection: api.CodespaceConnection{
TunnelProperties: api.TunnelProperties{
ConnectAccessToken: "tunnel access-token",
ManagePortsAccessToken: "manage-ports-token",
ServiceUri: "http://global.rel.tunnels.api.visualstudio.com/",
TunnelId: "tunnel-id",
ClusterId: "usw2",
Domain: "domain.com",
},
},
RuntimeConstraints: api.RuntimeConstraints{
AllowedPortPrivacySettings: allowedPortPrivacySettings,
},
}, nil
},
StartCodespaceFunc: func(ctx context.Context, codespaceName string) error {
return nil
},
GetCodespaceRepositoryContentsFunc: func(ctx context.Context, codespace *api.Codespace, path string) ([]byte, error) {
return nil, nil
},
HTTPClientFunc: func() (*http.Client, error) {
return connection.NewMockHttpClient()
},
}
}
func testingPortsApp() *App {
disabledCodespace := &api.Codespace{
Name: "disabledCodespace",
PendingOperation: true,
PendingOperationDisabledReason: "Some pending operation",
}
apiMock := &apiClientMock{
GetCodespaceFunc: func(_ context.Context, name string, _ bool) (*api.Codespace, error) {
if name == "disabledCodespace" {
return disabledCodespace, nil
}
return nil, nil
},
}
ios, _, _, _ := iostreams.Test()
return NewApp(ios, nil, apiMock, nil, nil)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/edit_test.go | pkg/cmd/codespace/edit_test.go | package codespace
import (
"context"
"testing"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/cli/cli/v2/pkg/iostreams"
)
func TestEdit(t *testing.T) {
tests := []struct {
name string
opts editOptions
cliArgs []string // alternative to opts; will test command dispatcher
wantEdits *api.EditCodespaceParams
mockCodespace *api.Codespace
wantStdout string
wantStderr string
wantErr bool
errMsg string
}{
{
name: "edit codespace display name",
opts: editOptions{
selector: &CodespaceSelector{codespaceName: "hubot"},
displayName: "hubot-changed",
machine: "",
},
wantEdits: &api.EditCodespaceParams{
DisplayName: "hubot-changed",
},
mockCodespace: &api.Codespace{
Name: "hubot",
DisplayName: "hubot-changed",
},
wantStdout: "",
wantErr: false,
},
{
name: "CLI legacy --displayName",
cliArgs: []string{"--codespace", "hubot", "--displayName", "hubot-changed"},
wantEdits: &api.EditCodespaceParams{
DisplayName: "hubot-changed",
},
mockCodespace: &api.Codespace{
Name: "hubot",
DisplayName: "hubot-changed",
},
wantStdout: "",
wantStderr: "Flag --displayName has been deprecated, use `--display-name` instead\n",
wantErr: false,
},
{
name: "edit codespace machine",
opts: editOptions{
selector: &CodespaceSelector{codespaceName: "hubot"},
displayName: "",
machine: "machine",
},
wantEdits: &api.EditCodespaceParams{
Machine: "machine",
},
mockCodespace: &api.Codespace{
Name: "hubot",
Machine: api.CodespaceMachine{
Name: "machine",
},
},
wantStdout: "",
wantErr: false,
},
{
name: "no CLI arguments",
cliArgs: []string{},
wantErr: true,
errMsg: "must provide `--display-name` or `--machine`",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var gotEdits *api.EditCodespaceParams
apiMock := &apiClientMock{
EditCodespaceFunc: func(_ context.Context, codespaceName string, params *api.EditCodespaceParams) (*api.Codespace, error) {
gotEdits = params
return tt.mockCodespace, nil
},
}
ios, _, stdout, stderr := iostreams.Test()
a := NewApp(ios, nil, apiMock, nil, nil)
var err error
if tt.cliArgs == nil {
if tt.opts.selector == nil {
t.Fatalf("selector must be set in opts if cliArgs are not provided")
}
tt.opts.selector.api = apiMock
err = a.Edit(context.Background(), tt.opts)
} else {
cmd := newEditCmd(a)
cmd.SilenceUsage = true
cmd.SilenceErrors = true
cmd.SetOut(ios.ErrOut)
cmd.SetErr(ios.ErrOut)
cmd.SetArgs(tt.cliArgs)
_, err = cmd.ExecuteC()
}
if tt.wantErr {
if err == nil {
t.Error("Edit() expected error, got nil")
} else if err.Error() != tt.errMsg {
t.Errorf("Edit() error = %q, want %q", err, tt.errMsg)
}
} else if err != nil {
t.Errorf("Edit() expected no error, got %v", err)
}
if out := stdout.String(); out != tt.wantStdout {
t.Errorf("stdout = %q, want %q", out, tt.wantStdout)
}
if out := stderr.String(); out != tt.wantStderr {
t.Errorf("stderr = %q, want %q", out, tt.wantStderr)
}
if tt.wantEdits != nil {
if gotEdits == nil {
t.Fatalf("EditCodespace() never called")
}
if tt.wantEdits.DisplayName != gotEdits.DisplayName {
t.Errorf("edited display name %q, want %q", gotEdits.DisplayName, tt.wantEdits.DisplayName)
}
if tt.wantEdits.Machine != gotEdits.Machine {
t.Errorf("edited machine type %q, want %q", gotEdits.Machine, tt.wantEdits.Machine)
}
if tt.wantEdits.IdleTimeoutMinutes != gotEdits.IdleTimeoutMinutes {
t.Errorf("edited idle timeout minutes %d, want %d", gotEdits.IdleTimeoutMinutes, tt.wantEdits.IdleTimeoutMinutes)
}
}
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/rebuild_test.go | pkg/cmd/codespace/rebuild_test.go | package codespace
import (
"context"
"testing"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/cli/cli/v2/pkg/iostreams"
)
func TestAlreadyRebuildingCodespace(t *testing.T) {
rebuildingCodespace := &api.Codespace{
Name: "rebuildingCodespace",
State: api.CodespaceStateRebuilding,
}
app := testingRebuildApp(*rebuildingCodespace)
selector := &CodespaceSelector{api: app.apiClient, codespaceName: "rebuildingCodespace"}
err := app.Rebuild(context.Background(), selector, false)
if err != nil {
t.Errorf("rebuilding a codespace that was already rebuilding: %v", err)
}
}
func testingRebuildApp(mockCodespace api.Codespace) *App {
apiMock := &apiClientMock{
GetCodespaceFunc: func(_ context.Context, name string, _ bool) (*api.Codespace, error) {
if name == mockCodespace.Name {
return &mockCodespace, nil
}
return nil, nil
},
}
ios, _, _, _ := iostreams.Test()
return NewApp(ios, nil, apiMock, nil, nil)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/jupyter.go | pkg/cmd/codespace/jupyter.go | package codespace
import (
"context"
"fmt"
"net"
"strings"
"github.com/cli/cli/v2/internal/codespaces"
"github.com/cli/cli/v2/internal/codespaces/portforwarder"
"github.com/cli/cli/v2/internal/codespaces/rpc"
"github.com/spf13/cobra"
)
func newJupyterCmd(app *App) *cobra.Command {
var selector *CodespaceSelector
jupyterCmd := &cobra.Command{
Use: "jupyter",
Short: "Open a codespace in JupyterLab",
Args: noArgsConstraint,
RunE: func(cmd *cobra.Command, args []string) error {
return app.Jupyter(cmd.Context(), selector)
},
}
selector = AddCodespaceSelector(jupyterCmd, app.apiClient)
return jupyterCmd
}
func (a *App) Jupyter(ctx context.Context, selector *CodespaceSelector) (err error) {
// Ensure all child tasks (e.g. port forwarding) terminate before return.
ctx, cancel := context.WithCancel(ctx)
defer cancel()
codespace, err := selector.Select(ctx)
if err != nil {
return err
}
codespaceConnection, err := codespaces.GetCodespaceConnection(ctx, a, a.apiClient, codespace)
if err != nil {
return fmt.Errorf("error connecting to codespace: %w", err)
}
fwd, err := portforwarder.NewPortForwarder(ctx, codespaceConnection)
if err != nil {
return fmt.Errorf("failed to create port forwarder: %w", err)
}
defer safeClose(fwd, &err)
var (
invoker rpc.Invoker
serverPort int
serverUrl string
)
err = a.RunWithProgress("Starting JupyterLab on codespace", func() (err error) {
invoker, err = rpc.CreateInvoker(ctx, fwd)
if err != nil {
return
}
serverPort, serverUrl, err = invoker.StartJupyterServer(ctx)
return
})
if invoker != nil {
defer safeClose(invoker, &err)
}
if err != nil {
return err
}
// Pass 0 to pick a random port
listen, _, err := codespaces.ListenTCP(0, false)
if err != nil {
return err
}
defer listen.Close()
destPort := listen.Addr().(*net.TCPAddr).Port
tunnelClosed := make(chan error, 1)
go func() {
opts := portforwarder.ForwardPortOpts{
Port: serverPort,
}
tunnelClosed <- fwd.ForwardPortToListener(ctx, opts, listen)
}()
// Server URL contains an authentication token that must be preserved
targetUrl := strings.Replace(serverUrl, fmt.Sprintf("%d", serverPort), fmt.Sprintf("%d", destPort), 1)
err = a.browser.Browse(targetUrl)
if err != nil {
return fmt.Errorf("failed to open JupyterLab in browser: %w", err)
}
fmt.Fprintln(a.io.Out, targetUrl)
select {
case err := <-tunnelClosed:
return fmt.Errorf("tunnel closed: %w", err)
case <-ctx.Done():
return nil // success
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/select_test.go | pkg/cmd/codespace/select_test.go | package codespace
import (
"context"
"errors"
"fmt"
"os"
"testing"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/cli/cli/v2/pkg/iostreams"
)
const CODESPACE_NAME = "monalisa-cli-cli-abcdef"
func TestApp_Select(t *testing.T) {
tests := []struct {
name string
arg string
wantErr bool
outputToFile bool
wantStdout string
wantStderr string
wantFileContents string
}{
{
name: "Select a codespace",
arg: CODESPACE_NAME,
wantErr: false,
wantStdout: fmt.Sprintf("%s\n", CODESPACE_NAME),
},
{
name: "Select a codespace error",
arg: "non-existent-codespace-name",
wantErr: true,
},
{
name: "Select a codespace",
arg: CODESPACE_NAME,
wantErr: false,
wantFileContents: CODESPACE_NAME,
outputToFile: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdinTTY(true)
ios.SetStdoutTTY(true)
a := NewApp(ios, nil, testSelectApiMock(), nil, nil)
opts := selectOptions{}
if tt.outputToFile {
file, err := os.CreateTemp("", "codespace-selection-test")
if err != nil {
t.Fatal(err)
}
defer os.Remove(file.Name())
opts = selectOptions{filePath: file.Name()}
}
opts.selector = &CodespaceSelector{api: a.apiClient, codespaceName: tt.arg}
if err := a.Select(context.Background(), opts); (err != nil) != tt.wantErr {
t.Errorf("App.Select() error = %v, wantErr %v", err, tt.wantErr)
}
if out := stdout.String(); out != tt.wantStdout {
t.Errorf("stdout = %q, want %q", out, tt.wantStdout)
}
if out := sortLines(stderr.String()); out != tt.wantStderr {
t.Errorf("stderr = %q, want %q", out, tt.wantStderr)
}
if tt.wantFileContents != "" {
if opts.filePath == "" {
t.Errorf("wantFileContents is set but opts.filePath is not")
}
dat, err := os.ReadFile(opts.filePath)
if err != nil {
t.Fatal(err)
}
if string(dat) != tt.wantFileContents {
t.Errorf("file contents = %q, want %q", string(dat), CODESPACE_NAME)
}
}
})
}
}
func testSelectApiMock() *apiClientMock {
testingCodespace := &api.Codespace{
Name: CODESPACE_NAME,
}
return &apiClientMock{
GetCodespaceFunc: func(_ context.Context, name string, includeConnection bool) (*api.Codespace, error) {
if name == CODESPACE_NAME {
return testingCodespace, nil
}
return nil, errors.New("cannot find codespace")
},
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/list_test.go | pkg/cmd/codespace/list_test.go | package codespace
import (
"bytes"
"context"
"fmt"
"testing"
"github.com/cli/cli/v2/internal/browser"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
)
func TestListCmdFlagError(t *testing.T) {
tests := []struct {
name string
args string
wantsErr error
}{
{
name: "list codespaces,--repo, --org and --user flag",
args: "--repo foo/bar --org github --user github",
wantsErr: fmt.Errorf("using `--org` or `--user` with `--repo` is not allowed"),
},
{
name: "list codespaces,--web, --org and --user flag",
args: "--web --org github --user github",
wantsErr: fmt.Errorf("using `--web` with `--org` or `--user` is not supported, please use with `--repo` instead"),
},
{
name: "list codespaces, negative --limit flag",
args: "--limit -1",
wantsErr: fmt.Errorf("invalid limit: -1"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
a := &App{
io: ios,
}
cmd := newListCmd(a)
args, _ := shlex.Split(tt.args)
cmd.SetArgs(args)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
_, err := cmd.ExecuteC()
if tt.wantsErr != nil {
assert.Error(t, err)
assert.EqualError(t, err, tt.wantsErr.Error())
return
}
})
}
}
func TestApp_List(t *testing.T) {
type fields struct {
apiClient apiClient
}
tests := []struct {
name string
fields fields
opts *listOptions
wantError error
wantURL string
}{
{
name: "list codespaces, no flags",
fields: fields{
apiClient: &apiClientMock{
ListCodespacesFunc: func(ctx context.Context, opts api.ListCodespacesOptions) ([]*api.Codespace, error) {
if opts.OrgName != "" {
return nil, fmt.Errorf("should not be called with an orgName")
}
return []*api.Codespace{
{
DisplayName: "CS1",
CreatedAt: "2023-01-01T00:00:00Z",
},
}, nil
},
},
},
opts: &listOptions{},
},
{
name: "list codespaces, --org flag",
fields: fields{
apiClient: &apiClientMock{
ListCodespacesFunc: func(ctx context.Context, opts api.ListCodespacesOptions) ([]*api.Codespace, error) {
if opts.OrgName != "TestOrg" {
return nil, fmt.Errorf("Expected orgName to be TestOrg. Got %s", opts.OrgName)
}
if opts.UserName != "" {
return nil, fmt.Errorf("Expected userName to be blank. Got %s", opts.UserName)
}
return []*api.Codespace{
{
DisplayName: "CS1",
CreatedAt: "2023-01-01T00:00:00Z",
},
}, nil
},
},
},
opts: &listOptions{
orgName: "TestOrg",
},
},
{
name: "list codespaces, --org and --user flag",
fields: fields{
apiClient: &apiClientMock{
ListCodespacesFunc: func(ctx context.Context, opts api.ListCodespacesOptions) ([]*api.Codespace, error) {
if opts.OrgName != "TestOrg" {
return nil, fmt.Errorf("Expected orgName to be TestOrg. Got %s", opts.OrgName)
}
if opts.UserName != "jimmy" {
return nil, fmt.Errorf("Expected userName to be jimmy. Got %s", opts.UserName)
}
return []*api.Codespace{
{
DisplayName: "CS1",
CreatedAt: "2023-01-01T00:00:00Z",
},
}, nil
},
},
},
opts: &listOptions{
orgName: "TestOrg",
userName: "jimmy",
},
},
{
name: "list codespaces, --repo",
fields: fields{
apiClient: &apiClientMock{
ListCodespacesFunc: func(ctx context.Context, opts api.ListCodespacesOptions) ([]*api.Codespace, error) {
if opts.RepoName == "" {
return nil, fmt.Errorf("Expected repository to not be nil")
}
if opts.RepoName != "cli/cli" {
return nil, fmt.Errorf("Expected repository name to be cli/cli. Got %s", opts.RepoName)
}
if opts.OrgName != "" {
return nil, fmt.Errorf("Expected orgName to be blank. Got %s", opts.OrgName)
}
if opts.UserName != "" {
return nil, fmt.Errorf("Expected userName to be blank. Got %s", opts.UserName)
}
return []*api.Codespace{
{
DisplayName: "CS1",
CreatedAt: "2023-01-01T00:00:00Z",
},
}, nil
},
},
},
opts: &listOptions{
repo: "cli/cli",
},
},
{
name: "list codespaces,--web",
fields: fields{
apiClient: &apiClientMock{
ServerURLFunc: func() string {
return "https://github.com"
},
},
},
opts: &listOptions{
useWeb: true,
},
wantURL: "https://github.com/codespaces",
},
{
name: "list codespaces,--web with custom server url",
fields: fields{
apiClient: &apiClientMock{
ServerURLFunc: func() string {
return "https://github.mycompany.com"
},
},
},
opts: &listOptions{
useWeb: true,
},
wantURL: "https://github.mycompany.com/codespaces",
},
{
name: "list codespaces,--web, --repo flag",
fields: fields{
apiClient: &apiClientMock{
ListCodespacesFunc: func(ctx context.Context, opts api.ListCodespacesOptions) ([]*api.Codespace, error) {
if opts.RepoName == "" {
return nil, fmt.Errorf("Expected repository to not be nil")
}
if opts.RepoName != "cli/cli" {
return nil, fmt.Errorf("Expected repository name to be cli/cli. Got %s", opts.RepoName)
}
if opts.OrgName != "" {
return nil, fmt.Errorf("Expected orgName to be blank. Got %s", opts.OrgName)
}
if opts.UserName != "" {
return nil, fmt.Errorf("Expected userName to be blank. Got %s", opts.UserName)
}
return []*api.Codespace{
{
DisplayName: "CS1",
Repository: api.Repository{ID: 123},
},
}, nil
},
ServerURLFunc: func() string {
return "https://github.com"
},
},
},
opts: &listOptions{
useWeb: true,
repo: "cli/cli",
},
wantURL: "https://github.com/codespaces?repository_id=123",
},
}
var b *browser.Stub
var a *App
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
if tt.opts.useWeb {
b = &browser.Stub{}
a = &App{
browser: b,
io: ios,
apiClient: tt.fields.apiClient,
}
} else {
a = &App{
io: ios,
apiClient: tt.fields.apiClient,
}
}
var exporter cmdutil.Exporter
err := a.List(context.Background(), tt.opts, exporter)
if (err != nil) != (tt.wantError != nil) {
t.Errorf("error = %v, wantErr %v", err, tt.wantError)
return
}
if err != nil && err.Error() != tt.wantError.Error() {
t.Errorf("error = %v, wantErr %v", err, tt.wantError)
}
if tt.opts.useWeb {
b.Verify(t, tt.wantURL)
}
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/logs_test.go | pkg/cmd/codespace/logs_test.go | package codespace
import (
"context"
"testing"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/cli/cli/v2/pkg/iostreams"
)
func TestPendingOperationDisallowsLogs(t *testing.T) {
app := testingLogsApp()
selector := &CodespaceSelector{api: app.apiClient, codespaceName: "disabledCodespace"}
if err := app.Logs(context.Background(), selector, false); err != nil {
if err.Error() != "codespace is disabled while it has a pending operation: Some pending operation" {
t.Errorf("expected pending operation error, but got: %v", err)
}
} else {
t.Error("expected pending operation error, but got nothing")
}
}
func testingLogsApp() *App {
disabledCodespace := &api.Codespace{
Name: "disabledCodespace",
PendingOperation: true,
PendingOperationDisabledReason: "Some pending operation",
}
apiMock := &apiClientMock{
GetCodespaceFunc: func(_ context.Context, name string, _ bool) (*api.Codespace, error) {
if name == "disabledCodespace" {
return disabledCodespace, nil
}
return nil, nil
},
}
ios, _, _, _ := iostreams.Test()
return NewApp(ios, nil, apiMock, nil, nil)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/code.go | pkg/cmd/codespace/code.go | package codespace
import (
"context"
"fmt"
"net/url"
"github.com/spf13/cobra"
)
func newCodeCmd(app *App) *cobra.Command {
var (
selector *CodespaceSelector
useInsiders bool
useWeb bool
)
codeCmd := &cobra.Command{
Use: "code",
Short: "Open a codespace in Visual Studio Code",
Args: noArgsConstraint,
RunE: func(cmd *cobra.Command, args []string) error {
return app.VSCode(cmd.Context(), selector, useInsiders, useWeb)
},
}
selector = AddCodespaceSelector(codeCmd, app.apiClient)
codeCmd.Flags().BoolVar(&useInsiders, "insiders", false, "Use the insiders version of Visual Studio Code")
codeCmd.Flags().BoolVarP(&useWeb, "web", "w", false, "Use the web version of Visual Studio Code")
return codeCmd
}
// VSCode opens a codespace in the local VS VSCode application.
func (a *App) VSCode(ctx context.Context, selector *CodespaceSelector, useInsiders bool, useWeb bool) error {
codespace, err := selector.Select(ctx)
if err != nil {
return err
}
browseURL := vscodeProtocolURL(codespace.Name, useInsiders)
if useWeb {
browseURL = codespace.WebURL
if useInsiders {
u, err := url.Parse(browseURL)
if err != nil {
return err
}
q := u.Query()
q.Set("vscodeChannel", "insiders")
u.RawQuery = q.Encode()
browseURL = u.String()
}
}
if err := a.browser.Browse(browseURL); err != nil {
return fmt.Errorf("error opening Visual Studio Code: %w", err)
}
return nil
}
func vscodeProtocolURL(codespaceName string, useInsiders bool) string {
application := "vscode"
if useInsiders {
application = "vscode-insiders"
}
return fmt.Sprintf("%s://github.codespaces/connect?name=%s&windowId=_blank", application, url.QueryEscape(codespaceName))
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/list.go | pkg/cmd/codespace/list.go | package codespace
import (
"context"
"fmt"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/cli/cli/v2/internal/tableprinter"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/spf13/cobra"
)
type listOptions struct {
limit int
repo string
orgName string
userName string
useWeb bool
}
func newListCmd(app *App) *cobra.Command {
opts := &listOptions{}
var exporter cmdutil.Exporter
listCmd := &cobra.Command{
Use: "list",
Short: "List codespaces",
Long: heredoc.Doc(`
List codespaces of the authenticated user.
Alternatively, organization administrators may list all codespaces billed to the organization.
`),
Aliases: []string{"ls"},
Args: noArgsConstraint,
PreRunE: func(cmd *cobra.Command, args []string) error {
if err := cmdutil.MutuallyExclusive(
"using `--org` or `--user` with `--repo` is not allowed",
opts.repo != "",
opts.orgName != "" || opts.userName != "",
); err != nil {
return err
}
if err := cmdutil.MutuallyExclusive(
"using `--web` with `--org` or `--user` is not supported, please use with `--repo` instead",
opts.useWeb,
opts.orgName != "" || opts.userName != "",
); err != nil {
return err
}
if opts.limit < 1 {
return cmdutil.FlagErrorf("invalid limit: %v", opts.limit)
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
return app.List(cmd.Context(), opts, exporter)
},
}
listCmd.Flags().IntVarP(&opts.limit, "limit", "L", 30, "Maximum number of codespaces to list")
listCmd.Flags().StringVarP(&opts.repo, "repo", "R", "", "Repository name with owner: user/repo")
if err := addDeprecatedRepoShorthand(listCmd, &opts.repo); err != nil {
fmt.Fprintf(app.io.ErrOut, "%v\n", err)
}
listCmd.Flags().StringVarP(&opts.orgName, "org", "o", "", "The `login` handle of the organization to list codespaces for (admin-only)")
listCmd.Flags().StringVarP(&opts.userName, "user", "u", "", "The `username` to list codespaces for (used with --org)")
cmdutil.AddJSONFlags(listCmd, &exporter, api.ListCodespaceFields)
listCmd.Flags().BoolVarP(&opts.useWeb, "web", "w", false, "List codespaces in the web browser, cannot be used with --user or --org")
return listCmd
}
func (a *App) List(ctx context.Context, opts *listOptions, exporter cmdutil.Exporter) error {
if opts.useWeb && opts.repo == "" {
return a.browser.Browse(fmt.Sprintf("%s/codespaces", a.apiClient.ServerURL()))
}
var codespaces []*api.Codespace
err := a.RunWithProgress("Fetching codespaces", func() (err error) {
codespaces, err = a.apiClient.ListCodespaces(ctx, api.ListCodespacesOptions{Limit: opts.limit, RepoName: opts.repo, OrgName: opts.orgName, UserName: opts.userName})
return
})
if err != nil {
return fmt.Errorf("error getting codespaces: %w", err)
}
hasNonProdVSCSTarget := false
for _, apiCodespace := range codespaces {
if apiCodespace.VSCSTarget != "" && apiCodespace.VSCSTarget != api.VSCSTargetProduction {
hasNonProdVSCSTarget = true
break
}
}
if err := a.io.StartPager(); err != nil {
a.errLogger.Printf("error starting pager: %v", err)
}
defer a.io.StopPager()
if exporter != nil {
return exporter.Write(a.io, codespaces)
}
if len(codespaces) == 0 {
return cmdutil.NewNoResultsError("no codespaces found")
}
if opts.useWeb && codespaces[0].Repository.ID > 0 {
return a.browser.Browse(fmt.Sprintf("%s/codespaces?repository_id=%d", a.apiClient.ServerURL(), codespaces[0].Repository.ID))
}
headers := []string{
"NAME",
"DISPLAY NAME",
}
if opts.orgName != "" {
headers = append(headers, "OWNER")
}
headers = append(headers,
"REPOSITORY",
"BRANCH",
"STATE",
"CREATED AT",
)
if hasNonProdVSCSTarget {
headers = append(headers, "VSCS TARGET")
}
tp := tableprinter.New(a.io, tableprinter.WithHeader(headers...))
cs := a.io.ColorScheme()
for _, apiCodespace := range codespaces {
c := codespace{apiCodespace}
var stateColor func(string) string
switch c.State {
case api.CodespaceStateStarting:
stateColor = cs.Yellow
case api.CodespaceStateAvailable:
stateColor = cs.Green
}
formattedName := formatNameForVSCSTarget(c.Name, c.VSCSTarget)
var nameColor func(string) string
switch c.PendingOperation {
case false:
nameColor = cs.Yellow
case true:
nameColor = cs.Muted
}
tp.AddField(formattedName, tableprinter.WithColor(nameColor))
tp.AddField(c.DisplayName)
if opts.orgName != "" {
tp.AddField(c.Owner.Login)
}
tp.AddField(c.Repository.FullName)
tp.AddField(c.branchWithGitStatus(), tableprinter.WithColor(cs.Cyan))
if c.PendingOperation {
tp.AddField(c.PendingOperationDisabledReason, tableprinter.WithColor(nameColor))
} else {
tp.AddField(c.State, tableprinter.WithColor(stateColor))
}
ct, err := time.Parse(time.RFC3339, c.CreatedAt)
if err != nil {
return fmt.Errorf("error parsing date %q: %w", c.CreatedAt, err)
}
tp.AddTimeField(time.Now(), ct, cs.Muted)
if hasNonProdVSCSTarget {
tp.AddField(c.VSCSTarget)
}
tp.EndRow()
}
return tp.Render()
}
func formatNameForVSCSTarget(name, vscsTarget string) string {
if vscsTarget == api.VSCSTargetDevelopment || vscsTarget == api.VSCSTargetLocal {
return fmt.Sprintf("%s π§", name)
}
if vscsTarget == api.VSCSTargetPPE {
return fmt.Sprintf("%s β¨", name)
}
return name
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/ssh_test.go | pkg/cmd/codespace/ssh_test.go | package codespace
import (
"context"
"fmt"
"os"
"path"
"path/filepath"
"strings"
"testing"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/pkg/ssh"
)
func TestPendingOperationDisallowsSSH(t *testing.T) {
app := testingSSHApp()
selector := &CodespaceSelector{api: app.apiClient, codespaceName: "disabledCodespace"}
if err := app.SSH(context.Background(), []string{}, sshOptions{selector: selector}); err != nil {
if err.Error() != "codespace is disabled while it has a pending operation: Some pending operation" {
t.Errorf("expected pending operation error, but got: %v", err)
}
} else {
t.Error("expected pending operation error, but got nothing")
}
}
func TestGenerateAutomaticSSHKeys(t *testing.T) {
tests := []struct {
// These files exist when calling generateAutomaticSSHKeys
existingFiles []string
// These files should exist after generateAutomaticSSHKeys finishes
wantFinalFiles []string
}{
// Basic case: no existing keys, they should be created
{
nil,
[]string{automaticPrivateKeyName, automaticPrivateKeyName + ".pub"},
},
// Basic case: keys already exist
{
[]string{automaticPrivateKeyName, automaticPrivateKeyName + ".pub"},
[]string{automaticPrivateKeyName, automaticPrivateKeyName + ".pub"},
},
// Backward compatibility: both old keys exist, they should be renamed
{
[]string{automaticPrivateKeyNameOld, automaticPrivateKeyNameOld + ".pub"},
[]string{automaticPrivateKeyName, automaticPrivateKeyName + ".pub"},
},
// Backward compatibility: old private key exists but not the public key, the new keys should be created
{
[]string{automaticPrivateKeyNameOld},
[]string{automaticPrivateKeyNameOld, automaticPrivateKeyName, automaticPrivateKeyName + ".pub"},
},
// Backward compatibility: old public key exists but not the private key, the new keys should be created
{
[]string{automaticPrivateKeyNameOld + ".pub"},
[]string{automaticPrivateKeyNameOld + ".pub", automaticPrivateKeyName, automaticPrivateKeyName + ".pub"},
},
// Backward compatibility (edge case): files exist which contains old key name as a substring, the new keys should be created
{
[]string{"foo" + automaticPrivateKeyNameOld + ".pub", "foo" + automaticPrivateKeyNameOld},
[]string{"foo" + automaticPrivateKeyNameOld + ".pub", "foo" + automaticPrivateKeyNameOld, automaticPrivateKeyName, automaticPrivateKeyName + ".pub"},
},
}
for _, tt := range tests {
dir := t.TempDir()
sshContext := ssh.NewContextForTests(dir, "")
for _, file := range tt.existingFiles {
f, err := os.Create(filepath.Join(dir, file))
if err != nil {
t.Errorf("Failed to setup test files: %v", err)
}
// If the file isn't closed here windows will have errors about file already in use
f.Close()
}
keyPair, err := generateAutomaticSSHKeys(sshContext)
if err != nil {
t.Errorf("Unexpected error from generateAutomaticSSHKeys: %v", err)
}
if keyPair == nil {
t.Fatal("Unexpected nil KeyPair from generateAutomaticSSHKeys")
}
if !strings.HasSuffix(keyPair.PrivateKeyPath, automaticPrivateKeyName) {
t.Errorf("Expected private key path %v, got %v", automaticPrivateKeyName, keyPair.PrivateKeyPath)
}
if !strings.HasSuffix(keyPair.PublicKeyPath, automaticPrivateKeyName+".pub") {
t.Errorf("Expected public key path %v, got %v", automaticPrivateKeyName+".pub", keyPair.PublicKeyPath)
}
// Check that all the expected files are present
for _, file := range tt.wantFinalFiles {
if _, err := os.Stat(filepath.Join(dir, file)); err != nil {
t.Errorf("Want file %q to exist after generateAutomaticSSHKeys but it doesn't", file)
}
}
// Check that no unexpected files are present
allExistingFiles, err := os.ReadDir(dir)
if err != nil {
t.Errorf("Failed to list files in test directory: %v", err)
}
for _, file := range allExistingFiles {
filename := file.Name()
isWantedFile := false
for _, wantedFile := range tt.wantFinalFiles {
if filename == wantedFile {
isWantedFile = true
break
}
}
if !isWantedFile {
t.Errorf("Unexpected file %q exists after generateAutomaticSSHKeys", filename)
}
}
}
}
func TestSelectSSHKeys(t *testing.T) {
// This string will be substituted in sshArgs for test cases
// This is to work around the temp test ssh dir not being known until the test is executing
substituteSSHDir := "SUB_SSH_DIR"
tests := []struct {
sshDirFiles []string
sshConfigKeys []string
sshArgs []string
profileOpt string
wantKeyPair *ssh.KeyPair
wantShouldAddArg bool
}{
// -i tests
{
sshArgs: []string{"-i", "custom-private-key"},
wantKeyPair: &ssh.KeyPair{PrivateKeyPath: "custom-private-key", PublicKeyPath: "custom-private-key.pub"},
},
{
sshArgs: []string{"-i", path.Join(substituteSSHDir, automaticPrivateKeyName)},
wantKeyPair: &ssh.KeyPair{PrivateKeyPath: automaticPrivateKeyName, PublicKeyPath: automaticPrivateKeyName + ".pub"},
},
{
// Edge case check for missing arg value
sshArgs: []string{"-i"},
},
// Auto key exists tests
{
sshDirFiles: []string{automaticPrivateKeyName, automaticPrivateKeyName + ".pub"},
wantKeyPair: &ssh.KeyPair{PrivateKeyPath: automaticPrivateKeyName, PublicKeyPath: automaticPrivateKeyName + ".pub"},
wantShouldAddArg: true,
},
{
sshDirFiles: []string{automaticPrivateKeyName, automaticPrivateKeyName + ".pub", "custom-private-key", "custom-private-key.pub"},
wantKeyPair: &ssh.KeyPair{PrivateKeyPath: automaticPrivateKeyName, PublicKeyPath: automaticPrivateKeyName + ".pub"},
wantShouldAddArg: true,
},
// SSH config tests
{
sshDirFiles: []string{"custom-private-key", "custom-private-key.pub"},
sshConfigKeys: []string{"custom-private-key"},
wantKeyPair: &ssh.KeyPair{PrivateKeyPath: "custom-private-key", PublicKeyPath: "custom-private-key.pub"},
wantShouldAddArg: true,
},
{
// 2 pairs, but only 1 is configured
sshDirFiles: []string{"custom-private-key", "custom-private-key.pub", "custom-private-key-2", "custom-private-key-2.pub"},
sshConfigKeys: []string{"custom-private-key-2"},
wantKeyPair: &ssh.KeyPair{PrivateKeyPath: "custom-private-key-2", PublicKeyPath: "custom-private-key-2.pub"},
wantShouldAddArg: true,
},
{
// 2 pairs, but only 1 has both public and private
sshDirFiles: []string{"custom-private-key", "custom-private-key-2", "custom-private-key-2.pub"},
sshConfigKeys: []string{"custom-private-key", "custom-private-key-2"},
wantKeyPair: &ssh.KeyPair{PrivateKeyPath: "custom-private-key-2", PublicKeyPath: "custom-private-key-2.pub"},
wantShouldAddArg: true,
},
// Automatic key tests
{
wantKeyPair: &ssh.KeyPair{PrivateKeyPath: automaticPrivateKeyName, PublicKeyPath: automaticPrivateKeyName + ".pub"},
wantShouldAddArg: true,
},
{
// Renames old key pair to new
sshDirFiles: []string{automaticPrivateKeyNameOld, automaticPrivateKeyNameOld + ".pub"},
wantKeyPair: &ssh.KeyPair{PrivateKeyPath: automaticPrivateKeyName, PublicKeyPath: automaticPrivateKeyName + ".pub"},
wantShouldAddArg: true,
},
{
// Other key is configured, but doesn't exist
sshConfigKeys: []string{"custom-private-key"},
wantKeyPair: &ssh.KeyPair{PrivateKeyPath: automaticPrivateKeyName, PublicKeyPath: automaticPrivateKeyName + ".pub"},
wantShouldAddArg: true,
},
}
for _, tt := range tests {
sshDir := t.TempDir()
sshContext := ssh.NewContextForTests(sshDir, "")
for _, file := range tt.sshDirFiles {
f, err := os.Create(filepath.Join(sshDir, file))
if err != nil {
t.Errorf("Failed to create test ssh dir file %q: %v", file, err)
}
f.Close()
}
configPath := filepath.Join(sshDir, "test-config")
// Seed the config with a non-existent key so that the default config won't apply
configContent := "IdentityFile dummy\n"
for _, key := range tt.sshConfigKeys {
configContent += fmt.Sprintf("IdentityFile %s\n", filepath.Join(sshDir, key))
}
err := os.WriteFile(configPath, []byte(configContent), 0666)
if err != nil {
t.Fatalf("could not write test config %v", err)
}
var subbedSSHArgs []string
for _, arg := range tt.sshArgs {
subbedSSHArgs = append(subbedSSHArgs, strings.Replace(arg, substituteSSHDir, sshDir, -1))
}
tt.sshArgs = append([]string{"-F", configPath}, subbedSSHArgs...)
gotKeyPair, gotShouldAddArg, err := selectSSHKeys(context.Background(), sshContext, tt.sshArgs, sshOptions{profile: tt.profileOpt})
if tt.wantKeyPair == nil {
if err == nil {
t.Errorf("Expected error from selectSSHKeys but got nil")
}
continue
}
if err != nil {
t.Errorf("Unexpected error from selectSSHKeys: %v", err)
continue
}
if gotKeyPair == nil {
t.Errorf("Expected non-nil result from selectSSHKeys but got nil")
continue
}
if gotShouldAddArg != tt.wantShouldAddArg {
t.Errorf("Got wrong shouldAddArg value from selectSSHKeys, wanted %v got %v", tt.wantShouldAddArg, gotShouldAddArg)
continue
}
// Strip the dir (sshDir) from the gotKeyPair paths so that they match wantKeyPair (which doesn't know the directory)
gotKeyPairJustFileNames := &ssh.KeyPair{
PrivateKeyPath: filepath.Base(gotKeyPair.PrivateKeyPath),
PublicKeyPath: filepath.Base(gotKeyPair.PublicKeyPath),
}
if fmt.Sprintf("%v", gotKeyPairJustFileNames) != fmt.Sprintf("%v", tt.wantKeyPair) {
t.Errorf("Want selectSSHKeys result to be %v, got %v", tt.wantKeyPair, gotKeyPairJustFileNames)
}
// If the automatic key pair is selected, it needs to exist no matter what
if strings.Contains(tt.wantKeyPair.PrivateKeyPath, automaticPrivateKeyName) {
if _, err := os.Stat(gotKeyPair.PrivateKeyPath); err != nil {
t.Errorf("Expected automatic key pair private key to exist, but it did not")
}
if _, err := os.Stat(gotKeyPair.PublicKeyPath); err != nil {
t.Errorf("Expected automatic key pair public key to exist, but it did not")
}
}
}
}
func testingSSHApp() *App {
disabledCodespace := &api.Codespace{
Name: "disabledCodespace",
PendingOperation: true,
PendingOperationDisabledReason: "Some pending operation",
}
apiMock := &apiClientMock{
GetCodespaceFunc: func(_ context.Context, name string, _ bool) (*api.Codespace, error) {
if name == "disabledCodespace" {
return disabledCodespace, nil
}
return nil, nil
},
}
ios, _, _, _ := iostreams.Test()
return NewApp(ios, nil, apiMock, nil, nil)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/logs.go | pkg/cmd/codespace/logs.go | package codespace
import (
"context"
"fmt"
"github.com/cli/cli/v2/internal/codespaces"
"github.com/cli/cli/v2/internal/codespaces/portforwarder"
"github.com/cli/cli/v2/internal/codespaces/rpc"
"github.com/spf13/cobra"
)
func newLogsCmd(app *App) *cobra.Command {
var (
selector *CodespaceSelector
follow bool
)
logsCmd := &cobra.Command{
Use: "logs",
Short: "Access codespace logs",
Args: noArgsConstraint,
RunE: func(cmd *cobra.Command, args []string) error {
return app.Logs(cmd.Context(), selector, follow)
},
}
selector = AddCodespaceSelector(logsCmd, app.apiClient)
logsCmd.Flags().BoolVarP(&follow, "follow", "f", false, "Tail and follow the logs")
return logsCmd
}
func (a *App) Logs(ctx context.Context, selector *CodespaceSelector, follow bool) (err error) {
// Ensure all child tasks (port forwarding, remote exec) terminate before return.
ctx, cancel := context.WithCancel(ctx)
defer cancel()
codespace, err := selector.Select(ctx)
if err != nil {
return err
}
codespaceConnection, err := codespaces.GetCodespaceConnection(ctx, a, a.apiClient, codespace)
if err != nil {
return fmt.Errorf("error connecting to codespace: %w", err)
}
fwd, err := portforwarder.NewPortForwarder(ctx, codespaceConnection)
if err != nil {
return fmt.Errorf("failed to create port forwarder: %w", err)
}
defer safeClose(fwd, &err)
// Ensure local port is listening before client (getPostCreateOutput) connects.
listen, localPort, err := codespaces.ListenTCP(0, false)
if err != nil {
return err
}
defer listen.Close()
remoteSSHServerPort, sshUser := 0, ""
err = a.RunWithProgress("Fetching SSH Details", func() (err error) {
invoker, err := rpc.CreateInvoker(ctx, fwd)
if err != nil {
return
}
defer safeClose(invoker, &err)
remoteSSHServerPort, sshUser, err = invoker.StartSSHServer(ctx)
return
})
if err != nil {
return fmt.Errorf("error getting ssh server details: %w", err)
}
cmdType := "cat"
if follow {
cmdType = "tail -f"
}
dst := fmt.Sprintf("%s@localhost", sshUser)
cmd, err := codespaces.NewRemoteCommand(
ctx, localPort, dst, fmt.Sprintf("%s /workspaces/.codespaces/.persistedshare/creation.log", cmdType),
)
if err != nil {
return fmt.Errorf("remote command: %w", err)
}
tunnelClosed := make(chan error, 1)
go func() {
opts := portforwarder.ForwardPortOpts{
Port: remoteSSHServerPort,
Internal: true,
}
tunnelClosed <- fwd.ForwardPortToListener(ctx, opts, listen)
}()
cmdDone := make(chan error, 1)
go func() {
cmdDone <- cmd.Run()
}()
select {
case err := <-tunnelClosed:
return fmt.Errorf("connection closed: %w", err)
case err := <-cmdDone:
if err != nil {
return fmt.Errorf("error retrieving logs: %w", err)
}
return nil // success
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/mock_prompter.go | pkg/cmd/codespace/mock_prompter.go | // Code generated by moq; DO NOT EDIT.
// github.com/matryer/moq
package codespace
import (
"sync"
)
// prompterMock is a mock implementation of prompter.
//
// func TestSomethingThatUsesprompter(t *testing.T) {
//
// // make and configure a mocked prompter
// mockedprompter := &prompterMock{
// ConfirmFunc: func(message string) (bool, error) {
// panic("mock out the Confirm method")
// },
// }
//
// // use mockedprompter in code that requires prompter
// // and then make assertions.
//
// }
type prompterMock struct {
// ConfirmFunc mocks the Confirm method.
ConfirmFunc func(message string) (bool, error)
// calls tracks calls to the methods.
calls struct {
// Confirm holds details about calls to the Confirm method.
Confirm []struct {
// Message is the message argument value.
Message string
}
}
lockConfirm sync.RWMutex
}
// Confirm calls ConfirmFunc.
func (mock *prompterMock) Confirm(message string) (bool, error) {
if mock.ConfirmFunc == nil {
panic("prompterMock.ConfirmFunc: method is nil but prompter.Confirm was just called")
}
callInfo := struct {
Message string
}{
Message: message,
}
mock.lockConfirm.Lock()
mock.calls.Confirm = append(mock.calls.Confirm, callInfo)
mock.lockConfirm.Unlock()
return mock.ConfirmFunc(message)
}
// ConfirmCalls gets all the calls that were made to Confirm.
// Check the length with:
//
// len(mockedprompter.ConfirmCalls())
func (mock *prompterMock) ConfirmCalls() []struct {
Message string
} {
var calls []struct {
Message string
}
mock.lockConfirm.RLock()
calls = mock.calls.Confirm
mock.lockConfirm.RUnlock()
return calls
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/view_test.go | pkg/cmd/codespace/view_test.go | package codespace
import (
"context"
"fmt"
"testing"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/cli/cli/v2/pkg/iostreams"
)
func Test_NewCmdView(t *testing.T) {
tests := []struct {
tName string
codespaceName string
opts *viewOptions
cliArgs []string
wantErr bool
wantStdout string
errMsg string
}{
{
tName: "selector throws because no terminal found",
opts: &viewOptions{},
wantErr: true,
errMsg: "choosing codespace: error getting answers: no terminal",
},
{
tName: "command fails because provided codespace doesn't exist",
codespaceName: "i-dont-exist",
opts: &viewOptions{},
wantErr: true,
errMsg: "getting full codespace details: codespace not found",
},
{
tName: "command succeeds because codespace exists (no details)",
codespaceName: "monalisa-cli-cli-abcdef",
opts: &viewOptions{},
wantErr: false,
wantStdout: "Name\tmonalisa-cli-cli-abcdef\nState\t\nRepository\t\nGit Status\t - 0 commits ahead, 0 commits behind\nDevcontainer Path\t\nMachine Display Name\t\nIdle Timeout\t0 minutes\nCreated At\t\nRetention Period\t\n",
},
{
tName: "command succeeds because codespace exists (with details)",
codespaceName: "monalisa-cli-cli-hijklm",
opts: &viewOptions{},
wantErr: false,
wantStdout: "Name\tmonalisa-cli-cli-hijklm\nState\tAvailable\nRepository\tcli/cli\nGit Status\tmain* - 1 commit ahead, 2 commits behind\nDevcontainer Path\t.devcontainer/devcontainer.json\nMachine Display Name\tTest Display Name\nIdle Timeout\t30 minutes\nCreated At\t\nRetention Period\t1 day\n",
},
}
for _, tt := range tests {
t.Run(tt.tName, func(t *testing.T) {
ios, _, stdout, _ := iostreams.Test()
a := &App{
apiClient: testViewApiMock(),
io: ios,
}
selector := &CodespaceSelector{api: a.apiClient, codespaceName: tt.codespaceName}
tt.opts.selector = selector
var err error
if tt.cliArgs == nil {
if tt.opts.selector == nil {
t.Fatalf("selector must be set in opts if cliArgs are not provided")
}
err = a.ViewCodespace(context.Background(), tt.opts)
} else {
cmd := newViewCmd(a)
cmd.SilenceUsage = true
cmd.SilenceErrors = true
cmd.SetOut(ios.ErrOut)
cmd.SetErr(ios.ErrOut)
cmd.SetArgs(tt.cliArgs)
_, err = cmd.ExecuteC()
}
if tt.wantErr {
if err == nil {
t.Error("Edit() expected error, got nil")
} else if err.Error() != tt.errMsg {
t.Errorf("Edit() error = %q, want %q", err, tt.errMsg)
}
} else if err != nil {
t.Errorf("Edit() expected no error, got %v", err)
}
if out := stdout.String(); out != tt.wantStdout {
t.Errorf("stdout = %q, want %q", out, tt.wantStdout)
}
})
}
}
func testViewApiMock() *apiClientMock {
codespaceWithNoDetails := &api.Codespace{
Name: "monalisa-cli-cli-abcdef",
}
codespaceWithDetails := &api.Codespace{
Name: "monalisa-cli-cli-hijklm",
GitStatus: api.CodespaceGitStatus{
Ahead: 1,
Behind: 2,
Ref: "main",
HasUnpushedChanges: true,
HasUncommittedChanges: true,
},
IdleTimeoutMinutes: 30,
RetentionPeriodMinutes: 1440,
State: "Available",
Repository: api.Repository{FullName: "cli/cli"},
DevContainerPath: ".devcontainer/devcontainer.json",
Machine: api.CodespaceMachine{
DisplayName: "Test Display Name",
},
}
return &apiClientMock{
GetCodespaceFunc: func(_ context.Context, name string, _ bool) (*api.Codespace, error) {
if name == codespaceWithDetails.Name {
return codespaceWithDetails, nil
} else if name == codespaceWithNoDetails.Name {
return codespaceWithNoDetails, nil
}
return nil, fmt.Errorf("codespace not found")
},
ListCodespacesFunc: func(ctx context.Context, opts api.ListCodespacesOptions) ([]*api.Codespace, error) {
return []*api.Codespace{codespaceWithNoDetails, codespaceWithDetails}, nil
},
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/codespace_selector.go | pkg/cmd/codespace/codespace_selector.go | package codespace
import (
"context"
"errors"
"fmt"
"strings"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/spf13/cobra"
)
type CodespaceSelector struct {
api apiClient
repoName string
codespaceName string
repoOwner string
}
var errNoFilteredCodespaces = errors.New("you have no codespaces meeting the filter criteria")
// AddCodespaceSelector adds persistent flags for selecting a codespace to the given command and returns a CodespaceSelector which applies them
func AddCodespaceSelector(cmd *cobra.Command, api apiClient) *CodespaceSelector {
cs := &CodespaceSelector{api: api}
cmd.PersistentFlags().StringVarP(&cs.codespaceName, "codespace", "c", "", "Name of the codespace")
cmd.PersistentFlags().StringVarP(&cs.repoName, "repo", "R", "", "Filter codespace selection by repository name (user/repo)")
cmd.PersistentFlags().StringVar(&cs.repoOwner, "repo-owner", "", "Filter codespace selection by repository owner (username or org)")
cmd.MarkFlagsMutuallyExclusive("codespace", "repo")
cmd.MarkFlagsMutuallyExclusive("codespace", "repo-owner")
return cs
}
func (cs *CodespaceSelector) Select(ctx context.Context) (codespace *api.Codespace, err error) {
if cs.codespaceName != "" {
codespace, err = cs.api.GetCodespace(ctx, cs.codespaceName, true)
if err != nil {
return nil, fmt.Errorf("getting full codespace details: %w", err)
}
} else {
codespaces, err := cs.fetchCodespaces(ctx)
if err != nil {
return nil, err
}
codespace, err = cs.chooseCodespace(ctx, codespaces)
if err != nil {
return nil, err
}
}
if codespace.PendingOperation {
return nil, fmt.Errorf(
"codespace is disabled while it has a pending operation: %s",
codespace.PendingOperationDisabledReason,
)
}
return codespace, nil
}
func (cs *CodespaceSelector) SelectName(ctx context.Context) (string, error) {
if cs.codespaceName != "" {
return cs.codespaceName, nil
}
codespaces, err := cs.fetchCodespaces(ctx)
if err != nil {
return "", err
}
codespace, err := cs.chooseCodespace(ctx, codespaces)
if err != nil {
return "", err
}
return codespace.Name, nil
}
func (cs *CodespaceSelector) fetchCodespaces(ctx context.Context) (codespaces []*api.Codespace, err error) {
codespaces, err = cs.api.ListCodespaces(ctx, api.ListCodespacesOptions{})
if err != nil {
return nil, fmt.Errorf("error getting codespaces: %w", err)
}
if len(codespaces) == 0 {
return nil, errNoCodespaces
}
// Note that repo filtering done here can also be done in api.ListCodespaces.
// We do it here instead so that we can differentiate no codespaces in general vs. none after filtering.
if cs.repoName != "" {
var filteredCodespaces []*api.Codespace
for _, c := range codespaces {
if !strings.EqualFold(c.Repository.FullName, cs.repoName) {
continue
}
filteredCodespaces = append(filteredCodespaces, c)
}
codespaces = filteredCodespaces
}
if cs.repoOwner != "" {
codespaces = filterCodespacesByRepoOwner(codespaces, cs.repoOwner)
}
if len(codespaces) == 0 {
return nil, errNoFilteredCodespaces
}
return codespaces, err
}
func (cs *CodespaceSelector) chooseCodespace(ctx context.Context, codespaces []*api.Codespace) (codespace *api.Codespace, err error) {
skipPromptForSingleOption := cs.repoName != ""
codespace, err = chooseCodespaceFromList(ctx, codespaces, false, skipPromptForSingleOption)
if err != nil {
if err == errNoCodespaces {
return nil, err
}
return nil, fmt.Errorf("choosing codespace: %w", err)
}
return codespace, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/common.go | pkg/cmd/codespace/common.go | package codespace
// This file defines functions common to the entire codespace command set.
import (
"context"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"sort"
"strings"
"github.com/AlecAivazis/survey/v2"
"github.com/AlecAivazis/survey/v2/terminal"
clicontext "github.com/cli/cli/v2/context"
"github.com/cli/cli/v2/internal/browser"
"github.com/cli/cli/v2/internal/codespaces/api"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
"golang.org/x/term"
)
type executable interface {
Executable() string
}
type App struct {
io *iostreams.IOStreams
apiClient apiClient
errLogger *log.Logger
executable executable
browser browser.Browser
remotes func() (clicontext.Remotes, error)
}
func NewApp(io *iostreams.IOStreams, exe executable, apiClient apiClient, browser browser.Browser, remotes func() (clicontext.Remotes, error)) *App {
errLogger := log.New(io.ErrOut, "", 0)
return &App{
io: io,
apiClient: apiClient,
errLogger: errLogger,
executable: exe,
browser: browser,
remotes: remotes,
}
}
// StartProgressIndicatorWithLabel starts a progress indicator with a message.
func (a *App) StartProgressIndicatorWithLabel(s string) {
a.io.StartProgressIndicatorWithLabel(s)
}
// StopProgressIndicator stops the progress indicator.
func (a *App) StopProgressIndicator() {
a.io.StopProgressIndicator()
}
func (a *App) RunWithProgress(label string, run func() error) error {
return a.io.RunWithProgress(label, run)
}
//go:generate moq -fmt goimports -rm -skip-ensure -out mock_api.go . apiClient
type apiClient interface {
ServerURL() string
GetUser(ctx context.Context) (*api.User, error)
GetCodespace(ctx context.Context, name string, includeConnection bool) (*api.Codespace, error)
GetOrgMemberCodespace(ctx context.Context, orgName string, userName string, codespaceName string) (*api.Codespace, error)
ListCodespaces(ctx context.Context, opts api.ListCodespacesOptions) ([]*api.Codespace, error)
DeleteCodespace(ctx context.Context, name string, orgName string, userName string) error
StartCodespace(ctx context.Context, name string) error
StopCodespace(ctx context.Context, name string, orgName string, userName string) error
CreateCodespace(ctx context.Context, params *api.CreateCodespaceParams) (*api.Codespace, error)
EditCodespace(ctx context.Context, codespaceName string, params *api.EditCodespaceParams) (*api.Codespace, error)
GetRepository(ctx context.Context, nwo string) (*api.Repository, error)
GetCodespacesMachines(ctx context.Context, repoID int, branch string, location string, devcontainerPath string) ([]*api.Machine, error)
GetCodespacesPermissionsCheck(ctx context.Context, repoID int, branch string, devcontainerPath string) (bool, error)
GetCodespaceRepositoryContents(ctx context.Context, codespace *api.Codespace, path string) ([]byte, error)
ListDevContainers(ctx context.Context, repoID int, branch string, limit int) (devcontainers []api.DevContainerEntry, err error)
GetCodespaceRepoSuggestions(ctx context.Context, partialSearch string, params api.RepoSearchParameters) ([]string, error)
GetCodespaceBillableOwner(ctx context.Context, nwo string) (*api.User, error)
HTTPClient() (*http.Client, error)
}
var errNoCodespaces = errors.New("you have no codespaces")
// chooseCodespaceFromList returns the codespace that the user has interactively selected from the list, or
// an error if there are no codespaces.
func chooseCodespaceFromList(ctx context.Context, codespaces []*api.Codespace, includeOwner bool, skipPromptForSingleOption bool) (*api.Codespace, error) {
if len(codespaces) == 0 {
return nil, errNoCodespaces
}
if skipPromptForSingleOption && len(codespaces) == 1 {
return codespaces[0], nil
}
sortedCodespaces := codespaces
sort.Slice(sortedCodespaces, func(i, j int) bool {
return sortedCodespaces[i].CreatedAt > sortedCodespaces[j].CreatedAt
})
csSurvey := []*survey.Question{
{
Name: "codespace",
Prompt: &survey.Select{
Message: "Choose codespace:",
Options: formatCodespacesForSelect(sortedCodespaces, includeOwner),
},
Validate: survey.Required,
},
}
prompter := &Prompter{}
var answers struct {
Codespace int
}
if err := prompter.Ask(csSurvey, &answers); err != nil {
return nil, fmt.Errorf("error getting answers: %w", err)
}
return sortedCodespaces[answers.Codespace], nil
}
func formatCodespacesForSelect(codespaces []*api.Codespace, includeOwner bool) []string {
names := make([]string, len(codespaces))
for i, apiCodespace := range codespaces {
cs := codespace{apiCodespace}
names[i] = cs.displayName(includeOwner)
}
return names
}
func safeClose(closer io.Closer, err *error) {
if closeErr := closer.Close(); *err == nil {
*err = closeErr
}
}
// hasTTY indicates whether the process connected to a terminal.
// It is not portable to assume stdin/stdout are fds 0 and 1.
var hasTTY = term.IsTerminal(int(os.Stdin.Fd())) && term.IsTerminal(int(os.Stdout.Fd()))
type SurveyPrompter interface {
Ask(qs []*survey.Question, response interface{}) error
}
type Prompter struct{}
// ask asks survey questions on the terminal, using standard options.
// It fails unless hasTTY, but ideally callers should avoid calling it in that case.
func (p *Prompter) Ask(qs []*survey.Question, response interface{}) error {
if !hasTTY {
return fmt.Errorf("no terminal")
}
err := survey.Ask(qs, response, survey.WithShowCursor(true))
// The survey package temporarily clears the terminal's ISIG mode bit
// (see tcsetattr(3)) so the QUIT button (Ctrl-C) is reported as
// ASCII \x03 (ETX) instead of delivering SIGINT to the application.
// So we have to serve ourselves the SIGINT.
//
// https://github.com/AlecAivazis/survey/#why-isnt-ctrl-c-working
if err == terminal.InterruptErr {
self, _ := os.FindProcess(os.Getpid())
_ = self.Signal(os.Interrupt) // assumes POSIX
// Suspend the goroutine, to avoid a race between
// return from main and async delivery of INT signal.
select {}
}
return err
}
var ErrTooManyArgs = errors.New("the command accepts no arguments")
func noArgsConstraint(cmd *cobra.Command, args []string) error {
if len(args) > 0 {
return ErrTooManyArgs
}
return nil
}
type codespace struct {
*api.Codespace
}
// displayName formats the codespace name for the interactive selector prompt.
func (c codespace) displayName(includeOwner bool) string {
branch := c.branchWithGitStatus()
displayName := c.DisplayName
if displayName == "" {
displayName = c.Name
}
description := fmt.Sprintf("%s [%s]: %s", c.Repository.FullName, branch, displayName)
if includeOwner {
description = fmt.Sprintf("%-15s %s", c.Owner.Login, description)
}
return description
}
// gitStatusDirty represents an unsaved changes status.
const gitStatusDirty = "*"
// branchWithGitStatus returns the branch with a star
// if the branch is currently being worked on.
func (c codespace) branchWithGitStatus() string {
if c.hasUnsavedChanges() {
return c.GitStatus.Ref + gitStatusDirty
}
return c.GitStatus.Ref
}
// hasUnsavedChanges returns whether the environment has
// unsaved changes.
func (c codespace) hasUnsavedChanges() bool {
return c.GitStatus.HasUncommittedChanges || c.GitStatus.HasUnpushedChanges
}
// running returns whether the codespace environment is running.
func (c codespace) running() bool {
return c.State == api.CodespaceStateAvailable
}
// addDeprecatedRepoShorthand adds a -r parameter (deprecated shorthand for --repo)
// which instructs the user to use -R instead.
func addDeprecatedRepoShorthand(cmd *cobra.Command, target *string) error {
cmd.Flags().StringVarP(target, "repo-deprecated", "r", "", "(Deprecated) Shorthand for --repo")
if err := cmd.Flags().MarkHidden("repo-deprecated"); err != nil {
return fmt.Errorf("error marking `-r` shorthand as hidden: %w", err)
}
if err := cmd.Flags().MarkShorthandDeprecated("repo-deprecated", "use `-R` instead"); err != nil {
return fmt.Errorf("error marking `-r` shorthand as deprecated: %w", err)
}
if cmd.Flag("codespace") != nil {
cmd.MarkFlagsMutuallyExclusive("codespace", "repo-deprecated")
}
return nil
}
// filterCodespacesByRepoOwner filters a list of codespaces by the owner of the repository.
func filterCodespacesByRepoOwner(codespaces []*api.Codespace, repoOwner string) []*api.Codespace {
filtered := make([]*api.Codespace, 0, len(codespaces))
for _, c := range codespaces {
if strings.EqualFold(c.Repository.Owner.Login, repoOwner) {
filtered = append(filtered, c)
}
}
return filtered
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/codespace/codespace_selector_test.go | pkg/cmd/codespace/codespace_selector_test.go | package codespace
import (
"context"
"fmt"
"testing"
"github.com/cli/cli/v2/internal/codespaces/api"
)
func TestSelectWithCodespaceName(t *testing.T) {
wantName := "mock-codespace"
api := &apiClientMock{
GetCodespaceFunc: func(ctx context.Context, name string, includeConnection bool) (*api.Codespace, error) {
if name != wantName {
t.Errorf("incorrect name: want %s, got %s", wantName, name)
}
return &api.Codespace{}, nil
},
}
cs := &CodespaceSelector{api: api, codespaceName: wantName}
_, err := cs.Select(context.Background())
if err != nil {
t.Errorf("unexpected error: %v", err)
}
}
func TestSelectNameWithCodespaceName(t *testing.T) {
wantName := "mock-codespace"
cs := &CodespaceSelector{codespaceName: wantName}
name, err := cs.SelectName(context.Background())
if name != wantName {
t.Errorf("incorrect name: want %s, got %s", wantName, name)
}
if err != nil {
t.Errorf("unexpected error: %v", err)
}
}
func TestFetchCodespaces(t *testing.T) {
var (
octocatOwner = api.RepositoryOwner{Login: "octocat"}
cliOwner = api.RepositoryOwner{Login: "cli"}
octocatA = &api.Codespace{
Name: "1",
Repository: api.Repository{FullName: "octocat/A", Owner: octocatOwner},
}
octocatA2 = &api.Codespace{
Name: "2",
Repository: api.Repository{FullName: "octocat/A", Owner: octocatOwner},
}
cliA = &api.Codespace{
Name: "3",
Repository: api.Repository{FullName: "cli/A", Owner: cliOwner},
}
octocatB = &api.Codespace{
Name: "4",
Repository: api.Repository{FullName: "octocat/B", Owner: octocatOwner},
}
)
tests := []struct {
tName string
apiCodespaces []*api.Codespace
codespaceName string
repoName string
repoOwner string
wantCodespaces []*api.Codespace
wantErr error
}{
// Empty case
{
tName: "empty",
apiCodespaces: nil,
wantCodespaces: nil,
wantErr: errNoCodespaces,
},
// Tests with no filtering
{
tName: "no filtering, single codespaces",
apiCodespaces: []*api.Codespace{octocatA},
wantCodespaces: []*api.Codespace{octocatA},
wantErr: nil,
},
{
tName: "no filtering, multiple codespace",
apiCodespaces: []*api.Codespace{octocatA, cliA, octocatB},
wantCodespaces: []*api.Codespace{octocatA, cliA, octocatB},
},
// Test repo filtering
{
tName: "repo name filtering, single codespace",
apiCodespaces: []*api.Codespace{octocatA},
repoName: "octocat/A",
wantCodespaces: []*api.Codespace{octocatA},
wantErr: nil,
},
{
tName: "repo name filtering, multiple codespace",
apiCodespaces: []*api.Codespace{octocatA, octocatA2, cliA, octocatB},
repoName: "octocat/A",
wantCodespaces: []*api.Codespace{octocatA, octocatA2},
wantErr: nil,
},
{
tName: "repo name filtering, multiple codespace 2",
apiCodespaces: []*api.Codespace{octocatA, cliA, octocatB},
repoName: "octocat/B",
wantCodespaces: []*api.Codespace{octocatB},
wantErr: nil,
},
{
tName: "repo name filtering, no matches",
apiCodespaces: []*api.Codespace{octocatA, cliA, octocatB},
repoName: "Unknown/unknown",
wantCodespaces: nil,
wantErr: errNoFilteredCodespaces,
},
{
tName: "repo filtering, match with repo owner",
apiCodespaces: []*api.Codespace{octocatA, octocatA2, cliA, octocatB},
repoOwner: "octocat",
wantCodespaces: []*api.Codespace{octocatA, octocatA2, octocatB},
wantErr: nil,
},
{
tName: "repo filtering, no match with repo owner",
apiCodespaces: []*api.Codespace{octocatA, cliA, octocatB},
repoOwner: "unknown",
wantCodespaces: []*api.Codespace{},
wantErr: errNoFilteredCodespaces,
},
}
for _, tt := range tests {
t.Run(tt.tName, func(t *testing.T) {
api := &apiClientMock{
ListCodespacesFunc: func(ctx context.Context, opts api.ListCodespacesOptions) ([]*api.Codespace, error) {
return tt.apiCodespaces, nil
},
}
cs := &CodespaceSelector{
api: api,
repoName: tt.repoName,
repoOwner: tt.repoOwner,
}
codespaces, err := cs.fetchCodespaces(context.Background())
if err != tt.wantErr {
t.Errorf("expected error to be %v, got %v", tt.wantErr, err)
}
if fmt.Sprintf("%v", tt.wantCodespaces) != fmt.Sprintf("%v", codespaces) {
t.Errorf("expected codespaces to be %v, got %v", tt.wantCodespaces, codespaces)
}
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/actions/actions.go | pkg/cmd/actions/actions.go | package actions
import (
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
func NewCmdActions(f *cmdutil.Factory) *cobra.Command {
cs := f.IOStreams.ColorScheme()
cmd := &cobra.Command{
Use: "actions",
Short: "Learn about working with GitHub Actions",
Long: actionsExplainer(cs),
Hidden: true,
}
cmdutil.DisableAuthCheck(cmd)
return cmd
}
func actionsExplainer(cs *iostreams.ColorScheme) string {
header := cs.Bold("Welcome to GitHub Actions on the command line.")
runHeader := cs.Bold("Interacting with workflow runs")
workflowHeader := cs.Bold("Interacting with workflow files")
cacheHeader := cs.Bold("Interacting with the GitHub Actions cache")
return heredoc.Docf(`
%[2]s
GitHub CLI integrates with GitHub Actions to help you manage runs and workflows.
%[3]s
gh run list: List recent workflow runs
gh run view: View details for a workflow run or one of its jobs
gh run watch: Watch a workflow run while it executes
gh run rerun: Rerun a failed workflow run
gh run download: Download artifacts generated by runs
To see more help, run %[1]sgh help run <subcommand>%[1]s
%[4]s
gh workflow list: List workflow files in your repository
gh workflow view: View details for a workflow file
gh workflow enable: Enable a workflow file
gh workflow disable: Disable a workflow file
gh workflow run: Trigger a workflow_dispatch run for a workflow file
To see more help, run %[1]sgh help workflow <subcommand>%[1]s
%[5]s
gh cache list: List all the caches saved in GitHub Actions for a repository
gh cache delete: Delete one or all saved caches in GitHub Actions for a repository
To see more help, run %[1]sgh help cache <subcommand>%[1]s
`, "`", header, runHeader, workflowHeader, cacheHeader)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/ssh-key/ssh_key.go | pkg/cmd/ssh-key/ssh_key.go | package key
import (
cmdAdd "github.com/cli/cli/v2/pkg/cmd/ssh-key/add"
cmdDelete "github.com/cli/cli/v2/pkg/cmd/ssh-key/delete"
cmdList "github.com/cli/cli/v2/pkg/cmd/ssh-key/list"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/spf13/cobra"
)
func NewCmdSSHKey(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "ssh-key <command>",
Short: "Manage SSH keys",
Long: "Manage SSH keys registered with your GitHub account.",
}
cmd.AddCommand(cmdAdd.NewCmdAdd(f, nil))
cmd.AddCommand(cmdDelete.NewCmdDelete(f, nil))
cmd.AddCommand(cmdList.NewCmdList(f, nil))
return cmd
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/ssh-key/delete/delete.go | pkg/cmd/ssh-key/delete/delete.go | package delete
import (
"fmt"
"net/http"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/prompter"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type DeleteOptions struct {
IO *iostreams.IOStreams
Config func() (gh.Config, error)
HttpClient func() (*http.Client, error)
KeyID string
Confirmed bool
Prompter prompter.Prompter
}
func NewCmdDelete(f *cmdutil.Factory, runF func(*DeleteOptions) error) *cobra.Command {
opts := &DeleteOptions{
HttpClient: f.HttpClient,
Config: f.Config,
IO: f.IOStreams,
Prompter: f.Prompter,
}
cmd := &cobra.Command{
Use: "delete <id>",
Short: "Delete an SSH key from your GitHub account",
Args: cmdutil.ExactArgs(1, "cannot delete: key id required"),
RunE: func(cmd *cobra.Command, args []string) error {
opts.KeyID = args[0]
if !opts.IO.CanPrompt() && !opts.Confirmed {
return cmdutil.FlagErrorf("--yes required when not running interactively")
}
if runF != nil {
return runF(opts)
}
return deleteRun(opts)
},
}
cmd.Flags().BoolVar(&opts.Confirmed, "confirm", false, "Skip the confirmation prompt")
_ = cmd.Flags().MarkDeprecated("confirm", "use `--yes` instead")
cmd.Flags().BoolVarP(&opts.Confirmed, "yes", "y", false, "Skip the confirmation prompt")
return cmd
}
func deleteRun(opts *DeleteOptions) error {
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
cfg, err := opts.Config()
if err != nil {
return err
}
host, _ := cfg.Authentication().DefaultHost()
key, err := getSSHKey(httpClient, host, opts.KeyID)
if err != nil {
return err
}
if !opts.Confirmed {
if err := opts.Prompter.ConfirmDeletion(key.Title); err != nil {
return err
}
}
err = deleteSSHKey(httpClient, host, opts.KeyID)
if err != nil {
return err
}
if opts.IO.IsStdoutTTY() {
cs := opts.IO.ColorScheme()
fmt.Fprintf(opts.IO.Out, "%s SSH key %q (%s) deleted from your account\n", cs.SuccessIcon(), key.Title, opts.KeyID)
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/ssh-key/delete/delete_test.go | pkg/cmd/ssh-key/delete/delete_test.go | package delete
import (
"bytes"
"net/http"
"testing"
"github.com/cli/cli/v2/internal/config"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/prompter"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
)
func TestNewCmdDelete(t *testing.T) {
tests := []struct {
name string
tty bool
input string
output DeleteOptions
wantErr bool
wantErrMsg string
}{
{
name: "tty",
tty: true,
input: "123",
output: DeleteOptions{KeyID: "123", Confirmed: false},
},
{
name: "confirm flag tty",
tty: true,
input: "123 --yes",
output: DeleteOptions{KeyID: "123", Confirmed: true},
},
{
name: "shorthand confirm flag tty",
tty: true,
input: "123 -y",
output: DeleteOptions{KeyID: "123", Confirmed: true},
},
{
name: "no tty",
input: "123",
wantErr: true,
wantErrMsg: "--yes required when not running interactively",
},
{
name: "confirm flag no tty",
input: "123 --yes",
output: DeleteOptions{KeyID: "123", Confirmed: true},
},
{
name: "shorthand confirm flag no tty",
input: "123 -y",
output: DeleteOptions{KeyID: "123", Confirmed: true},
},
{
name: "no args",
input: "",
wantErr: true,
wantErrMsg: "cannot delete: key id required",
},
{
name: "too many args",
input: "123 456",
wantErr: true,
wantErrMsg: "too many arguments",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
ios.SetStdinTTY(tt.tty)
ios.SetStdoutTTY(tt.tty)
f := &cmdutil.Factory{
IOStreams: ios,
}
argv, err := shlex.Split(tt.input)
assert.NoError(t, err)
var cmdOpts *DeleteOptions
cmd := NewCmdDelete(f, func(opts *DeleteOptions) error {
cmdOpts = opts
return nil
})
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
_, err = cmd.ExecuteC()
if tt.wantErr {
assert.Error(t, err)
assert.EqualError(t, err, tt.wantErrMsg)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.output.KeyID, cmdOpts.KeyID)
assert.Equal(t, tt.output.Confirmed, cmdOpts.Confirmed)
})
}
}
func Test_deleteRun(t *testing.T) {
keyResp := "{\"title\":\"My Key\"}"
tests := []struct {
name string
tty bool
opts DeleteOptions
httpStubs func(*httpmock.Registry)
prompterStubs func(*prompter.PrompterMock)
wantStdout string
wantErr bool
wantErrMsg string
}{
{
name: "delete tty",
tty: true,
opts: DeleteOptions{KeyID: "123"},
prompterStubs: func(pm *prompter.PrompterMock) {
pm.ConfirmDeletionFunc = func(_ string) error {
return nil
}
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.REST("GET", "user/keys/123"), httpmock.StatusStringResponse(200, keyResp))
reg.Register(httpmock.REST("DELETE", "user/keys/123"), httpmock.StatusStringResponse(204, ""))
},
wantStdout: "β SSH key \"My Key\" (123) deleted from your account\n",
},
{
name: "delete with confirm flag tty",
tty: true,
opts: DeleteOptions{KeyID: "123", Confirmed: true},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.REST("GET", "user/keys/123"), httpmock.StatusStringResponse(200, keyResp))
reg.Register(httpmock.REST("DELETE", "user/keys/123"), httpmock.StatusStringResponse(204, ""))
},
wantStdout: "β SSH key \"My Key\" (123) deleted from your account\n",
},
{
name: "not found tty",
tty: true,
opts: DeleteOptions{KeyID: "123"},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.REST("GET", "user/keys/123"), httpmock.StatusStringResponse(404, ""))
},
wantErr: true,
wantErrMsg: "HTTP 404 (https://api.github.com/user/keys/123)",
},
{
name: "delete no tty",
opts: DeleteOptions{KeyID: "123", Confirmed: true},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.REST("GET", "user/keys/123"), httpmock.StatusStringResponse(200, keyResp))
reg.Register(httpmock.REST("DELETE", "user/keys/123"), httpmock.StatusStringResponse(204, ""))
},
wantStdout: "",
},
{
name: "not found no tty",
opts: DeleteOptions{KeyID: "123", Confirmed: true},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.REST("GET", "user/keys/123"), httpmock.StatusStringResponse(404, ""))
},
wantErr: true,
wantErrMsg: "HTTP 404 (https://api.github.com/user/keys/123)",
},
}
for _, tt := range tests {
pm := &prompter.PrompterMock{}
if tt.prompterStubs != nil {
tt.prompterStubs(pm)
}
tt.opts.Prompter = pm
reg := &httpmock.Registry{}
if tt.httpStubs != nil {
tt.httpStubs(reg)
}
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
tt.opts.Config = func() (gh.Config, error) {
return config.NewBlankConfig(), nil
}
ios, _, stdout, _ := iostreams.Test()
ios.SetStdinTTY(tt.tty)
ios.SetStdoutTTY(tt.tty)
tt.opts.IO = ios
t.Run(tt.name, func(t *testing.T) {
err := deleteRun(&tt.opts)
reg.Verify(t)
if tt.wantErr {
assert.Error(t, err)
assert.EqualError(t, err, tt.wantErrMsg)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.wantStdout, stdout.String())
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/ssh-key/delete/http.go | pkg/cmd/ssh-key/delete/http.go | package delete
import (
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghinstance"
)
type sshKey struct {
Title string
}
func deleteSSHKey(httpClient *http.Client, host string, keyID string) error {
url := fmt.Sprintf("%suser/keys/%s", ghinstance.RESTPrefix(host), keyID)
req, err := http.NewRequest("DELETE", url, nil)
if err != nil {
return err
}
resp, err := httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode > 299 {
return api.HandleHTTPError(resp)
}
return nil
}
func getSSHKey(httpClient *http.Client, host string, keyID string) (*sshKey, error) {
url := fmt.Sprintf("%suser/keys/%s", ghinstance.RESTPrefix(host), keyID)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode > 299 {
return nil, api.HandleHTTPError(resp)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var key sshKey
err = json.Unmarshal(b, &key)
if err != nil {
return nil, err
}
return &key, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/ssh-key/list/list_test.go | pkg/cmd/ssh-key/list/list_test.go | package list
import (
"fmt"
"net/http"
"testing"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/config"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
)
func TestListRun(t *testing.T) {
tests := []struct {
name string
opts ListOptions
isTTY bool
wantStdout string
wantStderr string
wantErr bool
}{
{
name: "list authentication and signing keys; in tty",
opts: ListOptions{
HTTPClient: func() (*http.Client, error) {
createdAt := time.Now().Add(time.Duration(-24) * time.Hour)
reg := &httpmock.Registry{}
reg.Register(
httpmock.REST("GET", "user/keys"),
httpmock.StringResponse(fmt.Sprintf(`[
{
"id": 1234,
"key": "ssh-rsa AAAABbBB123",
"title": "Mac",
"created_at": "%[1]s"
},
{
"id": 5678,
"key": "ssh-rsa EEEEEEEK247",
"title": "hubot@Windows",
"created_at": "%[1]s"
}
]`, createdAt.Format(time.RFC3339))),
)
reg.Register(
httpmock.REST("GET", "user/ssh_signing_keys"),
httpmock.StringResponse(fmt.Sprintf(`[
{
"id": 321,
"key": "ssh-rsa AAAABbBB123",
"title": "Mac Signing",
"created_at": "%[1]s"
}
]`, createdAt.Format(time.RFC3339))),
)
return &http.Client{Transport: reg}, nil
},
},
isTTY: true,
wantStdout: heredoc.Doc(`
TITLE ID KEY TYPE ADDED
Mac 1234 ssh-rsa AAAABbBB123 authentication about 1 day ago
hubot@Windows 5678 ssh-rsa EEEEEEEK247 authentication about 1 day ago
Mac Signing 321 ssh-rsa AAAABbBB123 signing about 1 day ago
`),
wantStderr: "",
},
{
name: "list authentication and signing keys; in non-tty",
opts: ListOptions{
HTTPClient: func() (*http.Client, error) {
createdAt, _ := time.Parse(time.RFC3339, "2020-08-31T15:44:24+02:00")
reg := &httpmock.Registry{}
reg.Register(
httpmock.REST("GET", "user/keys"),
httpmock.StringResponse(fmt.Sprintf(`[
{
"id": 1234,
"key": "ssh-rsa AAAABbBB123",
"title": "Mac",
"created_at": "%[1]s"
},
{
"id": 5678,
"key": "ssh-rsa EEEEEEEK247",
"title": "hubot@Windows",
"created_at": "%[1]s"
}
]`, createdAt.Format(time.RFC3339))),
)
reg.Register(
httpmock.REST("GET", "user/ssh_signing_keys"),
httpmock.StringResponse(fmt.Sprintf(`[
{
"id": 321,
"key": "ssh-rsa AAAABbBB123",
"title": "Mac Signing",
"created_at": "%[1]s"
}
]`, createdAt.Format(time.RFC3339))),
)
return &http.Client{Transport: reg}, nil
},
},
isTTY: false,
wantStdout: heredoc.Doc(`
Mac ssh-rsa AAAABbBB123 2020-08-31T15:44:24+02:00 1234 authentication
hubot@Windows ssh-rsa EEEEEEEK247 2020-08-31T15:44:24+02:00 5678 authentication
Mac Signing ssh-rsa AAAABbBB123 2020-08-31T15:44:24+02:00 321 signing
`),
wantStderr: "",
},
{
name: "only authentication ssh keys are available",
opts: ListOptions{
HTTPClient: func() (*http.Client, error) {
createdAt := time.Now().Add(time.Duration(-24) * time.Hour)
reg := &httpmock.Registry{}
reg.Register(
httpmock.REST("GET", "user/keys"),
httpmock.StringResponse(fmt.Sprintf(`[
{
"id": 1234,
"key": "ssh-rsa AAAABbBB123",
"title": "Mac",
"created_at": "%[1]s"
}
]`, createdAt.Format(time.RFC3339))),
)
reg.Register(
httpmock.REST("GET", "user/ssh_signing_keys"),
httpmock.StatusStringResponse(404, "Not Found"),
)
return &http.Client{Transport: reg}, nil
},
},
wantStdout: heredoc.Doc(`
TITLE ID KEY TYPE ADDED
Mac 1234 ssh-rsa AAAABbBB123 authentication about 1 day ago
`),
wantStderr: heredoc.Doc(`
warning: HTTP 404 (https://api.github.com/user/ssh_signing_keys?per_page=100)
`),
wantErr: false,
isTTY: true,
},
{
name: "only signing ssh keys are available",
opts: ListOptions{
HTTPClient: func() (*http.Client, error) {
createdAt := time.Now().Add(time.Duration(-24) * time.Hour)
reg := &httpmock.Registry{}
reg.Register(
httpmock.REST("GET", "user/ssh_signing_keys"),
httpmock.StringResponse(fmt.Sprintf(`[
{
"id": 1234,
"key": "ssh-rsa AAAABbBB123",
"title": "Mac",
"created_at": "%[1]s"
}
]`, createdAt.Format(time.RFC3339))),
)
reg.Register(
httpmock.REST("GET", "user/keys"),
httpmock.StatusStringResponse(404, "Not Found"),
)
return &http.Client{Transport: reg}, nil
},
},
wantStdout: heredoc.Doc(`
TITLE ID KEY TYPE ADDED
Mac 1234 ssh-rsa AAAABbBB123 signing about 1 day ago
`),
wantStderr: heredoc.Doc(`
warning: HTTP 404 (https://api.github.com/user/keys?per_page=100)
`),
wantErr: false,
isTTY: true,
},
{
name: "no keys tty",
opts: ListOptions{
HTTPClient: func() (*http.Client, error) {
reg := &httpmock.Registry{}
reg.Register(
httpmock.REST("GET", "user/keys"),
httpmock.StringResponse(`[]`),
)
reg.Register(
httpmock.REST("GET", "user/ssh_signing_keys"),
httpmock.StringResponse(`[]`),
)
return &http.Client{Transport: reg}, nil
},
},
wantStdout: "",
wantStderr: "",
wantErr: true,
isTTY: true,
},
{
name: "no keys non-tty",
opts: ListOptions{
HTTPClient: func() (*http.Client, error) {
reg := &httpmock.Registry{}
reg.Register(
httpmock.REST("GET", "user/keys"),
httpmock.StringResponse(`[]`),
)
reg.Register(
httpmock.REST("GET", "user/ssh_signing_keys"),
httpmock.StringResponse(`[]`),
)
return &http.Client{Transport: reg}, nil
},
},
wantStdout: "",
wantStderr: "",
wantErr: true,
isTTY: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdinTTY(tt.isTTY)
ios.SetStdoutTTY(tt.isTTY)
ios.SetStderrTTY(tt.isTTY)
opts := tt.opts
opts.IO = ios
opts.Config = func() (gh.Config, error) { return config.NewBlankConfig(), nil }
err := listRun(&opts)
if (err != nil) != tt.wantErr {
t.Errorf("listRun() return error: %v", err)
return
}
if stdout.String() != tt.wantStdout {
t.Errorf("wants stdout %q, got %q", tt.wantStdout, stdout.String())
}
if stderr.String() != tt.wantStderr {
t.Errorf("wants stderr %q, got %q", tt.wantStderr, stderr.String())
}
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/ssh-key/list/list.go | pkg/cmd/ssh-key/list/list.go | package list
import (
"errors"
"fmt"
"io"
"net/http"
"strconv"
"time"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/tableprinter"
"github.com/cli/cli/v2/pkg/cmd/ssh-key/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type ListOptions struct {
IO *iostreams.IOStreams
Config func() (gh.Config, error)
HTTPClient func() (*http.Client, error)
}
func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Command {
opts := &ListOptions{
IO: f.IOStreams,
Config: f.Config,
HTTPClient: f.HttpClient,
}
cmd := &cobra.Command{
Use: "list",
Short: "Lists SSH keys in your GitHub account",
Aliases: []string{"ls"},
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
if runF != nil {
return runF(opts)
}
return listRun(opts)
},
}
return cmd
}
func listRun(opts *ListOptions) error {
apiClient, err := opts.HTTPClient()
if err != nil {
return err
}
cfg, err := opts.Config()
if err != nil {
return err
}
host, _ := cfg.Authentication().DefaultHost()
sshAuthKeys, authKeyErr := shared.UserKeys(apiClient, host, "")
if authKeyErr != nil {
printError(opts.IO.ErrOut, authKeyErr)
}
sshSigningKeys, signKeyErr := shared.UserSigningKeys(apiClient, host, "")
if signKeyErr != nil {
printError(opts.IO.ErrOut, signKeyErr)
}
if authKeyErr != nil && signKeyErr != nil {
return cmdutil.SilentError
}
sshKeys := append(sshAuthKeys, sshSigningKeys...)
if len(sshKeys) == 0 {
return cmdutil.NewNoResultsError("no SSH keys present in the GitHub account")
}
t := tableprinter.New(opts.IO, tableprinter.WithHeader("TITLE", "ID", "KEY", "TYPE", "ADDED"))
cs := opts.IO.ColorScheme()
now := time.Now()
for _, sshKey := range sshKeys {
id := strconv.Itoa(sshKey.ID)
if t.IsTTY() {
t.AddField(sshKey.Title)
t.AddField(id)
t.AddField(sshKey.Key, tableprinter.WithTruncate(truncateMiddle))
t.AddField(sshKey.Type)
t.AddTimeField(now, sshKey.CreatedAt, cs.Muted)
} else {
t.AddField(sshKey.Title)
t.AddField(sshKey.Key)
t.AddTimeField(now, sshKey.CreatedAt, cs.Muted)
t.AddField(id)
t.AddField(sshKey.Type)
}
t.EndRow()
}
return t.Render()
}
func truncateMiddle(maxWidth int, t string) string {
if len(t) <= maxWidth {
return t
}
ellipsis := "..."
if maxWidth < len(ellipsis)+2 {
return t[0:maxWidth]
}
halfWidth := (maxWidth - len(ellipsis)) / 2
remainder := (maxWidth - len(ellipsis)) % 2
return t[0:halfWidth+remainder] + ellipsis + t[len(t)-halfWidth:]
}
func printError(w io.Writer, err error) {
fmt.Fprintln(w, "warning: ", err)
var httpErr api.HTTPError
if errors.As(err, &httpErr) {
if msg := httpErr.ScopesSuggestion(); msg != "" {
fmt.Fprintln(w, msg)
}
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/ssh-key/add/add.go | pkg/cmd/ssh-key/add/add.go | package add
import (
"fmt"
"io"
"net/http"
"os"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/pkg/cmd/ssh-key/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type AddOptions struct {
IO *iostreams.IOStreams
Config func() (gh.Config, error)
HTTPClient func() (*http.Client, error)
KeyFile string
Title string
Type string
}
func NewCmdAdd(f *cmdutil.Factory, runF func(*AddOptions) error) *cobra.Command {
opts := &AddOptions{
HTTPClient: f.HttpClient,
Config: f.Config,
IO: f.IOStreams,
}
cmd := &cobra.Command{
Use: "add [<key-file>]",
Short: "Add an SSH key to your GitHub account",
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
if opts.IO.IsStdoutTTY() && opts.IO.IsStdinTTY() {
return cmdutil.FlagErrorf("public key file missing")
}
opts.KeyFile = "-"
} else {
opts.KeyFile = args[0]
}
if runF != nil {
return runF(opts)
}
return runAdd(opts)
},
}
typeEnums := []string{shared.AuthenticationKey, shared.SigningKey}
cmdutil.StringEnumFlag(cmd, &opts.Type, "type", "", shared.AuthenticationKey, typeEnums, "Type of the ssh key")
cmd.Flags().StringVarP(&opts.Title, "title", "t", "", "Title for the new key")
return cmd
}
func runAdd(opts *AddOptions) error {
httpClient, err := opts.HTTPClient()
if err != nil {
return err
}
var keyReader io.Reader
if opts.KeyFile == "-" {
keyReader = opts.IO.In
defer opts.IO.In.Close()
} else {
f, err := os.Open(opts.KeyFile)
if err != nil {
return err
}
defer f.Close()
keyReader = f
}
cfg, err := opts.Config()
if err != nil {
return err
}
hostname, _ := cfg.Authentication().DefaultHost()
var uploaded bool
if opts.Type == shared.SigningKey {
uploaded, err = SSHSigningKeyUpload(httpClient, hostname, keyReader, opts.Title)
} else {
uploaded, err = SSHKeyUpload(httpClient, hostname, keyReader, opts.Title)
}
if err != nil {
return err
}
cs := opts.IO.ColorScheme()
if uploaded {
fmt.Fprintf(opts.IO.ErrOut, "%s Public key added to your account\n", cs.SuccessIcon())
} else {
fmt.Fprintf(opts.IO.ErrOut, "%s Public key already exists on your account\n", cs.SuccessIcon())
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/ssh-key/add/http.go | pkg/cmd/ssh-key/add/http.go | package add
import (
"bytes"
"encoding/json"
"errors"
"io"
"net/http"
"strings"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghinstance"
"github.com/cli/cli/v2/pkg/cmd/ssh-key/shared"
)
// Uploads the provided SSH key. Returns true if the key was uploaded, false if it was not.
func SSHKeyUpload(httpClient *http.Client, hostname string, keyFile io.Reader, title string) (bool, error) {
url := ghinstance.RESTPrefix(hostname) + "user/keys"
keyBytes, err := io.ReadAll(keyFile)
if err != nil {
return false, err
}
fullUserKey := string(keyBytes)
splitKey := strings.Fields(fullUserKey)
if len(splitKey) < 2 {
return false, errors.New("provided key is not in a valid format")
}
keyToCompare := splitKey[0] + " " + splitKey[1]
keys, err := shared.UserKeys(httpClient, hostname, "")
if err != nil {
return false, err
}
for _, k := range keys {
if k.Key == keyToCompare {
return false, nil
}
}
payload := map[string]string{
"title": title,
"key": fullUserKey,
}
err = keyUpload(httpClient, url, payload)
if err != nil {
return false, err
}
return true, nil
}
// Uploads the provided SSH Signing key. Returns true if the key was uploaded, false if it was not.
func SSHSigningKeyUpload(httpClient *http.Client, hostname string, keyFile io.Reader, title string) (bool, error) {
url := ghinstance.RESTPrefix(hostname) + "user/ssh_signing_keys"
keyBytes, err := io.ReadAll(keyFile)
if err != nil {
return false, err
}
fullUserKey := string(keyBytes)
splitKey := strings.Fields(fullUserKey)
if len(splitKey) < 2 {
return false, errors.New("provided key is not in a valid format")
}
keyToCompare := splitKey[0] + " " + splitKey[1]
keys, err := shared.UserSigningKeys(httpClient, hostname, "")
if err != nil {
return false, err
}
for _, k := range keys {
if k.Key == keyToCompare {
return false, nil
}
}
payload := map[string]string{
"title": title,
"key": fullUserKey,
}
err = keyUpload(httpClient, url, payload)
if err != nil {
return false, err
}
return true, nil
}
func keyUpload(httpClient *http.Client, url string, payload map[string]string) error {
payloadBytes, err := json.Marshal(payload)
if err != nil {
return err
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(payloadBytes))
if err != nil {
return err
}
resp, err := httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode > 299 {
return api.HandleHTTPError(resp)
}
_, err = io.Copy(io.Discard, resp.Body)
if err != nil {
return err
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/ssh-key/add/add_test.go | pkg/cmd/ssh-key/add/add_test.go | package add
import (
"net/http"
"testing"
"github.com/cli/cli/v2/internal/config"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/stretchr/testify/assert"
)
func Test_runAdd(t *testing.T) {
tests := []struct {
name string
stdin string
opts AddOptions
httpStubs func(*httpmock.Registry)
wantStdout string
wantStderr string
wantErrMsg string
}{
{
name: "valid key format, not already in use",
stdin: "ssh-ed25519 asdf",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "user/keys"),
httpmock.StringResponse("[]"))
reg.Register(
httpmock.REST("POST", "user/keys"),
httpmock.RESTPayload(200, ``, func(payload map[string]interface{}) {
assert.Contains(t, payload, "key")
assert.Empty(t, payload["title"])
}))
},
wantStdout: "",
wantStderr: "β Public key added to your account\n",
wantErrMsg: "",
opts: AddOptions{KeyFile: "-"},
},
{
name: "valid signing key format, not already in use",
stdin: "ssh-ed25519 asdf",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "user/ssh_signing_keys"),
httpmock.StringResponse("[]"))
reg.Register(
httpmock.REST("POST", "user/ssh_signing_keys"),
httpmock.RESTPayload(200, ``, func(payload map[string]interface{}) {
assert.Contains(t, payload, "key")
assert.Empty(t, payload["title"])
}))
},
wantStdout: "",
wantStderr: "β Public key added to your account\n",
wantErrMsg: "",
opts: AddOptions{KeyFile: "-", Type: "signing"},
},
{
name: "valid key format, already in use",
stdin: "ssh-ed25519 asdf title",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "user/keys"),
httpmock.StringResponse(`[
{
"id": 1,
"key": "ssh-ed25519 asdf",
"title": "anything"
}
]`))
},
wantStdout: "",
wantStderr: "β Public key already exists on your account\n",
wantErrMsg: "",
opts: AddOptions{KeyFile: "-"},
},
{
name: "valid signing key format, already in use",
stdin: "ssh-ed25519 asdf title",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "user/ssh_signing_keys"),
httpmock.StringResponse(`[
{
"id": 1,
"key": "ssh-ed25519 asdf",
"title": "anything"
}
]`))
},
wantStdout: "",
wantStderr: "β Public key already exists on your account\n",
wantErrMsg: "",
opts: AddOptions{KeyFile: "-", Type: "signing"},
},
{
name: "invalid key format",
stdin: "ssh-ed25519",
wantStdout: "",
wantStderr: "",
wantErrMsg: "provided key is not in a valid format",
opts: AddOptions{KeyFile: "-"},
},
{
name: "invalid signing key format",
stdin: "ssh-ed25519",
wantStdout: "",
wantStderr: "",
wantErrMsg: "provided key is not in a valid format",
opts: AddOptions{KeyFile: "-", Type: "signing"},
},
}
for _, tt := range tests {
ios, stdin, stdout, stderr := iostreams.Test()
ios.SetStdinTTY(false)
ios.SetStdoutTTY(true)
ios.SetStderrTTY(true)
stdin.WriteString(tt.stdin)
reg := &httpmock.Registry{}
tt.opts.IO = ios
tt.opts.HTTPClient = func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
if tt.httpStubs != nil {
tt.httpStubs(reg)
}
tt.opts.Config = func() (gh.Config, error) {
return config.NewBlankConfig(), nil
}
t.Run(tt.name, func(t *testing.T) {
defer reg.Verify(t)
err := runAdd(&tt.opts)
if tt.wantErrMsg != "" {
assert.Equal(t, tt.wantErrMsg, err.Error())
} else {
assert.NoError(t, err)
}
assert.Equal(t, tt.wantStdout, stdout.String())
assert.Equal(t, tt.wantStderr, stderr.String())
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/ssh-key/shared/user_keys.go | pkg/cmd/ssh-key/shared/user_keys.go | package shared
import (
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghinstance"
)
const (
AuthenticationKey = "authentication"
SigningKey = "signing"
)
type sshKey struct {
ID int
Key string
Title string
Type string
CreatedAt time.Time `json:"created_at"`
}
func UserKeys(httpClient *http.Client, host, userHandle string) ([]sshKey, error) {
resource := "user/keys"
if userHandle != "" {
resource = fmt.Sprintf("users/%s/keys", userHandle)
}
url := fmt.Sprintf("%s%s?per_page=%d", ghinstance.RESTPrefix(host), resource, 100)
keys, err := getUserKeys(httpClient, url)
if err != nil {
return nil, err
}
for i := 0; i < len(keys); i++ {
keys[i].Type = AuthenticationKey
}
return keys, nil
}
func UserSigningKeys(httpClient *http.Client, host, userHandle string) ([]sshKey, error) {
resource := "user/ssh_signing_keys"
if userHandle != "" {
resource = fmt.Sprintf("users/%s/ssh_signing_keys", userHandle)
}
url := fmt.Sprintf("%s%s?per_page=%d", ghinstance.RESTPrefix(host), resource, 100)
keys, err := getUserKeys(httpClient, url)
if err != nil {
return nil, err
}
for i := 0; i < len(keys); i++ {
keys[i].Type = SigningKey
}
return keys, nil
}
func getUserKeys(httpClient *http.Client, url string) ([]sshKey, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode > 299 {
return nil, api.HandleHTTPError(resp)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var keys []sshKey
err = json.Unmarshal(b, &keys)
if err != nil {
return nil, err
}
return keys, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/project.go | pkg/cmd/project/project.go | package project
import (
"github.com/MakeNowJust/heredoc"
cmdClose "github.com/cli/cli/v2/pkg/cmd/project/close"
cmdCopy "github.com/cli/cli/v2/pkg/cmd/project/copy"
cmdCreate "github.com/cli/cli/v2/pkg/cmd/project/create"
cmdDelete "github.com/cli/cli/v2/pkg/cmd/project/delete"
cmdEdit "github.com/cli/cli/v2/pkg/cmd/project/edit"
cmdFieldCreate "github.com/cli/cli/v2/pkg/cmd/project/field-create"
cmdFieldDelete "github.com/cli/cli/v2/pkg/cmd/project/field-delete"
cmdFieldList "github.com/cli/cli/v2/pkg/cmd/project/field-list"
cmdItemAdd "github.com/cli/cli/v2/pkg/cmd/project/item-add"
cmdItemArchive "github.com/cli/cli/v2/pkg/cmd/project/item-archive"
cmdItemCreate "github.com/cli/cli/v2/pkg/cmd/project/item-create"
cmdItemDelete "github.com/cli/cli/v2/pkg/cmd/project/item-delete"
cmdItemEdit "github.com/cli/cli/v2/pkg/cmd/project/item-edit"
cmdItemList "github.com/cli/cli/v2/pkg/cmd/project/item-list"
cmdLink "github.com/cli/cli/v2/pkg/cmd/project/link"
cmdList "github.com/cli/cli/v2/pkg/cmd/project/list"
cmdTemplate "github.com/cli/cli/v2/pkg/cmd/project/mark-template"
cmdUnlink "github.com/cli/cli/v2/pkg/cmd/project/unlink"
cmdView "github.com/cli/cli/v2/pkg/cmd/project/view"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/spf13/cobra"
)
func NewCmdProject(f *cmdutil.Factory) *cobra.Command {
var cmd = &cobra.Command{
Use: "project <command>",
Short: "Work with GitHub Projects.",
Long: heredoc.Docf(`
Work with GitHub Projects.
The minimum required scope for the token is: %[1]sproject%[1]s.
You can verify your token scope by running %[1]sgh auth status%[1]s and
add the %[1]sproject%[1]s scope by running %[1]sgh auth refresh -s project%[1]s.
`, "`"),
Example: heredoc.Doc(`
$ gh project create --owner monalisa --title "Roadmap"
$ gh project view 1 --owner cli --web
$ gh project field-list 1 --owner cli
$ gh project item-list 1 --owner cli
`),
GroupID: "core",
}
cmd.AddCommand(cmdList.NewCmdList(f, nil))
cmd.AddCommand(cmdCreate.NewCmdCreate(f, nil))
cmd.AddCommand(cmdCopy.NewCmdCopy(f, nil))
cmd.AddCommand(cmdClose.NewCmdClose(f, nil))
cmd.AddCommand(cmdDelete.NewCmdDelete(f, nil))
cmd.AddCommand(cmdEdit.NewCmdEdit(f, nil))
cmd.AddCommand(cmdLink.NewCmdLink(f, nil))
cmd.AddCommand(cmdView.NewCmdView(f, nil))
cmd.AddCommand(cmdTemplate.NewCmdMarkTemplate(f, nil))
cmd.AddCommand(cmdUnlink.NewCmdUnlink(f, nil))
// items
cmd.AddCommand(cmdItemList.NewCmdList(f, nil))
cmd.AddCommand(cmdItemCreate.NewCmdCreateItem(f, nil))
cmd.AddCommand(cmdItemAdd.NewCmdAddItem(f, nil))
cmd.AddCommand(cmdItemEdit.NewCmdEditItem(f, nil))
cmd.AddCommand(cmdItemArchive.NewCmdArchiveItem(f, nil))
cmd.AddCommand(cmdItemDelete.NewCmdDeleteItem(f, nil))
// fields
cmd.AddCommand(cmdFieldList.NewCmdList(f, nil))
cmd.AddCommand(cmdFieldCreate.NewCmdCreateField(f, nil))
cmd.AddCommand(cmdFieldDelete.NewCmdDeleteField(f, nil))
return cmd
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/item-list/item_list.go | pkg/cmd/project/item-list/item_list.go | package itemlist
import (
"fmt"
"strconv"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/tableprinter"
"github.com/cli/cli/v2/pkg/cmd/project/shared/client"
"github.com/cli/cli/v2/pkg/cmd/project/shared/queries"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type listOpts struct {
limit int
owner string
number int32
exporter cmdutil.Exporter
}
type listConfig struct {
io *iostreams.IOStreams
client *queries.Client
opts listOpts
}
func NewCmdList(f *cmdutil.Factory, runF func(config listConfig) error) *cobra.Command {
opts := listOpts{}
listCmd := &cobra.Command{
Short: "List the items in a project",
Use: "item-list [<number>]",
Example: heredoc.Doc(`
# List the items in the current users's project "1"
$ gh project item-list 1 --owner "@me"
`),
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
client, err := client.New(f)
if err != nil {
return err
}
if len(args) == 1 {
num, err := strconv.ParseInt(args[0], 10, 32)
if err != nil {
return cmdutil.FlagErrorf("invalid number: %v", args[0])
}
opts.number = int32(num)
}
config := listConfig{
io: f.IOStreams,
client: client,
opts: opts,
}
// allow testing of the command without actually running it
if runF != nil {
return runF(config)
}
return runList(config)
},
}
listCmd.Flags().StringVar(&opts.owner, "owner", "", "Login of the owner. Use \"@me\" for the current user.")
cmdutil.AddFormatFlags(listCmd, &opts.exporter)
listCmd.Flags().IntVarP(&opts.limit, "limit", "L", queries.LimitDefault, "Maximum number of items to fetch")
return listCmd
}
func runList(config listConfig) error {
canPrompt := config.io.CanPrompt()
owner, err := config.client.NewOwner(canPrompt, config.opts.owner)
if err != nil {
return err
}
// no need to fetch the project if we already have the number
if config.opts.number == 0 {
project, err := config.client.NewProject(canPrompt, owner, config.opts.number, false)
if err != nil {
return err
}
config.opts.number = project.Number
}
project, err := config.client.ProjectItems(owner, config.opts.number, config.opts.limit)
if err != nil {
return err
}
if config.opts.exporter != nil {
return config.opts.exporter.Write(config.io, project.DetailedItems())
}
return printResults(config, project.Items.Nodes, owner.Login)
}
func printResults(config listConfig, items []queries.ProjectItem, login string) error {
if len(items) == 0 {
return cmdutil.NewNoResultsError(fmt.Sprintf("Project %d for owner %s has no items", config.opts.number, login))
}
tp := tableprinter.New(config.io, tableprinter.WithHeader("Type", "Title", "Number", "Repository", "ID"))
for _, i := range items {
tp.AddField(i.Type())
tp.AddField(i.Title())
if i.Number() == 0 {
tp.AddField("")
} else {
tp.AddField(strconv.Itoa(i.Number()))
}
tp.AddField(i.Repo())
tp.AddField(i.ID(), tableprinter.WithTruncate(nil))
tp.EndRow()
}
return tp.Render()
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/item-list/item_list_test.go | pkg/cmd/project/item-list/item_list_test.go | package itemlist
import (
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/pkg/cmd/project/shared/queries"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"gopkg.in/h2non/gock.v1"
)
func TestNewCmdList(t *testing.T) {
tests := []struct {
name string
cli string
wants listOpts
wantsErr bool
wantsErrMsg string
wantsExporter bool
}{
{
name: "not-a-number",
cli: "x",
wantsErr: true,
wantsErrMsg: "invalid number: x",
},
{
name: "number",
cli: "123",
wants: listOpts{
number: 123,
limit: 30,
},
},
{
name: "owner",
cli: "--owner monalisa",
wants: listOpts{
owner: "monalisa",
limit: 30,
},
},
{
name: "json",
cli: "--format json",
wants: listOpts{
limit: 30,
},
wantsExporter: true,
},
}
t.Setenv("GH_TOKEN", "auth-token")
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
f := &cmdutil.Factory{
IOStreams: ios,
}
argv, err := shlex.Split(tt.cli)
assert.NoError(t, err)
var gotOpts listOpts
cmd := NewCmdList(f, func(config listConfig) error {
gotOpts = config.opts
return nil
})
cmd.SetArgs(argv)
_, err = cmd.ExecuteC()
if tt.wantsErr {
assert.Error(t, err)
assert.Equal(t, tt.wantsErrMsg, err.Error())
return
}
assert.NoError(t, err)
assert.Equal(t, tt.wants.number, gotOpts.number)
assert.Equal(t, tt.wants.owner, gotOpts.owner)
assert.Equal(t, tt.wantsExporter, gotOpts.exporter != nil)
assert.Equal(t, tt.wants.limit, gotOpts.limit)
})
}
}
func TestRunList_User_tty(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// get user ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "monalisa",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"organization"},
},
},
})
// list project items
gock.New("https://api.github.com").
Post("/graphql").
JSON(map[string]interface{}{
"query": "query UserProjectWithItems.*",
"variables": map[string]interface{}{
"firstItems": queries.LimitDefault,
"afterItems": nil,
"firstFields": queries.LimitMax,
"afterFields": nil,
"login": "monalisa",
"number": 1,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"projectV2": map[string]interface{}{
"items": map[string]interface{}{
"nodes": []map[string]interface{}{
{
"id": "issue ID",
"content": map[string]interface{}{
"__typename": "Issue",
"title": "an issue",
"number": 1,
"repository": map[string]string{
"nameWithOwner": "cli/go-gh",
},
},
},
{
"id": "pull request ID",
"content": map[string]interface{}{
"__typename": "PullRequest",
"title": "a pull request",
"number": 2,
"repository": map[string]string{
"nameWithOwner": "cli/go-gh",
},
},
},
{
"id": "draft issue ID",
"content": map[string]interface{}{
"id": "draft issue ID",
"title": "draft issue",
"__typename": "DraftIssue",
},
},
},
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(true)
config := listConfig{
opts: listOpts{
number: 1,
owner: "monalisa",
},
client: client,
io: ios,
}
err := runList(config)
assert.NoError(t, err)
assert.Equal(t, heredoc.Doc(`
TYPE TITLE NUMBER REPOSITORY ID
Issue an issue 1 cli/go-gh issue ID
PullRequest a pull request 2 cli/go-gh pull request ID
DraftIssue draft issue draft issue ID
`), stdout.String())
}
func TestRunList_User(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// get user ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "monalisa",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"organization"},
},
},
})
// list project items
gock.New("https://api.github.com").
Post("/graphql").
JSON(map[string]interface{}{
"query": "query UserProjectWithItems.*",
"variables": map[string]interface{}{
"firstItems": queries.LimitDefault,
"afterItems": nil,
"firstFields": queries.LimitMax,
"afterFields": nil,
"login": "monalisa",
"number": 1,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"projectV2": map[string]interface{}{
"items": map[string]interface{}{
"nodes": []map[string]interface{}{
{
"id": "issue ID",
"content": map[string]interface{}{
"__typename": "Issue",
"title": "an issue",
"number": 1,
"repository": map[string]string{
"nameWithOwner": "cli/go-gh",
},
},
},
{
"id": "pull request ID",
"content": map[string]interface{}{
"__typename": "PullRequest",
"title": "a pull request",
"number": 2,
"repository": map[string]string{
"nameWithOwner": "cli/go-gh",
},
},
},
{
"id": "draft issue ID",
"content": map[string]interface{}{
"id": "draft issue ID",
"title": "draft issue",
"__typename": "DraftIssue",
},
},
},
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
config := listConfig{
opts: listOpts{
number: 1,
owner: "monalisa",
},
client: client,
io: ios,
}
err := runList(config)
assert.NoError(t, err)
assert.Equal(
t,
"Issue\tan issue\t1\tcli/go-gh\tissue ID\nPullRequest\ta pull request\t2\tcli/go-gh\tpull request ID\nDraftIssue\tdraft issue\t\t\tdraft issue ID\n",
stdout.String())
}
func TestRunList_Org(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// get org ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "github",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"organization": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"user"},
},
},
})
// list project items
gock.New("https://api.github.com").
Post("/graphql").
JSON(map[string]interface{}{
"query": "query OrgProjectWithItems.*",
"variables": map[string]interface{}{
"firstItems": queries.LimitDefault,
"afterItems": nil,
"firstFields": queries.LimitMax,
"afterFields": nil,
"login": "github",
"number": 1,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"organization": map[string]interface{}{
"projectV2": map[string]interface{}{
"items": map[string]interface{}{
"nodes": []map[string]interface{}{
{
"id": "issue ID",
"content": map[string]interface{}{
"__typename": "Issue",
"title": "an issue",
"number": 1,
"repository": map[string]string{
"nameWithOwner": "cli/go-gh",
},
},
},
{
"id": "pull request ID",
"content": map[string]interface{}{
"__typename": "PullRequest",
"title": "a pull request",
"number": 2,
"repository": map[string]string{
"nameWithOwner": "cli/go-gh",
},
},
},
{
"id": "draft issue ID",
"content": map[string]interface{}{
"id": "draft issue ID",
"title": "draft issue",
"__typename": "DraftIssue",
},
},
},
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
config := listConfig{
opts: listOpts{
number: 1,
owner: "github",
},
client: client,
io: ios,
}
err := runList(config)
assert.NoError(t, err)
assert.Equal(
t,
"Issue\tan issue\t1\tcli/go-gh\tissue ID\nPullRequest\ta pull request\t2\tcli/go-gh\tpull request ID\nDraftIssue\tdraft issue\t\t\tdraft issue ID\n",
stdout.String())
}
func TestRunList_Me(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// get viewer ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query ViewerOwner.*",
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"id": "an ID",
},
},
})
// list project items
gock.New("https://api.github.com").
Post("/graphql").
JSON(map[string]interface{}{
"query": "query ViewerProjectWithItems.*",
"variables": map[string]interface{}{
"firstItems": queries.LimitDefault,
"afterItems": nil,
"firstFields": queries.LimitMax,
"afterFields": nil,
"number": 1,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"projectV2": map[string]interface{}{
"items": map[string]interface{}{
"nodes": []map[string]interface{}{
{
"id": "issue ID",
"content": map[string]interface{}{
"__typename": "Issue",
"title": "an issue",
"number": 1,
"repository": map[string]string{
"nameWithOwner": "cli/go-gh",
},
},
},
{
"id": "pull request ID",
"content": map[string]interface{}{
"__typename": "PullRequest",
"title": "a pull request",
"number": 2,
"repository": map[string]string{
"nameWithOwner": "cli/go-gh",
},
},
},
{
"id": "draft issue ID",
"content": map[string]interface{}{
"id": "draft issue ID",
"title": "draft issue",
"__typename": "DraftIssue",
},
},
},
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
config := listConfig{
opts: listOpts{
number: 1,
owner: "@me",
},
client: client,
io: ios,
}
err := runList(config)
assert.NoError(t, err)
assert.Equal(
t,
"Issue\tan issue\t1\tcli/go-gh\tissue ID\nPullRequest\ta pull request\t2\tcli/go-gh\tpull request ID\nDraftIssue\tdraft issue\t\t\tdraft issue ID\n",
stdout.String())
}
func TestRunList_JSON(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// get user ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "monalisa",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"organization"},
},
},
})
// list project items
gock.New("https://api.github.com").
Post("/graphql").
JSON(map[string]interface{}{
"query": "query UserProjectWithItems.*",
"variables": map[string]interface{}{
"firstItems": queries.LimitDefault,
"afterItems": nil,
"firstFields": queries.LimitMax,
"afterFields": nil,
"login": "monalisa",
"number": 1,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"projectV2": map[string]interface{}{
"items": map[string]interface{}{
"nodes": []map[string]interface{}{
{
"id": "issue ID",
"content": map[string]interface{}{
"__typename": "Issue",
"title": "an issue",
"number": 1,
"repository": map[string]string{
"nameWithOwner": "cli/go-gh",
},
},
},
{
"id": "pull request ID",
"content": map[string]interface{}{
"__typename": "PullRequest",
"title": "a pull request",
"number": 2,
"repository": map[string]string{
"nameWithOwner": "cli/go-gh",
},
},
},
{
"id": "draft issue ID",
"content": map[string]interface{}{
"id": "draft issue ID",
"title": "draft issue",
"__typename": "DraftIssue",
},
},
},
"totalCount": 3,
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
config := listConfig{
opts: listOpts{
number: 1,
owner: "monalisa",
exporter: cmdutil.NewJSONExporter(),
},
client: client,
io: ios,
}
err := runList(config)
assert.NoError(t, err)
assert.JSONEq(
t,
`{"items":[{"content":{"type":"Issue","body":"","title":"an issue","number":1,"repository":"cli/go-gh","url":""},"id":"issue ID"},{"content":{"type":"PullRequest","body":"","title":"a pull request","number":2,"repository":"cli/go-gh","url":""},"id":"pull request ID"},{"content":{"type":"DraftIssue","body":"","title":"draft issue","id":"draft issue ID"},"id":"draft issue ID"}],"totalCount":3}`,
stdout.String())
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/item-create/item_create_test.go | pkg/cmd/project/item-create/item_create_test.go | package itemcreate
import (
"testing"
"github.com/cli/cli/v2/pkg/cmd/project/shared/queries"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"gopkg.in/h2non/gock.v1"
)
func TestNewCmdCreateItem(t *testing.T) {
tests := []struct {
name string
cli string
wants createItemOpts
wantsErr bool
wantsErrMsg string
wantsExporter bool
}{
{
name: "missing-title",
cli: "",
wantsErr: true,
wantsErrMsg: "required flag(s) \"title\" not set",
},
{
name: "not-a-number",
cli: "x --title t",
wantsErr: true,
wantsErrMsg: "invalid number: x",
},
{
name: "title",
cli: "--title t",
wants: createItemOpts{
title: "t",
},
},
{
name: "number",
cli: "123 --title t",
wants: createItemOpts{
number: 123,
title: "t",
},
},
{
name: "owner",
cli: "--owner monalisa --title t",
wants: createItemOpts{
owner: "monalisa",
title: "t",
},
},
{
name: "body",
cli: "--body b --title t",
wants: createItemOpts{
body: "b",
title: "t",
},
},
{
name: "json",
cli: "--format json --title t",
wants: createItemOpts{
title: "t",
},
wantsExporter: true,
},
}
t.Setenv("GH_TOKEN", "auth-token")
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
f := &cmdutil.Factory{
IOStreams: ios,
}
argv, err := shlex.Split(tt.cli)
assert.NoError(t, err)
var gotOpts createItemOpts
cmd := NewCmdCreateItem(f, func(config createItemConfig) error {
gotOpts = config.opts
return nil
})
cmd.SetArgs(argv)
_, err = cmd.ExecuteC()
if tt.wantsErr {
assert.Error(t, err)
assert.Equal(t, tt.wantsErrMsg, err.Error())
return
}
assert.NoError(t, err)
assert.Equal(t, tt.wants.number, gotOpts.number)
assert.Equal(t, tt.wants.owner, gotOpts.owner)
assert.Equal(t, tt.wants.title, gotOpts.title)
assert.Equal(t, tt.wantsExporter, gotOpts.exporter != nil)
})
}
}
func TestRunCreateItem_Draft_User(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get user ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "monalisa",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"organization"},
},
},
})
// get project ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserProject.*",
"variables": map[string]interface{}{
"login": "monalisa",
"number": 1,
"firstItems": 0,
"afterItems": nil,
"firstFields": 0,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"projectV2": map[string]interface{}{
"id": "an ID",
},
},
},
})
// create item
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation CreateDraftItem.*","variables":{"input":{"projectId":"an ID","title":"a title","body":""}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"addProjectV2DraftIssue": map[string]interface{}{
"projectItem": map[string]interface{}{
"id": "item ID",
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(true)
config := createItemConfig{
opts: createItemOpts{
title: "a title",
owner: "monalisa",
number: 1,
},
client: client,
io: ios,
}
err := runCreateItem(config)
assert.NoError(t, err)
assert.Equal(
t,
"Created item\n",
stdout.String())
}
func TestRunCreateItem_Draft_Org(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get org ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "github",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"organization": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"user"},
},
},
})
// get project ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query OrgProject.*",
"variables": map[string]interface{}{
"login": "github",
"number": 1,
"firstItems": 0,
"afterItems": nil,
"firstFields": 0,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"organization": map[string]interface{}{
"projectV2": map[string]interface{}{
"id": "an ID",
},
},
},
})
// create item
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation CreateDraftItem.*","variables":{"input":{"projectId":"an ID","title":"a title","body":""}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"addProjectV2DraftIssue": map[string]interface{}{
"projectItem": map[string]interface{}{
"id": "item ID",
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(true)
config := createItemConfig{
opts: createItemOpts{
title: "a title",
owner: "github",
number: 1,
},
client: client,
io: ios,
}
err := runCreateItem(config)
assert.NoError(t, err)
assert.Equal(
t,
"Created item\n",
stdout.String())
}
func TestRunCreateItem_Draft_Me(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get viewer ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query ViewerOwner.*",
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"id": "an ID",
},
},
})
// get project ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query ViewerProject.*",
"variables": map[string]interface{}{
"number": 1,
"firstItems": 0,
"afterItems": nil,
"firstFields": 0,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"projectV2": map[string]interface{}{
"id": "an ID",
},
},
},
})
// create item
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation CreateDraftItem.*","variables":{"input":{"projectId":"an ID","title":"a title","body":"a body"}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"addProjectV2DraftIssue": map[string]interface{}{
"projectItem": map[string]interface{}{
"id": "item ID",
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(true)
config := createItemConfig{
opts: createItemOpts{
title: "a title",
owner: "@me",
number: 1,
body: "a body",
},
client: client,
io: ios,
}
err := runCreateItem(config)
assert.NoError(t, err)
assert.Equal(
t,
"Created item\n",
stdout.String())
}
func TestRunCreateItem_JSON(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get user ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "monalisa",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"organization"},
},
},
})
// get project ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserProject.*",
"variables": map[string]interface{}{
"login": "monalisa",
"number": 1,
"firstItems": 0,
"afterItems": nil,
"firstFields": 0,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"projectV2": map[string]interface{}{
"id": "an ID",
},
},
},
})
// create item
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation CreateDraftItem.*","variables":{"input":{"projectId":"an ID","title":"a title","body":""}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"addProjectV2DraftIssue": map[string]interface{}{
"projectItem": map[string]interface{}{
"id": "item ID",
"content": map[string]interface{}{
"__typename": "Draft",
"title": "a title",
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
config := createItemConfig{
opts: createItemOpts{
title: "a title",
owner: "monalisa",
number: 1,
exporter: cmdutil.NewJSONExporter(),
},
client: client,
io: ios,
}
err := runCreateItem(config)
assert.NoError(t, err)
assert.JSONEq(
t,
`{"id":"item ID","title":"","body":"","type":"Draft"}`,
stdout.String())
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/item-create/item_create.go | pkg/cmd/project/item-create/item_create.go | package itemcreate
import (
"fmt"
"strconv"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/pkg/cmd/project/shared/client"
"github.com/cli/cli/v2/pkg/cmd/project/shared/queries"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/shurcooL/githubv4"
"github.com/spf13/cobra"
)
type createItemOpts struct {
title string
body string
owner string
number int32
projectID string
exporter cmdutil.Exporter
}
type createItemConfig struct {
client *queries.Client
opts createItemOpts
io *iostreams.IOStreams
}
type createProjectDraftItemMutation struct {
CreateProjectDraftItem struct {
ProjectV2Item queries.ProjectItem `graphql:"projectItem"`
} `graphql:"addProjectV2DraftIssue(input:$input)"`
}
func NewCmdCreateItem(f *cmdutil.Factory, runF func(config createItemConfig) error) *cobra.Command {
opts := createItemOpts{}
createItemCmd := &cobra.Command{
Short: "Create a draft issue item in a project",
Use: "item-create [<number>]",
Example: heredoc.Doc(`
# Create a draft issue in the current user's project "1"
$ gh project item-create 1 --owner "@me" --title "new item" --body "new item body"
`),
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
client, err := client.New(f)
if err != nil {
return err
}
if len(args) == 1 {
num, err := strconv.ParseInt(args[0], 10, 32)
if err != nil {
return cmdutil.FlagErrorf("invalid number: %v", args[0])
}
opts.number = int32(num)
}
config := createItemConfig{
client: client,
opts: opts,
io: f.IOStreams,
}
// allow testing of the command without actually running it
if runF != nil {
return runF(config)
}
return runCreateItem(config)
},
}
createItemCmd.Flags().StringVar(&opts.owner, "owner", "", "Login of the owner. Use \"@me\" for the current user.")
createItemCmd.Flags().StringVar(&opts.title, "title", "", "Title for the draft issue")
createItemCmd.Flags().StringVar(&opts.body, "body", "", "Body for the draft issue")
cmdutil.AddFormatFlags(createItemCmd, &opts.exporter)
_ = createItemCmd.MarkFlagRequired("title")
return createItemCmd
}
func runCreateItem(config createItemConfig) error {
canPrompt := config.io.CanPrompt()
owner, err := config.client.NewOwner(canPrompt, config.opts.owner)
if err != nil {
return err
}
project, err := config.client.NewProject(canPrompt, owner, config.opts.number, false)
if err != nil {
return err
}
config.opts.projectID = project.ID
query, variables := createDraftIssueArgs(config)
err = config.client.Mutate("CreateDraftItem", query, variables)
if err != nil {
return err
}
if config.opts.exporter != nil {
return config.opts.exporter.Write(config.io, query.CreateProjectDraftItem.ProjectV2Item)
}
return printResults(config, query.CreateProjectDraftItem.ProjectV2Item)
}
func createDraftIssueArgs(config createItemConfig) (*createProjectDraftItemMutation, map[string]interface{}) {
return &createProjectDraftItemMutation{}, map[string]interface{}{
"input": githubv4.AddProjectV2DraftIssueInput{
Body: githubv4.NewString(githubv4.String(config.opts.body)),
ProjectID: githubv4.ID(config.opts.projectID),
Title: githubv4.String(config.opts.title),
},
}
}
func printResults(config createItemConfig, item queries.ProjectItem) error {
if !config.io.IsStdoutTTY() {
return nil
}
_, err := fmt.Fprintf(config.io.Out, "Created item\n")
return err
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/delete/delete.go | pkg/cmd/project/delete/delete.go | package delete
import (
"fmt"
"strconv"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/pkg/cmd/project/shared/client"
"github.com/cli/cli/v2/pkg/cmd/project/shared/queries"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/shurcooL/githubv4"
"github.com/spf13/cobra"
)
type deleteOpts struct {
owner string
number int32
projectID string
exporter cmdutil.Exporter
}
type deleteConfig struct {
client *queries.Client
opts deleteOpts
io *iostreams.IOStreams
}
type deleteProjectMutation struct {
DeleteProject struct {
Project queries.Project `graphql:"projectV2"`
} `graphql:"deleteProjectV2(input:$input)"`
}
func NewCmdDelete(f *cmdutil.Factory, runF func(config deleteConfig) error) *cobra.Command {
opts := deleteOpts{}
deleteCmd := &cobra.Command{
Short: "Delete a project",
Use: "delete [<number>]",
Example: heredoc.Doc(`
# Delete the current user's project "1"
$ gh project delete 1 --owner "@me"
`),
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
client, err := client.New(f)
if err != nil {
return err
}
if len(args) == 1 {
num, err := strconv.ParseInt(args[0], 10, 32)
if err != nil {
return cmdutil.FlagErrorf("invalid number: %v", args[0])
}
opts.number = int32(num)
}
config := deleteConfig{
client: client,
opts: opts,
io: f.IOStreams,
}
// allow testing of the command without actually running it
if runF != nil {
return runF(config)
}
return runDelete(config)
},
}
deleteCmd.Flags().StringVar(&opts.owner, "owner", "", "Login of the owner. Use \"@me\" for the current user.")
cmdutil.AddFormatFlags(deleteCmd, &opts.exporter)
return deleteCmd
}
func runDelete(config deleteConfig) error {
canPrompt := config.io.CanPrompt()
owner, err := config.client.NewOwner(canPrompt, config.opts.owner)
if err != nil {
return err
}
project, err := config.client.NewProject(canPrompt, owner, config.opts.number, false)
if err != nil {
return err
}
config.opts.projectID = project.ID
query, variables := deleteItemArgs(config)
err = config.client.Mutate("DeleteProject", query, variables)
if err != nil {
return err
}
if config.opts.exporter != nil {
return config.opts.exporter.Write(config.io, query.DeleteProject.Project)
}
return printResults(config, query.DeleteProject.Project)
}
func deleteItemArgs(config deleteConfig) (*deleteProjectMutation, map[string]interface{}) {
return &deleteProjectMutation{}, map[string]interface{}{
"input": githubv4.DeleteProjectV2Input{
ProjectID: githubv4.ID(config.opts.projectID),
},
"firstItems": githubv4.Int(0),
"afterItems": (*githubv4.String)(nil),
"firstFields": githubv4.Int(0),
"afterFields": (*githubv4.String)(nil),
}
}
func printResults(config deleteConfig, project queries.Project) error {
if !config.io.IsStdoutTTY() {
return nil
}
_, err := fmt.Fprintf(config.io.Out, "Deleted project %d\n", project.Number)
return err
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/delete/delete_test.go | pkg/cmd/project/delete/delete_test.go | package delete
import (
"testing"
"github.com/cli/cli/v2/pkg/cmd/project/shared/queries"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"gopkg.in/h2non/gock.v1"
)
func TestNewCmdDelete(t *testing.T) {
tests := []struct {
name string
cli string
wants deleteOpts
wantsErr bool
wantsErrMsg string
wantsExporter bool
}{
{
name: "not-a-number",
cli: "x",
wantsErr: true,
wantsErrMsg: "invalid number: x",
},
{
name: "number",
cli: "123",
wants: deleteOpts{
number: 123,
},
},
{
name: "owner",
cli: "--owner monalisa",
wants: deleteOpts{
owner: "monalisa",
},
},
{
name: "json",
cli: "--format json",
wantsExporter: true,
},
}
t.Setenv("GH_TOKEN", "auth-token")
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
f := &cmdutil.Factory{
IOStreams: ios,
}
argv, err := shlex.Split(tt.cli)
assert.NoError(t, err)
var gotOpts deleteOpts
cmd := NewCmdDelete(f, func(config deleteConfig) error {
gotOpts = config.opts
return nil
})
cmd.SetArgs(argv)
_, err = cmd.ExecuteC()
if tt.wantsErr {
assert.Error(t, err)
assert.Equal(t, tt.wantsErrMsg, err.Error())
return
}
assert.NoError(t, err)
assert.Equal(t, tt.wants.number, gotOpts.number)
assert.Equal(t, tt.wants.owner, gotOpts.owner)
assert.Equal(t, tt.wantsExporter, gotOpts.exporter != nil)
})
}
}
func TestRunDelete_User(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get user ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "monalisa",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"organization"},
},
},
})
// get project ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserProject.*",
"variables": map[string]interface{}{
"login": "monalisa",
"number": 1,
"firstItems": 0,
"afterItems": nil,
"firstFields": 0,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"projectV2": map[string]interface{}{
"id": "an ID",
},
},
},
})
// delete project
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation DeleteProject.*","variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"projectId":"an ID"}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"deleteProjectV2": map[string]interface{}{
"projectV2": map[string]interface{}{
"id": "project ID",
"number": 1,
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(true)
config := deleteConfig{
opts: deleteOpts{
owner: "monalisa",
number: 1,
},
client: client,
io: ios,
}
err := runDelete(config)
assert.NoError(t, err)
assert.Equal(
t,
"Deleted project 1\n",
stdout.String())
}
func TestRunDelete_Org(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get org ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "github",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"organization": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"user"},
},
},
})
// get project ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query OrgProject.*",
"variables": map[string]interface{}{
"login": "github",
"number": 1,
"firstItems": 0,
"afterItems": nil,
"firstFields": 0,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"organization": map[string]interface{}{
"projectV2": map[string]interface{}{
"id": "an ID",
},
},
},
})
// delete project
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation DeleteProject.*","variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"projectId":"an ID"}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"deleteProjectV2": map[string]interface{}{
"projectV2": map[string]interface{}{
"id": "project ID",
"number": 1,
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(true)
config := deleteConfig{
opts: deleteOpts{
owner: "github",
number: 1,
},
client: client,
io: ios,
}
err := runDelete(config)
assert.NoError(t, err)
assert.Equal(
t,
"Deleted project 1\n",
stdout.String())
}
func TestRunDelete_Me(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get viewer ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query ViewerOwner.*",
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"id": "an ID",
},
},
})
// get project ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query ViewerProject.*",
"variables": map[string]interface{}{
"number": 1,
"firstItems": 0,
"afterItems": nil,
"firstFields": 0,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"projectV2": map[string]interface{}{
"id": "an ID",
},
},
},
})
// delete project
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation DeleteProject.*","variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"projectId":"an ID"}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"deleteProjectV2": map[string]interface{}{
"projectV2": map[string]interface{}{
"id": "project ID",
"number": 1,
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(true)
config := deleteConfig{
opts: deleteOpts{
owner: "@me",
number: 1,
},
client: client,
io: ios,
}
err := runDelete(config)
assert.NoError(t, err)
assert.Equal(
t,
"Deleted project 1\n",
stdout.String())
}
func TestRunDelete_JSON(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get user ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "monalisa",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"organization"},
},
},
})
// get project ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserProject.*",
"variables": map[string]interface{}{
"login": "monalisa",
"number": 1,
"firstItems": 0,
"afterItems": nil,
"firstFields": 0,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"projectV2": map[string]interface{}{
"id": "an ID",
},
},
},
})
// delete project
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation DeleteProject.*","variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"projectId":"an ID"}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"deleteProjectV2": map[string]interface{}{
"projectV2": map[string]interface{}{
"id": "project ID",
"number": 1,
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
config := deleteConfig{
opts: deleteOpts{
owner: "monalisa",
number: 1,
exporter: cmdutil.NewJSONExporter(),
},
client: client,
io: ios,
}
err := runDelete(config)
assert.NoError(t, err)
assert.JSONEq(
t,
`{"number":1,"url":"","shortDescription":"","public":false,"closed":false,"title":"","id":"project ID","readme":"","items":{"totalCount":0},"fields":{"totalCount":0},"owner":{"type":"","login":""}}`,
stdout.String())
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/item-archive/item_archive.go | pkg/cmd/project/item-archive/item_archive.go | package itemarchive
import (
"fmt"
"strconv"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/pkg/cmd/project/shared/client"
"github.com/cli/cli/v2/pkg/cmd/project/shared/queries"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/shurcooL/githubv4"
"github.com/spf13/cobra"
)
type archiveItemOpts struct {
owner string
number int32
undo bool
itemID string
projectID string
exporter cmdutil.Exporter
}
type archiveItemConfig struct {
client *queries.Client
opts archiveItemOpts
io *iostreams.IOStreams
}
type archiveProjectItemMutation struct {
ArchiveProjectItem struct {
ProjectV2Item queries.ProjectItem `graphql:"item"`
} `graphql:"archiveProjectV2Item(input:$input)"`
}
type unarchiveProjectItemMutation struct {
UnarchiveProjectItem struct {
ProjectV2Item queries.ProjectItem `graphql:"item"`
} `graphql:"unarchiveProjectV2Item(input:$input)"`
}
func NewCmdArchiveItem(f *cmdutil.Factory, runF func(config archiveItemConfig) error) *cobra.Command {
opts := archiveItemOpts{}
archiveItemCmd := &cobra.Command{
Short: "Archive an item in a project",
Use: "item-archive [<number>]",
Example: heredoc.Doc(`
# Archive an item in the current user's project "1"
$ gh project item-archive 1 --owner "@me" --id <item-ID>
`),
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
client, err := client.New(f)
if err != nil {
return err
}
if len(args) == 1 {
num, err := strconv.ParseInt(args[0], 10, 32)
if err != nil {
return cmdutil.FlagErrorf("invalid number: %v", args[0])
}
opts.number = int32(num)
}
config := archiveItemConfig{
client: client,
opts: opts,
io: f.IOStreams,
}
// allow testing of the command without actually running it
if runF != nil {
return runF(config)
}
return runArchiveItem(config)
},
}
archiveItemCmd.Flags().StringVar(&opts.owner, "owner", "", "Login of the owner. Use \"@me\" for the current user.")
archiveItemCmd.Flags().StringVar(&opts.itemID, "id", "", "ID of the item to archive")
archiveItemCmd.Flags().BoolVar(&opts.undo, "undo", false, "Unarchive an item")
cmdutil.AddFormatFlags(archiveItemCmd, &opts.exporter)
_ = archiveItemCmd.MarkFlagRequired("id")
return archiveItemCmd
}
func runArchiveItem(config archiveItemConfig) error {
canPrompt := config.io.CanPrompt()
owner, err := config.client.NewOwner(canPrompt, config.opts.owner)
if err != nil {
return err
}
project, err := config.client.NewProject(canPrompt, owner, config.opts.number, false)
if err != nil {
return err
}
config.opts.projectID = project.ID
if config.opts.undo {
query, variables := unarchiveItemArgs(config, config.opts.itemID)
err = config.client.Mutate("UnarchiveProjectItem", query, variables)
if err != nil {
return err
}
if config.opts.exporter != nil {
return config.opts.exporter.Write(config.io, query.UnarchiveProjectItem.ProjectV2Item)
}
return printResults(config, query.UnarchiveProjectItem.ProjectV2Item)
}
query, variables := archiveItemArgs(config)
err = config.client.Mutate("ArchiveProjectItem", query, variables)
if err != nil {
return err
}
if config.opts.exporter != nil {
return config.opts.exporter.Write(config.io, query.ArchiveProjectItem.ProjectV2Item)
}
return printResults(config, query.ArchiveProjectItem.ProjectV2Item)
}
func archiveItemArgs(config archiveItemConfig) (*archiveProjectItemMutation, map[string]interface{}) {
return &archiveProjectItemMutation{}, map[string]interface{}{
"input": githubv4.ArchiveProjectV2ItemInput{
ProjectID: githubv4.ID(config.opts.projectID),
ItemID: githubv4.ID(config.opts.itemID),
},
}
}
func unarchiveItemArgs(config archiveItemConfig, itemID string) (*unarchiveProjectItemMutation, map[string]interface{}) {
return &unarchiveProjectItemMutation{}, map[string]interface{}{
"input": githubv4.UnarchiveProjectV2ItemInput{
ProjectID: githubv4.ID(config.opts.projectID),
ItemID: githubv4.ID(itemID),
},
}
}
func printResults(config archiveItemConfig, item queries.ProjectItem) error {
if !config.io.IsStdoutTTY() {
return nil
}
if config.opts.undo {
_, err := fmt.Fprintf(config.io.Out, "Unarchived item\n")
return err
}
_, err := fmt.Fprintf(config.io.Out, "Archived item\n")
return err
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/item-archive/item_archive_test.go | pkg/cmd/project/item-archive/item_archive_test.go | package itemarchive
import (
"testing"
"github.com/cli/cli/v2/pkg/cmd/project/shared/queries"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"gopkg.in/h2non/gock.v1"
)
func TestNewCmdarchiveItem(t *testing.T) {
tests := []struct {
name string
cli string
wants archiveItemOpts
wantsErr bool
wantsErrMsg string
wantsExporter bool
}{
{
name: "missing-id",
cli: "",
wantsErr: true,
wantsErrMsg: "required flag(s) \"id\" not set",
},
{
name: "not-a-number",
cli: "x --id 123",
wantsErr: true,
wantsErrMsg: "invalid number: x",
},
{
name: "id",
cli: "--id 123",
wants: archiveItemOpts{
itemID: "123",
},
},
{
name: "number",
cli: "456 --id 123",
wants: archiveItemOpts{
number: 456,
itemID: "123",
},
},
{
name: "owner",
cli: "--owner monalisa --id 123",
wants: archiveItemOpts{
owner: "monalisa",
itemID: "123",
},
},
{
name: "undo",
cli: "--undo --id 123",
wants: archiveItemOpts{
undo: true,
itemID: "123",
},
},
{
name: "json",
cli: "--format json --id 123",
wants: archiveItemOpts{
itemID: "123",
},
wantsExporter: true,
},
}
t.Setenv("GH_TOKEN", "auth-token")
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
f := &cmdutil.Factory{
IOStreams: ios,
}
argv, err := shlex.Split(tt.cli)
assert.NoError(t, err)
var gotOpts archiveItemOpts
cmd := NewCmdArchiveItem(f, func(config archiveItemConfig) error {
gotOpts = config.opts
return nil
})
cmd.SetArgs(argv)
_, err = cmd.ExecuteC()
if tt.wantsErr {
assert.Error(t, err)
assert.Equal(t, tt.wantsErrMsg, err.Error())
return
}
assert.NoError(t, err)
assert.Equal(t, tt.wants.number, gotOpts.number)
assert.Equal(t, tt.wants.owner, gotOpts.owner)
assert.Equal(t, tt.wants.itemID, gotOpts.itemID)
assert.Equal(t, tt.wants.undo, gotOpts.undo)
assert.Equal(t, tt.wantsExporter, gotOpts.exporter != nil)
})
}
}
func TestRunArchive_User(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get user ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "monalisa",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"organization"},
},
},
})
// get project ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserProject.*",
"variables": map[string]interface{}{
"login": "monalisa",
"number": 1,
"firstItems": 0,
"afterItems": nil,
"firstFields": 0,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"projectV2": map[string]interface{}{
"id": "an ID",
},
},
},
})
// archive item
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation ArchiveProjectItem.*","variables":{"input":{"projectId":"an ID","itemId":"item ID"}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"archiveProjectV2Item": map[string]interface{}{
"item": map[string]interface{}{
"id": "item ID",
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(true)
config := archiveItemConfig{
opts: archiveItemOpts{
owner: "monalisa",
number: 1,
itemID: "item ID",
},
client: client,
io: ios,
}
err := runArchiveItem(config)
assert.NoError(t, err)
assert.Equal(
t,
"Archived item\n",
stdout.String())
}
func TestRunArchive_Org(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get org ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "github",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"organization": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"user"},
},
},
})
// get project ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query OrgProject.*",
"variables": map[string]interface{}{
"login": "github",
"number": 1,
"firstItems": 0,
"afterItems": nil,
"firstFields": 0,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"organization": map[string]interface{}{
"projectV2": map[string]interface{}{
"id": "an ID",
},
},
},
})
// archive item
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation ArchiveProjectItem.*","variables":{"input":{"projectId":"an ID","itemId":"item ID"}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"archiveProjectV2Item": map[string]interface{}{
"item": map[string]interface{}{
"id": "item ID",
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(true)
config := archiveItemConfig{
opts: archiveItemOpts{
owner: "github",
number: 1,
itemID: "item ID",
},
client: client,
io: ios,
}
err := runArchiveItem(config)
assert.NoError(t, err)
assert.Equal(
t,
"Archived item\n",
stdout.String())
}
func TestRunArchive_Me(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get viewer ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query ViewerOwner.*",
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"id": "an ID",
},
},
})
// get project ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query ViewerProject.*",
"variables": map[string]interface{}{
"number": 1,
"firstItems": 0,
"afterItems": nil,
"firstFields": 0,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"projectV2": map[string]interface{}{
"id": "an ID",
},
},
},
})
// archive item
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation ArchiveProjectItem.*","variables":{"input":{"projectId":"an ID","itemId":"item ID"}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"archiveProjectV2Item": map[string]interface{}{
"item": map[string]interface{}{
"id": "item ID",
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(true)
config := archiveItemConfig{
opts: archiveItemOpts{
owner: "@me",
number: 1,
itemID: "item ID",
},
client: client,
io: ios,
}
err := runArchiveItem(config)
assert.NoError(t, err)
assert.Equal(
t,
"Archived item\n",
stdout.String())
}
func TestRunArchive_User_Undo(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get user ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "monalisa",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"organization"},
},
},
})
// get project ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserProject.*",
"variables": map[string]interface{}{
"login": "monalisa",
"number": 1,
"firstItems": 0,
"afterItems": nil,
"firstFields": 0,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"projectV2": map[string]interface{}{
"id": "an ID",
},
},
},
})
// archive item
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation UnarchiveProjectItem.*","variables":{"input":{"projectId":"an ID","itemId":"item ID"}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"unarchiveProjectV2Item": map[string]interface{}{
"item": map[string]interface{}{
"id": "item ID",
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(true)
config := archiveItemConfig{
opts: archiveItemOpts{
owner: "monalisa",
number: 1,
itemID: "item ID",
undo: true,
},
client: client,
io: ios,
}
err := runArchiveItem(config)
assert.NoError(t, err)
assert.Equal(
t,
"Unarchived item\n",
stdout.String())
}
func TestRunArchive_Org_Undo(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get org ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "github",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"organization": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"user"},
},
},
})
// get project ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query OrgProject.*",
"variables": map[string]interface{}{
"login": "github",
"number": 1,
"firstItems": 0,
"afterItems": nil,
"firstFields": 0,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"organization": map[string]interface{}{
"projectV2": map[string]interface{}{
"id": "an ID",
},
},
},
})
// archive item
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation UnarchiveProjectItem.*","variables":{"input":{"projectId":"an ID","itemId":"item ID"}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"unarchiveProjectV2Item": map[string]interface{}{
"item": map[string]interface{}{
"id": "item ID",
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(true)
config := archiveItemConfig{
opts: archiveItemOpts{
owner: "github",
number: 1,
itemID: "item ID",
undo: true,
},
client: client,
io: ios,
}
err := runArchiveItem(config)
assert.NoError(t, err)
assert.Equal(
t,
"Unarchived item\n",
stdout.String())
}
func TestRunArchive_Me_Undo(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get viewer ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query ViewerOwner.*",
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"id": "an ID",
},
},
})
// get project ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query ViewerProject.*",
"variables": map[string]interface{}{
"number": 1,
"firstItems": 0,
"afterItems": nil,
"firstFields": 0,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"projectV2": map[string]interface{}{
"id": "an ID",
},
},
},
})
// archive item
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation UnarchiveProjectItem.*","variables":{"input":{"projectId":"an ID","itemId":"item ID"}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"unarchiveProjectV2Item": map[string]interface{}{
"item": map[string]interface{}{
"id": "item ID",
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(true)
config := archiveItemConfig{
opts: archiveItemOpts{
owner: "@me",
number: 1,
itemID: "item ID",
undo: true,
},
client: client,
io: ios,
}
err := runArchiveItem(config)
assert.NoError(t, err)
assert.Equal(
t,
"Unarchived item\n",
stdout.String())
}
func TestRunArchive_JSON(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get user ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "monalisa",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"organization"},
},
},
})
// get project ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserProject.*",
"variables": map[string]interface{}{
"login": "monalisa",
"number": 1,
"firstItems": 0,
"afterItems": nil,
"firstFields": 0,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"projectV2": map[string]interface{}{
"id": "an ID",
},
},
},
})
// archive item
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation ArchiveProjectItem.*","variables":{"input":{"projectId":"an ID","itemId":"item ID"}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"archiveProjectV2Item": map[string]interface{}{
"item": map[string]interface{}{
"id": "item ID",
"content": map[string]interface{}{
"__typename": "Issue",
"title": "a title",
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
config := archiveItemConfig{
opts: archiveItemOpts{
owner: "monalisa",
number: 1,
itemID: "item ID",
exporter: cmdutil.NewJSONExporter(),
},
client: client,
io: ios,
}
err := runArchiveItem(config)
assert.NoError(t, err)
assert.JSONEq(
t,
`{"id":"item ID","title":"a title","body":"","type":"Issue"}`,
stdout.String())
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/list/list_test.go | pkg/cmd/project/list/list_test.go | package list
import (
"bytes"
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/pkg/cmd/project/shared/queries"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"gopkg.in/h2non/gock.v1"
)
func TestNewCmdlist(t *testing.T) {
tests := []struct {
name string
cli string
wants listOpts
wantsErr bool
wantsErrMsg string
wantsExporter bool
}{
{
name: "owner",
cli: "--owner monalisa",
wants: listOpts{
owner: "monalisa",
limit: 30,
},
},
{
name: "closed",
cli: "--closed",
wants: listOpts{
closed: true,
limit: 30,
},
},
{
name: "web",
cli: "--web",
wants: listOpts{
web: true,
limit: 30,
},
},
{
name: "json",
cli: "--format json",
wants: listOpts{
limit: 30,
},
wantsExporter: true,
},
}
t.Setenv("GH_TOKEN", "auth-token")
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
f := &cmdutil.Factory{
IOStreams: ios,
}
argv, err := shlex.Split(tt.cli)
assert.NoError(t, err)
var gotOpts listOpts
cmd := NewCmdList(f, func(config listConfig) error {
gotOpts = config.opts
return nil
})
cmd.SetArgs(argv)
_, err = cmd.ExecuteC()
if tt.wantsErr {
assert.Error(t, err)
assert.Equal(t, tt.wantsErrMsg, err.Error())
return
}
assert.NoError(t, err)
assert.Equal(t, tt.wants.owner, gotOpts.owner)
assert.Equal(t, tt.wants.closed, gotOpts.closed)
assert.Equal(t, tt.wants.web, gotOpts.web)
assert.Equal(t, tt.wants.limit, gotOpts.limit)
assert.Equal(t, tt.wantsExporter, gotOpts.exporter != nil)
})
}
}
func TestRunListTTY(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get user ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "monalisa",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"organization"},
},
},
})
gock.New("https://api.github.com").
Post("/graphql").
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"login": "monalisa",
"projectsV2": map[string]interface{}{
"nodes": []interface{}{
map[string]interface{}{
"title": "Project 1",
"shortDescription": "Short description 1",
"url": "url1",
"closed": false,
"ID": "id-1",
"number": 1,
},
map[string]interface{}{
"title": "Project 2",
"shortDescription": "",
"url": "url2",
"closed": true,
"ID": "id-2",
"number": 2,
},
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(true)
config := listConfig{
opts: listOpts{
owner: "monalisa",
},
client: client,
io: ios,
}
err := runList(config)
assert.NoError(t, err)
assert.Equal(t, heredoc.Doc(`
NUMBER TITLE STATE ID
1 Project 1 open id-1
`), stdout.String())
}
func TestRunList(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get user ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "monalisa",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"organization"},
},
},
})
gock.New("https://api.github.com").
Post("/graphql").
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"login": "monalisa",
"projectsV2": map[string]interface{}{
"nodes": []interface{}{
map[string]interface{}{
"title": "Project 1",
"shortDescription": "Short description 1",
"url": "url1",
"closed": false,
"ID": "id-1",
"number": 1,
},
map[string]interface{}{
"title": "Project 2",
"shortDescription": "",
"url": "url2",
"closed": true,
"ID": "id-2",
"number": 2,
},
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
config := listConfig{
opts: listOpts{
owner: "monalisa",
},
client: client,
io: ios,
}
err := runList(config)
assert.NoError(t, err)
assert.Equal(
t,
"1\tProject 1\topen\tid-1\n",
stdout.String())
}
func TestRunList_tty(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get user ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "monalisa",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"organization"},
},
},
})
gock.New("https://api.github.com").
Post("/graphql").
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"login": "monalisa",
"projectsV2": map[string]interface{}{
"nodes": []interface{}{
map[string]interface{}{
"title": "Project 1",
"shortDescription": "Short description 1",
"url": "url1",
"closed": false,
"ID": "id-1",
"number": 1,
},
map[string]interface{}{
"title": "Project 2",
"shortDescription": "",
"url": "url2",
"closed": true,
"ID": "id-2",
"number": 2,
},
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(true)
config := listConfig{
opts: listOpts{
owner: "monalisa",
},
client: client,
io: ios,
}
err := runList(config)
assert.NoError(t, err)
assert.Equal(t, heredoc.Doc(`
NUMBER TITLE STATE ID
1 Project 1 open id-1
`),
stdout.String())
}
func TestRunList_Me(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get viewer ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query ViewerOwner.*",
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"id": "an ID",
},
},
})
gock.New("https://api.github.com").
Post("/graphql").
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"login": "monalisa",
"projectsV2": map[string]interface{}{
"nodes": []interface{}{
map[string]interface{}{
"title": "Project 1",
"shortDescription": "Short description 1",
"url": "url1",
"closed": false,
"ID": "id-1",
"number": 1,
},
map[string]interface{}{
"title": "Project 2",
"shortDescription": "",
"url": "url2",
"closed": true,
"ID": "id-2",
"number": 2,
},
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
config := listConfig{
opts: listOpts{
owner: "@me",
},
client: client,
io: ios,
}
err := runList(config)
assert.NoError(t, err)
assert.Equal(
t,
"1\tProject 1\topen\tid-1\n",
stdout.String())
}
func TestRunListViewer(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get viewer ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query ViewerOwner.*",
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"id": "an ID",
},
},
})
gock.New("https://api.github.com").
Post("/graphql").
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"login": "monalisa",
"projectsV2": map[string]interface{}{
"nodes": []interface{}{
map[string]interface{}{
"title": "Project 1",
"shortDescription": "Short description 1",
"url": "url1",
"closed": false,
"ID": "id-1",
"number": 1,
},
map[string]interface{}{
"title": "Project 2",
"shortDescription": "",
"url": "url2",
"closed": true,
"ID": "id-2",
"number": 2,
},
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
config := listConfig{
opts: listOpts{},
client: client,
io: ios,
}
err := runList(config)
assert.NoError(t, err)
assert.Equal(
t,
"1\tProject 1\topen\tid-1\n",
stdout.String())
}
func TestRunListOrg(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get org ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "github",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"organization": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"user"},
},
},
})
gock.New("https://api.github.com").
Post("/graphql").
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"organization": map[string]interface{}{
"login": "monalisa",
"projectsV2": map[string]interface{}{
"nodes": []interface{}{
map[string]interface{}{
"title": "Project 1",
"shortDescription": "Short description 1",
"url": "url1",
"closed": false,
"ID": "id-1",
"number": 1,
},
map[string]interface{}{
"title": "Project 2",
"shortDescription": "",
"url": "url2",
"closed": true,
"ID": "id-2",
"number": 2,
},
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
config := listConfig{
opts: listOpts{
owner: "github",
},
client: client,
io: ios,
}
err := runList(config)
assert.NoError(t, err)
assert.Equal(
t,
"1\tProject 1\topen\tid-1\n",
stdout.String())
}
func TestRunListEmpty(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get viewer ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query Viewer.*",
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"id": "an ID",
"login": "theviewer",
},
},
})
gock.New("https://api.github.com").
Post("/graphql").
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"login": "monalisa",
"projectsV2": map[string]interface{}{
"nodes": []interface{}{},
},
},
},
})
client := queries.NewTestClient()
ios, _, _, _ := iostreams.Test()
config := listConfig{
opts: listOpts{},
client: client,
io: ios,
}
err := runList(config)
assert.EqualError(
t,
err,
"No projects found for @me")
}
func TestRunListWithClosed(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get user ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "monalisa",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"organization"},
},
},
})
gock.New("https://api.github.com").
Post("/graphql").
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"login": "monalisa",
"projectsV2": map[string]interface{}{
"nodes": []interface{}{
map[string]interface{}{
"title": "Project 1",
"shortDescription": "Short description 1",
"url": "url1",
"closed": false,
"ID": "id-1",
"number": 1,
},
map[string]interface{}{
"title": "Project 2",
"shortDescription": "",
"url": "url2",
"closed": true,
"ID": "id-2",
"number": 2,
},
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
config := listConfig{
opts: listOpts{
owner: "monalisa",
closed: true,
},
client: client,
io: ios,
}
err := runList(config)
assert.NoError(t, err)
assert.Equal(
t,
"1\tProject 1\topen\tid-1\n2\tProject 2\tclosed\tid-2\n",
stdout.String())
}
func TestRunListWeb_User(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get user ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "monalisa",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"organization"},
},
},
})
client := queries.NewTestClient()
buf := bytes.Buffer{}
config := listConfig{
opts: listOpts{
owner: "monalisa",
web: true,
},
URLOpener: func(url string) error {
buf.WriteString(url)
return nil
},
client: client,
}
err := runList(config)
assert.NoError(t, err)
assert.Equal(t, "https://github.com/users/monalisa/projects", buf.String())
}
func TestRunListWeb_Org(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get org ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "github",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"organization": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"user"},
},
},
})
client := queries.NewTestClient()
buf := bytes.Buffer{}
config := listConfig{
opts: listOpts{
owner: "github",
web: true,
},
URLOpener: func(url string) error {
buf.WriteString(url)
return nil
},
client: client,
}
err := runList(config)
assert.NoError(t, err)
assert.Equal(t, "https://github.com/orgs/github/projects", buf.String())
}
func TestRunListWeb_Me(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get viewer ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query Viewer.*",
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"id": "an ID",
"login": "theviewer",
},
},
})
client := queries.NewTestClient()
buf := bytes.Buffer{}
config := listConfig{
opts: listOpts{
owner: "@me",
web: true,
},
URLOpener: func(url string) error {
buf.WriteString(url)
return nil
},
client: client,
}
err := runList(config)
assert.NoError(t, err)
assert.Equal(t, "https://github.com/users/theviewer/projects", buf.String())
}
func TestRunListWeb_Empty(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get viewer ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query Viewer.*",
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"id": "an ID",
"login": "theviewer",
},
},
})
client := queries.NewTestClient()
buf := bytes.Buffer{}
config := listConfig{
opts: listOpts{
web: true,
},
URLOpener: func(url string) error {
buf.WriteString(url)
return nil
},
client: client,
}
err := runList(config)
assert.NoError(t, err)
assert.Equal(t, "https://github.com/users/theviewer/projects", buf.String())
}
func TestRunListWeb_Closed(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get viewer ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query Viewer.*",
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"id": "an ID",
"login": "theviewer",
},
},
})
client := queries.NewTestClient()
buf := bytes.Buffer{}
config := listConfig{
opts: listOpts{
web: true,
closed: true,
},
URLOpener: func(url string) error {
buf.WriteString(url)
return nil
},
client: client,
}
err := runList(config)
assert.NoError(t, err)
assert.Equal(t, "https://github.com/users/theviewer/projects?query=is%3Aclosed", buf.String())
}
func TestRunList_JSON(t *testing.T) {
defer gock.Off()
gock.Observe(gock.DumpRequest)
// get user ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "monalisa",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"organization"},
},
},
})
gock.New("https://api.github.com").
Post("/graphql").
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"login": "monalisa",
"projectsV2": map[string]interface{}{
"nodes": []interface{}{
map[string]interface{}{
"title": "Project 1",
"shortDescription": "Short description 1",
"url": "url1",
"closed": false,
"ID": "id-1",
"number": 1,
},
map[string]interface{}{
"title": "Project 2",
"shortDescription": "",
"url": "url2",
"closed": true,
"ID": "id-2",
"number": 2,
},
},
"totalCount": 2,
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
config := listConfig{
opts: listOpts{
owner: "monalisa",
exporter: cmdutil.NewJSONExporter(),
},
client: client,
io: ios,
}
err := runList(config)
assert.NoError(t, err)
assert.JSONEq(
t,
`{"projects":[{"number":1,"url":"url1","shortDescription":"Short description 1","public":false,"closed":false,"title":"Project 1","id":"id-1","readme":"","items":{"totalCount":0},"fields":{"totalCount":0},"owner":{"type":"","login":""}}],"totalCount":2}`,
stdout.String())
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/list/list.go | pkg/cmd/project/list/list.go | package list
import (
"fmt"
"strconv"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/tableprinter"
"github.com/cli/cli/v2/pkg/cmd/project/shared/client"
"github.com/cli/cli/v2/pkg/cmd/project/shared/format"
"github.com/cli/cli/v2/pkg/cmd/project/shared/queries"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type listOpts struct {
limit int
web bool
owner string
closed bool
exporter cmdutil.Exporter
}
type listConfig struct {
client *queries.Client
opts listOpts
URLOpener func(string) error
io *iostreams.IOStreams
}
func NewCmdList(f *cmdutil.Factory, runF func(config listConfig) error) *cobra.Command {
opts := listOpts{}
listCmd := &cobra.Command{
Use: "list",
Short: "List the projects for an owner",
Example: heredoc.Doc(`
# List the current user's projects
$ gh project list
# List the projects for org github including closed projects
$ gh project list --owner github --closed
`),
Aliases: []string{"ls"},
RunE: func(cmd *cobra.Command, args []string) error {
client, err := client.New(f)
if err != nil {
return err
}
URLOpener := func(url string) error {
return f.Browser.Browse(url)
}
config := listConfig{
client: client,
opts: opts,
URLOpener: URLOpener,
io: f.IOStreams,
}
// allow testing of the command without actually running it
if runF != nil {
return runF(config)
}
return runList(config)
},
}
listCmd.Flags().StringVar(&opts.owner, "owner", "", "Login of the owner")
listCmd.Flags().BoolVarP(&opts.closed, "closed", "", false, "Include closed projects")
listCmd.Flags().BoolVarP(&opts.web, "web", "w", false, "Open projects list in the browser")
cmdutil.AddFormatFlags(listCmd, &opts.exporter)
listCmd.Flags().IntVarP(&opts.limit, "limit", "L", queries.LimitDefault, "Maximum number of projects to fetch")
return listCmd
}
func runList(config listConfig) error {
if config.opts.web {
url, err := buildURL(config)
if err != nil {
return err
}
if err := config.URLOpener(url); err != nil {
return err
}
return nil
}
if config.opts.owner == "" {
config.opts.owner = "@me"
}
canPrompt := config.io.CanPrompt()
owner, err := config.client.NewOwner(canPrompt, config.opts.owner)
if err != nil {
return err
}
projects, err := config.client.Projects(config.opts.owner, owner.Type, config.opts.limit, false)
if err != nil {
return err
}
projects = filterProjects(projects, config)
if config.opts.exporter != nil {
return config.opts.exporter.Write(config.io, projects)
}
return printResults(config, projects, owner.Login)
}
// TODO: support non-github.com hostnames
func buildURL(config listConfig) (string, error) {
var url string
if config.opts.owner == "@me" || config.opts.owner == "" {
owner, err := config.client.ViewerLoginName()
if err != nil {
return "", err
}
url = fmt.Sprintf("https://github.com/users/%s/projects", owner)
} else {
_, ownerType, err := config.client.OwnerIDAndType(config.opts.owner)
if err != nil {
return "", err
}
if ownerType == queries.UserOwner {
url = fmt.Sprintf("https://github.com/users/%s/projects", config.opts.owner)
} else {
url = fmt.Sprintf("https://github.com/orgs/%s/projects", config.opts.owner)
}
}
if config.opts.closed {
return url + "?query=is%3Aclosed", nil
}
return url, nil
}
func filterProjects(nodes queries.Projects, config listConfig) queries.Projects {
filtered := queries.Projects{
Nodes: make([]queries.Project, 0, len(nodes.Nodes)),
TotalCount: nodes.TotalCount,
}
for _, project := range nodes.Nodes {
if !config.opts.closed && project.Closed {
continue
}
filtered.Nodes = append(filtered.Nodes, project)
}
return filtered
}
func printResults(config listConfig, projects queries.Projects, owner string) error {
if len(projects.Nodes) == 0 {
return cmdutil.NewNoResultsError(fmt.Sprintf("No projects found for %s", owner))
}
tp := tableprinter.New(config.io, tableprinter.WithHeader("Number", "Title", "State", "ID"))
cs := config.io.ColorScheme()
for _, p := range projects.Nodes {
tp.AddField(
strconv.Itoa(int(p.Number)),
tableprinter.WithTruncate(nil),
)
tp.AddField(p.Title)
tp.AddField(
format.ProjectState(p),
tableprinter.WithColor(cs.ColorFromString(format.ColorForProjectState(p))),
)
tp.AddField(p.ID, tableprinter.WithTruncate(nil))
tp.EndRow()
}
return tp.Render()
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/field-list/field_list.go | pkg/cmd/project/field-list/field_list.go | package fieldlist
import (
"fmt"
"strconv"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/tableprinter"
"github.com/cli/cli/v2/pkg/cmd/project/shared/client"
"github.com/cli/cli/v2/pkg/cmd/project/shared/queries"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type listOpts struct {
limit int
owner string
number int32
exporter cmdutil.Exporter
}
type listConfig struct {
io *iostreams.IOStreams
client *queries.Client
opts listOpts
}
func NewCmdList(f *cmdutil.Factory, runF func(config listConfig) error) *cobra.Command {
opts := listOpts{}
listCmd := &cobra.Command{
Short: "List the fields in a project",
Use: "field-list [<number>]",
Example: heredoc.Doc(`
# List fields in the current user's project "1"
$ gh project field-list 1 --owner "@me"
`),
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
client, err := client.New(f)
if err != nil {
return err
}
if len(args) == 1 {
num, err := strconv.ParseInt(args[0], 10, 32)
if err != nil {
return cmdutil.FlagErrorf("invalid number: %v", args[0])
}
opts.number = int32(num)
}
config := listConfig{
io: f.IOStreams,
client: client,
opts: opts,
}
// allow testing of the command without actually running it
if runF != nil {
return runF(config)
}
return runList(config)
},
}
listCmd.Flags().StringVar(&opts.owner, "owner", "", "Login of the owner. Use \"@me\" for the current user.")
cmdutil.AddFormatFlags(listCmd, &opts.exporter)
listCmd.Flags().IntVarP(&opts.limit, "limit", "L", queries.LimitDefault, "Maximum number of fields to fetch")
return listCmd
}
func runList(config listConfig) error {
canPrompt := config.io.CanPrompt()
owner, err := config.client.NewOwner(canPrompt, config.opts.owner)
if err != nil {
return err
}
// no need to fetch the project if we already have the number
if config.opts.number == 0 {
canPrompt := config.io.CanPrompt()
project, err := config.client.NewProject(canPrompt, owner, config.opts.number, false)
if err != nil {
return err
}
config.opts.number = project.Number
}
project, err := config.client.ProjectFields(owner, config.opts.number, config.opts.limit)
if err != nil {
return err
}
if config.opts.exporter != nil {
return config.opts.exporter.Write(config.io, project.Fields)
}
return printResults(config, project.Fields.Nodes, owner.Login)
}
func printResults(config listConfig, fields []queries.ProjectField, login string) error {
if len(fields) == 0 {
return cmdutil.NewNoResultsError(fmt.Sprintf("Project %d for owner %s has no fields", config.opts.number, login))
}
tp := tableprinter.New(config.io, tableprinter.WithHeader("Name", "Data type", "ID"))
for _, f := range fields {
tp.AddField(f.Name())
tp.AddField(f.Type())
tp.AddField(f.ID(), tableprinter.WithTruncate(nil))
tp.EndRow()
}
return tp.Render()
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/field-list/field_list_test.go | pkg/cmd/project/field-list/field_list_test.go | package fieldlist
import (
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/pkg/cmd/project/shared/queries"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"gopkg.in/h2non/gock.v1"
)
func TestNewCmdList(t *testing.T) {
tests := []struct {
name string
cli string
wants listOpts
wantsErr bool
wantsErrMsg string
wantsExporter bool
}{
{
name: "not-a-number",
cli: "x",
wantsErr: true,
wantsErrMsg: "invalid number: x",
},
{
name: "number",
cli: "123",
wants: listOpts{
number: 123,
limit: 30,
},
},
{
name: "owner",
cli: "--owner monalisa",
wants: listOpts{
owner: "monalisa",
limit: 30,
},
},
{
name: "json",
cli: "--format json",
wants: listOpts{
limit: 30,
},
wantsExporter: true,
},
}
t.Setenv("GH_TOKEN", "auth-token")
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
f := &cmdutil.Factory{
IOStreams: ios,
}
argv, err := shlex.Split(tt.cli)
assert.NoError(t, err)
var gotOpts listOpts
cmd := NewCmdList(f, func(config listConfig) error {
gotOpts = config.opts
return nil
})
cmd.SetArgs(argv)
_, err = cmd.ExecuteC()
if tt.wantsErr {
assert.Equal(t, tt.wantsErrMsg, err.Error())
assert.Error(t, err)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.wants.number, gotOpts.number)
assert.Equal(t, tt.wants.owner, gotOpts.owner)
assert.Equal(t, tt.wants.limit, gotOpts.limit)
assert.Equal(t, tt.wantsExporter, gotOpts.exporter != nil)
})
}
}
func TestRunList_User_tty(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// get user ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "monalisa",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"organization"},
},
},
})
// list project fields
gock.New("https://api.github.com").
Post("/graphql").
JSON(map[string]interface{}{
"query": "query UserProject.*",
"variables": map[string]interface{}{
"login": "monalisa",
"number": 1,
"firstItems": queries.LimitMax,
"afterItems": nil,
"firstFields": queries.LimitDefault,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"projectV2": map[string]interface{}{
"fields": map[string]interface{}{
"nodes": []map[string]interface{}{
{
"__typename": "ProjectV2Field",
"name": "FieldTitle",
"id": "field ID",
},
{
"__typename": "ProjectV2SingleSelectField",
"name": "Status",
"id": "status ID",
},
{
"__typename": "ProjectV2IterationField",
"name": "Iterations",
"id": "iteration ID",
},
},
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(true)
config := listConfig{
opts: listOpts{
number: 1,
owner: "monalisa",
},
client: client,
io: ios,
}
err := runList(config)
assert.NoError(t, err)
assert.Equal(t, heredoc.Doc(`
NAME DATA TYPE ID
FieldTitle ProjectV2Field field ID
Status ProjectV2SingleSelectField status ID
Iterations ProjectV2IterationField iteration ID
`), stdout.String())
}
func TestRunList_User(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// get user ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "monalisa",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"organization"},
},
},
})
// list project fields
gock.New("https://api.github.com").
Post("/graphql").
JSON(map[string]interface{}{
"query": "query UserProject.*",
"variables": map[string]interface{}{
"login": "monalisa",
"number": 1,
"firstItems": queries.LimitMax,
"afterItems": nil,
"firstFields": queries.LimitDefault,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"projectV2": map[string]interface{}{
"fields": map[string]interface{}{
"nodes": []map[string]interface{}{
{
"__typename": "ProjectV2Field",
"name": "FieldTitle",
"id": "field ID",
},
{
"__typename": "ProjectV2SingleSelectField",
"name": "Status",
"id": "status ID",
},
{
"__typename": "ProjectV2IterationField",
"name": "Iterations",
"id": "iteration ID",
},
},
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
config := listConfig{
opts: listOpts{
number: 1,
owner: "monalisa",
},
client: client,
io: ios,
}
err := runList(config)
assert.NoError(t, err)
assert.Equal(
t,
"FieldTitle\tProjectV2Field\tfield ID\nStatus\tProjectV2SingleSelectField\tstatus ID\nIterations\tProjectV2IterationField\titeration ID\n",
stdout.String())
}
func TestRunList_Org(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// get org ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "github",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"organization": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"user"},
},
},
})
// list project fields
gock.New("https://api.github.com").
Post("/graphql").
JSON(map[string]interface{}{
"query": "query OrgProject.*",
"variables": map[string]interface{}{
"login": "github",
"number": 1,
"firstItems": queries.LimitMax,
"afterItems": nil,
"firstFields": queries.LimitDefault,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"organization": map[string]interface{}{
"projectV2": map[string]interface{}{
"fields": map[string]interface{}{
"nodes": []map[string]interface{}{
{
"__typename": "ProjectV2Field",
"name": "FieldTitle",
"id": "field ID",
},
{
"__typename": "ProjectV2SingleSelectField",
"name": "Status",
"id": "status ID",
},
{
"__typename": "ProjectV2IterationField",
"name": "Iterations",
"id": "iteration ID",
},
},
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
config := listConfig{
opts: listOpts{
number: 1,
owner: "github",
},
client: client,
io: ios,
}
err := runList(config)
assert.NoError(t, err)
assert.Equal(
t,
"FieldTitle\tProjectV2Field\tfield ID\nStatus\tProjectV2SingleSelectField\tstatus ID\nIterations\tProjectV2IterationField\titeration ID\n",
stdout.String())
}
func TestRunList_Me(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// get viewer ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query ViewerOwner.*",
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"id": "an ID",
},
},
})
// list project fields
gock.New("https://api.github.com").
Post("/graphql").
JSON(map[string]interface{}{
"query": "query ViewerProject.*",
"variables": map[string]interface{}{
"number": 1,
"firstItems": queries.LimitMax,
"afterItems": nil,
"firstFields": queries.LimitDefault,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"projectV2": map[string]interface{}{
"fields": map[string]interface{}{
"nodes": []map[string]interface{}{
{
"__typename": "ProjectV2Field",
"name": "FieldTitle",
"id": "field ID",
},
{
"__typename": "ProjectV2SingleSelectField",
"name": "Status",
"id": "status ID",
},
{
"__typename": "ProjectV2IterationField",
"name": "Iterations",
"id": "iteration ID",
},
},
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
config := listConfig{
opts: listOpts{
number: 1,
owner: "@me",
},
client: client,
io: ios,
}
err := runList(config)
assert.NoError(t, err)
assert.Equal(
t,
"FieldTitle\tProjectV2Field\tfield ID\nStatus\tProjectV2SingleSelectField\tstatus ID\nIterations\tProjectV2IterationField\titeration ID\n",
stdout.String())
}
func TestRunList_Empty(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// get viewer ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query ViewerOwner.*",
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"id": "an ID",
},
},
})
// list project fields
gock.New("https://api.github.com").
Post("/graphql").
JSON(map[string]interface{}{
"query": "query ViewerProject.*",
"variables": map[string]interface{}{
"number": 1,
"firstItems": queries.LimitMax,
"afterItems": nil,
"firstFields": queries.LimitDefault,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"projectV2": map[string]interface{}{
"fields": map[string]interface{}{
"nodes": nil,
},
},
},
},
})
client := queries.NewTestClient()
ios, _, _, _ := iostreams.Test()
config := listConfig{
opts: listOpts{
number: 1,
owner: "@me",
},
client: client,
io: ios,
}
err := runList(config)
assert.EqualError(
t,
err,
"Project 1 for owner @me has no fields")
}
func TestRunList_JSON(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// get user ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "monalisa",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"organization"},
},
},
})
// list project fields
gock.New("https://api.github.com").
Post("/graphql").
JSON(map[string]interface{}{
"query": "query UserProject.*",
"variables": map[string]interface{}{
"login": "monalisa",
"number": 1,
"firstItems": queries.LimitMax,
"afterItems": nil,
"firstFields": queries.LimitDefault,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"projectV2": map[string]interface{}{
"fields": map[string]interface{}{
"nodes": []map[string]interface{}{
{
"__typename": "ProjectV2Field",
"name": "FieldTitle",
"id": "field ID",
},
{
"__typename": "ProjectV2SingleSelectField",
"name": "Status",
"id": "status ID",
},
{
"__typename": "ProjectV2IterationField",
"name": "Iterations",
"id": "iteration ID",
},
},
"totalCount": 3,
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
config := listConfig{
opts: listOpts{
number: 1,
owner: "monalisa",
exporter: cmdutil.NewJSONExporter(),
},
client: client,
io: ios,
}
err := runList(config)
assert.NoError(t, err)
assert.JSONEq(
t,
`{"fields":[{"id":"field ID","name":"FieldTitle","type":"ProjectV2Field"},{"id":"status ID","name":"Status","type":"ProjectV2SingleSelectField"},{"id":"iteration ID","name":"Iterations","type":"ProjectV2IterationField"}],"totalCount":3}`,
stdout.String())
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/item-edit/item_edit.go | pkg/cmd/project/item-edit/item_edit.go | package itemedit
import (
"fmt"
"strings"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/pkg/cmd/project/shared/client"
"github.com/cli/cli/v2/pkg/cmd/project/shared/queries"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/shurcooL/githubv4"
"github.com/spf13/cobra"
)
type editItemOpts struct {
// updateDraftIssue
title string
body string
itemID string
// updateItem
fieldID string
projectID string
text string
number float64
numberChanged bool
date string
singleSelectOptionID string
iterationID string
clear bool
// format
exporter cmdutil.Exporter
}
type editItemConfig struct {
io *iostreams.IOStreams
client *queries.Client
opts editItemOpts
}
type EditProjectDraftIssue struct {
UpdateProjectV2DraftIssue struct {
DraftIssue queries.DraftIssue `graphql:"draftIssue"`
} `graphql:"updateProjectV2DraftIssue(input:$input)"`
}
type UpdateProjectV2FieldValue struct {
Update struct {
Item queries.ProjectItem `graphql:"projectV2Item"`
} `graphql:"updateProjectV2ItemFieldValue(input:$input)"`
}
type ClearProjectV2FieldValue struct {
Clear struct {
Item queries.ProjectItem `graphql:"projectV2Item"`
} `graphql:"clearProjectV2ItemFieldValue(input:$input)"`
}
func NewCmdEditItem(f *cmdutil.Factory, runF func(config editItemConfig) error) *cobra.Command {
opts := editItemOpts{}
editItemCmd := &cobra.Command{
Use: "item-edit",
Short: "Edit an item in a project",
Long: heredoc.Docf(`
Edit either a draft issue or a project item. Both usages require the ID of the item to edit.
For non-draft issues, the ID of the project is also required, and only a single field value can be updated per invocation.
Remove project item field value using %[1]s--clear%[1]s flag.
`, "`"),
Example: heredoc.Doc(`
# Edit an item's text field value
$ gh project item-edit --id <item-id> --field-id <field-id> --project-id <project-id> --text "new text"
# Clear an item's field value
$ gh project item-edit --id <item-id> --field-id <field-id> --project-id <project-id> --clear
`),
RunE: func(cmd *cobra.Command, args []string) error {
opts.numberChanged = cmd.Flags().Changed("number")
if err := cmdutil.MutuallyExclusive(
"only one of `--text`, `--number`, `--date`, `--single-select-option-id` or `--iteration-id` may be used",
opts.text != "",
opts.numberChanged,
opts.date != "",
opts.singleSelectOptionID != "",
opts.iterationID != "",
); err != nil {
return err
}
if err := cmdutil.MutuallyExclusive(
"cannot use `--text`, `--number`, `--date`, `--single-select-option-id` or `--iteration-id` in conjunction with `--clear`",
opts.text != "" || opts.numberChanged || opts.date != "" || opts.singleSelectOptionID != "" || opts.iterationID != "",
opts.clear,
); err != nil {
return err
}
client, err := client.New(f)
if err != nil {
return err
}
config := editItemConfig{
io: f.IOStreams,
client: client,
opts: opts,
}
// allow testing of the command without actually running it
if runF != nil {
return runF(config)
}
return runEditItem(config)
},
}
editItemCmd.Flags().StringVar(&opts.itemID, "id", "", "ID of the item to edit")
cmdutil.AddFormatFlags(editItemCmd, &opts.exporter)
editItemCmd.Flags().StringVar(&opts.title, "title", "", "Title of the draft issue item")
editItemCmd.Flags().StringVar(&opts.body, "body", "", "Body of the draft issue item")
editItemCmd.Flags().StringVar(&opts.fieldID, "field-id", "", "ID of the field to update")
editItemCmd.Flags().StringVar(&opts.projectID, "project-id", "", "ID of the project to which the field belongs to")
editItemCmd.Flags().StringVar(&opts.text, "text", "", "Text value for the field")
editItemCmd.Flags().Float64Var(&opts.number, "number", 0, "Number value for the field")
editItemCmd.Flags().StringVar(&opts.date, "date", "", "Date value for the field (YYYY-MM-DD)")
editItemCmd.Flags().StringVar(&opts.singleSelectOptionID, "single-select-option-id", "", "ID of the single select option value to set on the field")
editItemCmd.Flags().StringVar(&opts.iterationID, "iteration-id", "", "ID of the iteration value to set on the field")
editItemCmd.Flags().BoolVar(&opts.clear, "clear", false, "Remove field value")
_ = editItemCmd.MarkFlagRequired("id")
return editItemCmd
}
func runEditItem(config editItemConfig) error {
// when clear flag is used, remove value set to the corresponding field ID
if config.opts.clear {
return clearItemFieldValue(config)
}
// update draft issue
if config.opts.title != "" || config.opts.body != "" {
return updateDraftIssue(config)
}
// update item values
if config.opts.text != "" || config.opts.numberChanged || config.opts.date != "" || config.opts.singleSelectOptionID != "" || config.opts.iterationID != "" {
return updateItemValues(config)
}
if _, err := fmt.Fprintln(config.io.ErrOut, "error: no changes to make"); err != nil {
return err
}
return cmdutil.SilentError
}
func buildEditDraftIssue(config editItemConfig) (*EditProjectDraftIssue, map[string]interface{}) {
return &EditProjectDraftIssue{}, map[string]interface{}{
"input": githubv4.UpdateProjectV2DraftIssueInput{
Body: githubv4.NewString(githubv4.String(config.opts.body)),
DraftIssueID: githubv4.ID(config.opts.itemID),
Title: githubv4.NewString(githubv4.String(config.opts.title)),
},
}
}
func buildUpdateItem(config editItemConfig, date time.Time) (*UpdateProjectV2FieldValue, map[string]interface{}) {
var value githubv4.ProjectV2FieldValue
if config.opts.text != "" {
value = githubv4.ProjectV2FieldValue{
Text: githubv4.NewString(githubv4.String(config.opts.text)),
}
} else if config.opts.numberChanged {
value = githubv4.ProjectV2FieldValue{
Number: githubv4.NewFloat(githubv4.Float(config.opts.number)),
}
} else if config.opts.date != "" {
value = githubv4.ProjectV2FieldValue{
Date: githubv4.NewDate(githubv4.Date{Time: date}),
}
} else if config.opts.singleSelectOptionID != "" {
value = githubv4.ProjectV2FieldValue{
SingleSelectOptionID: githubv4.NewString(githubv4.String(config.opts.singleSelectOptionID)),
}
} else if config.opts.iterationID != "" {
value = githubv4.ProjectV2FieldValue{
IterationID: githubv4.NewString(githubv4.String(config.opts.iterationID)),
}
}
return &UpdateProjectV2FieldValue{}, map[string]interface{}{
"input": githubv4.UpdateProjectV2ItemFieldValueInput{
ProjectID: githubv4.ID(config.opts.projectID),
ItemID: githubv4.ID(config.opts.itemID),
FieldID: githubv4.ID(config.opts.fieldID),
Value: value,
},
}
}
func buildClearItem(config editItemConfig) (*ClearProjectV2FieldValue, map[string]interface{}) {
return &ClearProjectV2FieldValue{}, map[string]interface{}{
"input": githubv4.ClearProjectV2ItemFieldValueInput{
ProjectID: githubv4.ID(config.opts.projectID),
ItemID: githubv4.ID(config.opts.itemID),
FieldID: githubv4.ID(config.opts.fieldID),
},
}
}
func printDraftIssueResults(config editItemConfig, item queries.DraftIssue) error {
if !config.io.IsStdoutTTY() {
return nil
}
_, err := fmt.Fprintf(config.io.Out, "Edited draft issue %q\n", item.Title)
return err
}
func printItemResults(config editItemConfig, item *queries.ProjectItem) error {
if !config.io.IsStdoutTTY() {
return nil
}
_, err := fmt.Fprintf(config.io.Out, "Edited item %q\n", item.Title())
return err
}
func clearItemFieldValue(config editItemConfig) error {
if err := fieldIdAndProjectIdPresence(config); err != nil {
return err
}
query, variables := buildClearItem(config)
err := config.client.Mutate("ClearItemFieldValue", query, variables)
if err != nil {
return err
}
if config.opts.exporter != nil {
return config.opts.exporter.Write(config.io, &query.Clear.Item)
}
return printItemResults(config, &query.Clear.Item)
}
func updateDraftIssue(config editItemConfig) error {
if !strings.HasPrefix(config.opts.itemID, "DI_") {
return cmdutil.FlagErrorf("ID must be the ID of the draft issue content which is prefixed with `DI_`")
}
query, variables := buildEditDraftIssue(config)
err := config.client.Mutate("EditDraftIssueItem", query, variables)
if err != nil {
return err
}
if config.opts.exporter != nil {
return config.opts.exporter.Write(config.io, query.UpdateProjectV2DraftIssue.DraftIssue)
}
return printDraftIssueResults(config, query.UpdateProjectV2DraftIssue.DraftIssue)
}
func updateItemValues(config editItemConfig) error {
if err := fieldIdAndProjectIdPresence(config); err != nil {
return err
}
var parsedDate time.Time
if config.opts.date != "" {
date, err := time.Parse("2006-01-02", config.opts.date)
if err != nil {
return err
}
parsedDate = date
}
query, variables := buildUpdateItem(config, parsedDate)
err := config.client.Mutate("UpdateItemValues", query, variables)
if err != nil {
return err
}
if config.opts.exporter != nil {
return config.opts.exporter.Write(config.io, &query.Update.Item)
}
return printItemResults(config, &query.Update.Item)
}
func fieldIdAndProjectIdPresence(config editItemConfig) error {
if config.opts.fieldID == "" && config.opts.projectID == "" {
return cmdutil.FlagErrorf("field-id and project-id must be provided")
}
if config.opts.fieldID == "" {
return cmdutil.FlagErrorf("field-id must be provided")
}
if config.opts.projectID == "" {
// TODO: offer to fetch interactively
return cmdutil.FlagErrorf("project-id must be provided")
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/item-edit/item_edit_test.go | pkg/cmd/project/item-edit/item_edit_test.go | package itemedit
import (
"testing"
"github.com/cli/cli/v2/pkg/cmd/project/shared/queries"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"gopkg.in/h2non/gock.v1"
)
func TestNewCmdeditItem(t *testing.T) {
tests := []struct {
name string
cli string
wants editItemOpts
wantsErr bool
wantsErrMsg string
wantsExporter bool
}{
{
name: "missing-id",
cli: "",
wantsErr: true,
wantsErrMsg: "required flag(s) \"id\" not set",
},
{
name: "invalid-flags",
cli: "--id 123 --text t --date 2023-01-01",
wantsErr: true,
wantsErrMsg: "only one of `--text`, `--number`, `--date`, `--single-select-option-id` or `--iteration-id` may be used",
},
{
name: "item-id",
cli: "--id 123",
wants: editItemOpts{
itemID: "123",
},
},
{
name: "number",
cli: "--number 456 --id 123",
wants: editItemOpts{
number: 456,
itemID: "123",
},
},
{
name: "number with floating point value",
cli: "--number 123.45 --id 123",
wants: editItemOpts{
number: 123.45,
itemID: "123",
},
},
{
name: "number zero",
cli: "--number 0 --id 123",
wants: editItemOpts{
number: 0,
itemID: "123",
},
},
{
name: "field-id",
cli: "--field-id FIELD_ID --id 123",
wants: editItemOpts{
fieldID: "FIELD_ID",
itemID: "123",
},
},
{
name: "project-id",
cli: "--project-id PROJECT_ID --id 123",
wants: editItemOpts{
projectID: "PROJECT_ID",
itemID: "123",
},
},
{
name: "text",
cli: "--text t --id 123",
wants: editItemOpts{
text: "t",
itemID: "123",
},
},
{
name: "date",
cli: "--date 2023-01-01 --id 123",
wants: editItemOpts{
date: "2023-01-01",
itemID: "123",
},
},
{
name: "single-select-option-id",
cli: "--single-select-option-id OPTION_ID --id 123",
wants: editItemOpts{
singleSelectOptionID: "OPTION_ID",
itemID: "123",
},
},
{
name: "iteration-id",
cli: "--iteration-id ITERATION_ID --id 123",
wants: editItemOpts{
iterationID: "ITERATION_ID",
itemID: "123",
},
},
{
name: "clear",
cli: "--id 123 --field-id FIELD_ID --project-id PROJECT_ID --clear",
wants: editItemOpts{
itemID: "123",
fieldID: "FIELD_ID",
projectID: "PROJECT_ID",
clear: true,
},
},
{
name: "json",
cli: "--format json --id 123",
wants: editItemOpts{
itemID: "123",
},
wantsExporter: true,
},
}
t.Setenv("GH_TOKEN", "auth-token")
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
f := &cmdutil.Factory{
IOStreams: ios,
}
argv, err := shlex.Split(tt.cli)
assert.NoError(t, err)
var gotOpts editItemOpts
cmd := NewCmdEditItem(f, func(config editItemConfig) error {
gotOpts = config.opts
return nil
})
cmd.SetArgs(argv)
_, err = cmd.ExecuteC()
if tt.wantsErr {
assert.Error(t, err)
assert.Equal(t, tt.wantsErrMsg, err.Error())
return
}
assert.NoError(t, err)
assert.Equal(t, tt.wants.number, gotOpts.number)
assert.Equal(t, tt.wants.itemID, gotOpts.itemID)
assert.Equal(t, tt.wantsExporter, gotOpts.exporter != nil)
assert.Equal(t, tt.wants.title, gotOpts.title)
assert.Equal(t, tt.wants.fieldID, gotOpts.fieldID)
assert.Equal(t, tt.wants.projectID, gotOpts.projectID)
assert.Equal(t, tt.wants.text, gotOpts.text)
assert.Equal(t, tt.wants.number, gotOpts.number)
assert.Equal(t, tt.wants.date, gotOpts.date)
assert.Equal(t, tt.wants.singleSelectOptionID, gotOpts.singleSelectOptionID)
assert.Equal(t, tt.wants.iterationID, gotOpts.iterationID)
assert.Equal(t, tt.wants.clear, gotOpts.clear)
})
}
}
func TestRunItemEdit_Draft(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// edit item
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation EditDraftIssueItem.*","variables":{"input":{"draftIssueId":"DI_item_id","title":"a title","body":"a new body"}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"updateProjectV2DraftIssue": map[string]interface{}{
"draftIssue": map[string]interface{}{
"title": "a title",
"body": "a new body",
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(true)
config := editItemConfig{
io: ios,
opts: editItemOpts{
title: "a title",
body: "a new body",
itemID: "DI_item_id",
},
client: client,
}
err := runEditItem(config)
assert.NoError(t, err)
assert.Equal(
t,
"Edited draft issue \"a title\"\n",
stdout.String())
}
func TestRunItemEdit_Text(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// edit item
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation UpdateItemValues.*","variables":{"input":{"projectId":"project_id","itemId":"item_id","fieldId":"field_id","value":{"text":"item text"}}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"updateProjectV2ItemFieldValue": map[string]interface{}{
"projectV2Item": map[string]interface{}{
"ID": "item_id",
"content": map[string]interface{}{
"__typename": "Issue",
"body": "body",
"title": "title",
"number": 1,
"repository": map[string]interface{}{
"nameWithOwner": "my-repo",
},
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
config := editItemConfig{
io: ios,
opts: editItemOpts{
text: "item text",
itemID: "item_id",
projectID: "project_id",
fieldID: "field_id",
},
client: client,
}
err := runEditItem(config)
assert.NoError(t, err)
assert.Equal(t, "", stdout.String())
}
func TestRunItemEdit_Number(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// edit item
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation UpdateItemValues.*","variables":{"input":{"projectId":"project_id","itemId":"item_id","fieldId":"field_id","value":{"number":123.45}}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"updateProjectV2ItemFieldValue": map[string]interface{}{
"projectV2Item": map[string]interface{}{
"ID": "item_id",
"content": map[string]interface{}{
"__typename": "Issue",
"body": "body",
"title": "title",
"number": 1,
"repository": map[string]interface{}{
"nameWithOwner": "my-repo",
},
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(true)
config := editItemConfig{
io: ios,
opts: editItemOpts{
number: 123.45,
numberChanged: true,
itemID: "item_id",
projectID: "project_id",
fieldID: "field_id",
},
client: client,
}
err := runEditItem(config)
assert.NoError(t, err)
assert.Equal(
t,
"Edited item \"title\"\n",
stdout.String())
}
func TestRunItemEdit_NumberZero(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// edit item
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation UpdateItemValues.*","variables":{"input":{"projectId":"project_id","itemId":"item_id","fieldId":"field_id","value":{"number":0}}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"updateProjectV2ItemFieldValue": map[string]interface{}{
"projectV2Item": map[string]interface{}{
"ID": "item_id",
"content": map[string]interface{}{
"__typename": "Issue",
"body": "body",
"title": "title",
"number": 1,
"repository": map[string]interface{}{
"nameWithOwner": "my-repo",
},
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(true)
config := editItemConfig{
io: ios,
opts: editItemOpts{
number: 0,
numberChanged: true,
itemID: "item_id",
projectID: "project_id",
fieldID: "field_id",
},
client: client,
}
err := runEditItem(config)
assert.NoError(t, err)
assert.Equal(
t,
"Edited item \"title\"\n",
stdout.String())
}
func TestRunItemEdit_Date(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// edit item
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation UpdateItemValues.*","variables":{"input":{"projectId":"project_id","itemId":"item_id","fieldId":"field_id","value":{"date":"2023-01-01T00:00:00Z"}}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"updateProjectV2ItemFieldValue": map[string]interface{}{
"projectV2Item": map[string]interface{}{
"ID": "item_id",
"content": map[string]interface{}{
"__typename": "Issue",
"body": "body",
"title": "title",
"number": 1,
"repository": map[string]interface{}{
"nameWithOwner": "my-repo",
},
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
config := editItemConfig{
io: ios,
opts: editItemOpts{
date: "2023-01-01",
itemID: "item_id",
projectID: "project_id",
fieldID: "field_id",
},
client: client,
}
err := runEditItem(config)
assert.NoError(t, err)
assert.Equal(t, "", stdout.String())
}
func TestRunItemEdit_SingleSelect(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// edit item
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation UpdateItemValues.*","variables":{"input":{"projectId":"project_id","itemId":"item_id","fieldId":"field_id","value":{"singleSelectOptionId":"option_id"}}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"updateProjectV2ItemFieldValue": map[string]interface{}{
"projectV2Item": map[string]interface{}{
"ID": "item_id",
"content": map[string]interface{}{
"__typename": "Issue",
"body": "body",
"title": "title",
"number": 1,
"repository": map[string]interface{}{
"nameWithOwner": "my-repo",
},
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
config := editItemConfig{
io: ios,
opts: editItemOpts{
singleSelectOptionID: "option_id",
itemID: "item_id",
projectID: "project_id",
fieldID: "field_id",
},
client: client,
}
err := runEditItem(config)
assert.NoError(t, err)
assert.Equal(t, "", stdout.String())
}
func TestRunItemEdit_Iteration(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// edit item
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation UpdateItemValues.*","variables":{"input":{"projectId":"project_id","itemId":"item_id","fieldId":"field_id","value":{"iterationId":"option_id"}}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"updateProjectV2ItemFieldValue": map[string]interface{}{
"projectV2Item": map[string]interface{}{
"ID": "item_id",
"content": map[string]interface{}{
"__typename": "Issue",
"body": "body",
"title": "title",
"number": 1,
"repository": map[string]interface{}{
"nameWithOwner": "my-repo",
},
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(true)
config := editItemConfig{
io: ios,
opts: editItemOpts{
iterationID: "option_id",
itemID: "item_id",
projectID: "project_id",
fieldID: "field_id",
},
client: client,
}
err := runEditItem(config)
assert.NoError(t, err)
assert.Equal(
t,
"Edited item \"title\"\n",
stdout.String())
}
func TestRunItemEdit_NoChanges(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
client := queries.NewTestClient()
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdoutTTY(true)
config := editItemConfig{
io: ios,
opts: editItemOpts{},
client: client,
}
err := runEditItem(config)
assert.Error(t, err, "SilentError")
assert.Equal(t, "", stdout.String())
assert.Equal(t, "error: no changes to make\n", stderr.String())
}
func TestRunItemEdit_InvalidID(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
client := queries.NewTestClient()
config := editItemConfig{
opts: editItemOpts{
title: "a title",
body: "a new body",
itemID: "item_id",
},
client: client,
}
err := runEditItem(config)
assert.Error(t, err, "ID must be the ID of the draft issue content which is prefixed with `DI_`")
}
func TestRunItemEdit_Clear(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation ClearItemFieldValue.*","variables":{"input":{"projectId":"project_id","itemId":"item_id","fieldId":"field_id"}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"clearProjectV2ItemFieldValue": map[string]interface{}{
"projectV2Item": map[string]interface{}{
"ID": "item_id",
"content": map[string]interface{}{
"__typename": "Issue",
"body": "body",
"title": "title",
"number": 1,
"repository": map[string]interface{}{
"nameWithOwner": "my-repo",
},
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(true)
config := editItemConfig{
io: ios,
opts: editItemOpts{
itemID: "item_id",
projectID: "project_id",
fieldID: "field_id",
clear: true,
},
client: client,
}
err := runEditItem(config)
assert.NoError(t, err)
assert.Equal(t, "Edited item \"title\"\n", stdout.String())
}
func TestRunItemEdit_JSON(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// edit item
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation EditDraftIssueItem.*","variables":{"input":{"draftIssueId":"DI_item_id","title":"a title","body":"a new body"}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"updateProjectV2DraftIssue": map[string]interface{}{
"draftIssue": map[string]interface{}{
"id": "DI_item_id",
"title": "a title",
"body": "a new body",
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
config := editItemConfig{
io: ios,
opts: editItemOpts{
title: "a title",
body: "a new body",
itemID: "DI_item_id",
exporter: cmdutil.NewJSONExporter(),
},
client: client,
}
err := runEditItem(config)
assert.NoError(t, err)
assert.JSONEq(
t,
`{"id":"DI_item_id","title":"a title","body":"a new body","type":"DraftIssue"}`,
stdout.String())
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/close/close_test.go | pkg/cmd/project/close/close_test.go | package close
import (
"testing"
"github.com/cli/cli/v2/pkg/cmd/project/shared/queries"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"gopkg.in/h2non/gock.v1"
)
func TestNewCmdClose(t *testing.T) {
tests := []struct {
name string
cli string
wants closeOpts
wantsErr bool
wantsErrMsg string
wantsExporter bool
}{
{
name: "not-a-number",
cli: "x",
wantsErr: true,
wantsErrMsg: "invalid number: x",
},
{
name: "number",
cli: "123",
wants: closeOpts{
number: 123,
},
},
{
name: "owner",
cli: "--owner monalisa",
wants: closeOpts{
owner: "monalisa",
},
},
{
name: "reopen",
cli: "--undo",
wants: closeOpts{
reopen: true,
},
},
{
name: "json",
cli: "--format json",
wantsExporter: true,
},
}
t.Setenv("GH_TOKEN", "auth-token")
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
f := &cmdutil.Factory{
IOStreams: ios,
}
argv, err := shlex.Split(tt.cli)
assert.NoError(t, err)
var gotOpts closeOpts
cmd := NewCmdClose(f, func(config closeConfig) error {
gotOpts = config.opts
return nil
})
cmd.SetArgs(argv)
_, err = cmd.ExecuteC()
if tt.wantsErr {
assert.Error(t, err)
assert.Equal(t, tt.wantsErrMsg, err.Error())
return
}
assert.NoError(t, err)
assert.Equal(t, tt.wants.number, gotOpts.number)
assert.Equal(t, tt.wants.owner, gotOpts.owner)
assert.Equal(t, tt.wantsExporter, gotOpts.exporter != nil)
})
}
}
func TestRunClose_User(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// get user ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "monalisa",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"organization"},
},
},
})
// get user project ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserProject.*",
"variables": map[string]interface{}{
"login": "monalisa",
"number": 1,
"firstItems": 0,
"afterItems": nil,
"firstFields": 0,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"projectV2": map[string]string{
"id": "an ID",
},
},
},
})
// close project
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation CloseProjectV2.*"variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"projectId":"an ID","closed":true}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"updateProjectV2": map[string]interface{}{
"projectV2": map[string]interface{}{
"title": "a title",
"url": "http://a-url.com",
"owner": map[string]string{
"login": "monalisa",
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(true)
config := closeConfig{
io: ios,
opts: closeOpts{
number: 1,
owner: "monalisa",
},
client: client,
}
err := runClose(config)
assert.NoError(t, err)
assert.Equal(
t,
"http://a-url.com\n",
stdout.String())
}
func TestRunClose_Org(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// get org ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "github",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"organization": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"user"},
},
},
})
// get org project ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query OrgProject.*",
"variables": map[string]interface{}{
"login": "github",
"number": 1,
"firstItems": 0,
"afterItems": nil,
"firstFields": 0,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"organization": map[string]interface{}{
"projectV2": map[string]string{
"id": "an ID",
},
},
},
})
// close project
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation CloseProjectV2.*"variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"projectId":"an ID","closed":true}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"updateProjectV2": map[string]interface{}{
"projectV2": map[string]interface{}{
"title": "a title",
"url": "http://a-url.com",
"owner": map[string]string{
"login": "monalisa",
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
config := closeConfig{
io: ios,
opts: closeOpts{
number: 1,
owner: "github",
},
client: client,
}
err := runClose(config)
assert.NoError(t, err)
assert.Equal(t, "", stdout.String())
}
func TestRunClose_Me(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// get viewer ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query ViewerOwner.*",
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"id": "an ID",
},
},
})
// get viewer project ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query ViewerProject.*",
"variables": map[string]interface{}{
"number": 1,
"firstItems": 0,
"afterItems": nil,
"firstFields": 0,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"projectV2": map[string]string{
"id": "an ID",
},
},
},
})
// close project
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation CloseProjectV2.*"variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"projectId":"an ID","closed":true}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"updateProjectV2": map[string]interface{}{
"projectV2": map[string]interface{}{
"title": "a title",
"url": "http://a-url.com",
"owner": map[string]string{
"login": "me",
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
config := closeConfig{
io: ios,
opts: closeOpts{
number: 1,
owner: "@me",
},
client: client,
}
err := runClose(config)
assert.NoError(t, err)
assert.Equal(t, "", stdout.String())
}
func TestRunClose_Reopen(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// get user ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "monalisa",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"organization"},
},
},
})
// get user project ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserProject.*",
"variables": map[string]interface{}{
"login": "monalisa",
"number": 1,
"firstItems": 0,
"afterItems": nil,
"firstFields": 0,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"projectV2": map[string]string{
"id": "an ID",
},
},
},
})
// close project
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation CloseProjectV2.*"variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"projectId":"an ID","closed":false}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"updateProjectV2": map[string]interface{}{
"projectV2": map[string]interface{}{
"title": "a title",
"url": "http://a-url.com",
"owner": map[string]string{
"login": "monalisa",
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(true)
config := closeConfig{
io: ios,
opts: closeOpts{
number: 1,
owner: "monalisa",
reopen: true,
},
client: client,
}
err := runClose(config)
assert.NoError(t, err)
assert.Equal(
t,
"http://a-url.com\n",
stdout.String())
}
func TestRunClose_JSON(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// get user ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]interface{}{
"login": "monalisa",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"id": "an ID",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"organization"},
},
},
})
// get user project ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserProject.*",
"variables": map[string]interface{}{
"login": "monalisa",
"number": 1,
"firstItems": 0,
"afterItems": nil,
"firstFields": 0,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"projectV2": map[string]string{
"id": "an ID",
},
},
},
})
// close project
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation CloseProjectV2.*"variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"projectId":"an ID","closed":true}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"updateProjectV2": map[string]interface{}{
"projectV2": map[string]interface{}{
"number": 1,
"title": "a title",
"url": "http://a-url.com",
"owner": map[string]interface{}{
"__typename": "User",
"login": "monalisa",
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
config := closeConfig{
io: ios,
opts: closeOpts{
number: 1,
owner: "monalisa",
exporter: cmdutil.NewJSONExporter(),
},
client: client,
}
err := runClose(config)
assert.NoError(t, err)
assert.JSONEq(
t,
`{"number":1,"url":"http://a-url.com","shortDescription":"","public":false,"closed":false,"title":"a title","id":"","readme":"","items":{"totalCount":0},"fields":{"totalCount":0},"owner":{"type":"User","login":"monalisa"}}`,
stdout.String())
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/close/close.go | pkg/cmd/project/close/close.go | package close
import (
"fmt"
"strconv"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/pkg/cmd/project/shared/client"
"github.com/cli/cli/v2/pkg/cmd/project/shared/queries"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/shurcooL/githubv4"
"github.com/spf13/cobra"
)
type closeOpts struct {
number int32
owner string
reopen bool
projectID string
exporter cmdutil.Exporter
}
type closeConfig struct {
io *iostreams.IOStreams
client *queries.Client
opts closeOpts
}
// the close command relies on the updateProjectV2 mutation
type updateProjectMutation struct {
UpdateProjectV2 struct {
ProjectV2 queries.Project `graphql:"projectV2"`
} `graphql:"updateProjectV2(input:$input)"`
}
func NewCmdClose(f *cmdutil.Factory, runF func(config closeConfig) error) *cobra.Command {
opts := closeOpts{}
closeCmd := &cobra.Command{
Short: "Close a project",
Use: "close [<number>]",
Example: heredoc.Doc(`
# Close project "1" owned by monalisa
$ gh project close 1 --owner monalisa
# Reopen closed project "1" owned by github
$ gh project close 1 --owner github --undo
`),
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
client, err := client.New(f)
if err != nil {
return err
}
if len(args) == 1 {
num, err := strconv.ParseInt(args[0], 10, 32)
if err != nil {
return cmdutil.FlagErrorf("invalid number: %v", args[0])
}
opts.number = int32(num)
}
config := closeConfig{
io: f.IOStreams,
client: client,
opts: opts,
}
// allow testing of the command without actually running it
if runF != nil {
return runF(config)
}
return runClose(config)
},
}
closeCmd.Flags().StringVar(&opts.owner, "owner", "", "Login of the owner. Use \"@me\" for the current user.")
closeCmd.Flags().BoolVar(&opts.reopen, "undo", false, "Reopen a closed project")
cmdutil.AddFormatFlags(closeCmd, &opts.exporter)
return closeCmd
}
func runClose(config closeConfig) error {
canPrompt := config.io.CanPrompt()
owner, err := config.client.NewOwner(canPrompt, config.opts.owner)
if err != nil {
return err
}
project, err := config.client.NewProject(canPrompt, owner, config.opts.number, false)
if err != nil {
return err
}
config.opts.projectID = project.ID
query, variables := closeArgs(config)
err = config.client.Mutate("CloseProjectV2", query, variables)
if err != nil {
return err
}
if config.opts.exporter != nil {
return config.opts.exporter.Write(config.io, query.UpdateProjectV2.ProjectV2)
}
return printResults(config, query.UpdateProjectV2.ProjectV2)
}
func closeArgs(config closeConfig) (*updateProjectMutation, map[string]interface{}) {
closed := !config.opts.reopen
return &updateProjectMutation{}, map[string]interface{}{
"input": githubv4.UpdateProjectV2Input{
ProjectID: githubv4.ID(config.opts.projectID),
Closed: githubv4.NewBoolean(githubv4.Boolean(closed)),
},
"firstItems": githubv4.Int(0),
"afterItems": (*githubv4.String)(nil),
"firstFields": githubv4.Int(0),
"afterFields": (*githubv4.String)(nil),
}
}
func printResults(config closeConfig, project queries.Project) error {
if !config.io.IsStdoutTTY() {
return nil
}
_, err := fmt.Fprintf(config.io.Out, "%s\n", project.URL)
return err
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/copy/copy.go | pkg/cmd/project/copy/copy.go | package copy
import (
"fmt"
"strconv"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/pkg/cmd/project/shared/client"
"github.com/cli/cli/v2/pkg/cmd/project/shared/queries"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/shurcooL/githubv4"
"github.com/spf13/cobra"
)
type copyOpts struct {
includeDraftIssues bool
number int32
ownerID string
projectID string
sourceOwner string
targetOwner string
title string
exporter cmdutil.Exporter
}
type copyConfig struct {
io *iostreams.IOStreams
client *queries.Client
opts copyOpts
}
type copyProjectMutation struct {
CopyProjectV2 struct {
ProjectV2 queries.Project `graphql:"projectV2"`
} `graphql:"copyProjectV2(input:$input)"`
}
func NewCmdCopy(f *cmdutil.Factory, runF func(config copyConfig) error) *cobra.Command {
opts := copyOpts{}
copyCmd := &cobra.Command{
Short: "Copy a project",
Use: "copy [<number>]",
Example: heredoc.Doc(`
# Copy project "1" owned by monalisa to github
$ gh project copy 1 --source-owner monalisa --target-owner github --title "a new project"
`),
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
client, err := client.New(f)
if err != nil {
return err
}
if len(args) == 1 {
num, err := strconv.ParseInt(args[0], 10, 32)
if err != nil {
return cmdutil.FlagErrorf("invalid number: %v", args[0])
}
opts.number = int32(num)
}
config := copyConfig{
io: f.IOStreams,
client: client,
opts: opts,
}
// allow testing of the command without actually running it
if runF != nil {
return runF(config)
}
return runCopy(config)
},
}
copyCmd.Flags().StringVar(&opts.sourceOwner, "source-owner", "", "Login of the source owner. Use \"@me\" for the current user.")
copyCmd.Flags().StringVar(&opts.targetOwner, "target-owner", "", "Login of the target owner. Use \"@me\" for the current user.")
copyCmd.Flags().StringVar(&opts.title, "title", "", "Title for the new project")
copyCmd.Flags().BoolVar(&opts.includeDraftIssues, "drafts", false, "Include draft issues when copying")
cmdutil.AddFormatFlags(copyCmd, &opts.exporter)
_ = copyCmd.MarkFlagRequired("title")
return copyCmd
}
func runCopy(config copyConfig) error {
canPrompt := config.io.CanPrompt()
sourceOwner, err := config.client.NewOwner(canPrompt, config.opts.sourceOwner)
if err != nil {
return err
}
targetOwner, err := config.client.NewOwner(canPrompt, config.opts.targetOwner)
if err != nil {
return err
}
project, err := config.client.NewProject(canPrompt, sourceOwner, config.opts.number, false)
if err != nil {
return err
}
config.opts.projectID = project.ID
config.opts.ownerID = targetOwner.ID
query, variables := copyArgs(config)
err = config.client.Mutate("CopyProjectV2", query, variables)
if err != nil {
return err
}
if config.opts.exporter != nil {
return config.opts.exporter.Write(config.io, query.CopyProjectV2.ProjectV2)
}
return printResults(config, query.CopyProjectV2.ProjectV2)
}
func copyArgs(config copyConfig) (*copyProjectMutation, map[string]interface{}) {
return ©ProjectMutation{}, map[string]interface{}{
"input": githubv4.CopyProjectV2Input{
OwnerID: githubv4.ID(config.opts.ownerID),
ProjectID: githubv4.ID(config.opts.projectID),
Title: githubv4.String(config.opts.title),
IncludeDraftIssues: githubv4.NewBoolean(githubv4.Boolean(config.opts.includeDraftIssues)),
},
"firstItems": githubv4.Int(0),
"afterItems": (*githubv4.String)(nil),
"firstFields": githubv4.Int(0),
"afterFields": (*githubv4.String)(nil),
}
}
func printResults(config copyConfig, project queries.Project) error {
if !config.io.IsStdoutTTY() {
return nil
}
_, err := fmt.Fprintf(config.io.Out, "%s\n", project.URL)
return err
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/copy/copy_test.go | pkg/cmd/project/copy/copy_test.go | package copy
import (
"testing"
"github.com/cli/cli/v2/pkg/cmd/project/shared/queries"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"gopkg.in/h2non/gock.v1"
)
func TestNewCmdCopy(t *testing.T) {
tests := []struct {
name string
cli string
wants copyOpts
wantsErr bool
wantsErrMsg string
wantsExporter bool
}{
{
name: "not-a-number",
cli: "x --title t",
wantsErr: true,
wantsErrMsg: "invalid number: x",
},
{
name: "title",
cli: "--title t",
wants: copyOpts{
title: "t",
},
},
{
name: "number",
cli: "123 --title t",
wants: copyOpts{
number: 123,
title: "t",
},
},
{
name: "source-owner",
cli: "--source-owner monalisa --title t",
wants: copyOpts{
sourceOwner: "monalisa",
title: "t",
},
},
{
name: "target-owner",
cli: "--target-owner monalisa --title t",
wants: copyOpts{
targetOwner: "monalisa",
title: "t",
},
},
{
name: "drafts",
cli: "--drafts --title t",
wants: copyOpts{
includeDraftIssues: true,
title: "t",
},
},
{
name: "json",
cli: "--format json --title t",
wants: copyOpts{
title: "t",
},
wantsExporter: true,
},
}
t.Setenv("GH_TOKEN", "auth-token")
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
f := &cmdutil.Factory{
IOStreams: ios,
}
argv, err := shlex.Split(tt.cli)
assert.NoError(t, err)
var gotOpts copyOpts
cmd := NewCmdCopy(f, func(config copyConfig) error {
gotOpts = config.opts
return nil
})
cmd.SetArgs(argv)
_, err = cmd.ExecuteC()
if tt.wantsErr {
assert.Error(t, err)
assert.Equal(t, tt.wantsErrMsg, err.Error())
return
}
assert.NoError(t, err)
assert.Equal(t, tt.wants.number, gotOpts.number)
assert.Equal(t, tt.wants.sourceOwner, gotOpts.sourceOwner)
assert.Equal(t, tt.wants.targetOwner, gotOpts.targetOwner)
assert.Equal(t, tt.wants.title, gotOpts.title)
assert.Equal(t, tt.wants.includeDraftIssues, gotOpts.includeDraftIssues)
assert.Equal(t, tt.wantsExporter, gotOpts.exporter != nil)
})
}
}
func TestRunCopy_User(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// get user project ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserProject.*",
"variables": map[string]interface{}{
"login": "monalisa",
"number": 1,
"firstItems": 0,
"afterItems": nil,
"firstFields": 0,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"projectV2": map[string]string{
"id": "an ID",
},
},
},
})
// get source user ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]string{
"login": "monalisa",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"id": "an ID",
"login": "monalisa",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"organization"},
},
},
})
// get target user ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]string{
"login": "monalisa",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"id": "an ID",
"login": "monalisa",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"organization"},
},
},
})
// Copy project
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation CopyProjectV2.*","variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"projectId":"an ID","ownerId":"an ID","title":"a title","includeDraftIssues":false}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"copyProjectV2": map[string]interface{}{
"projectV2": map[string]interface{}{
"title": "a title",
"url": "http://a-url.com",
"owner": map[string]string{
"login": "monalisa",
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(false)
config := copyConfig{
io: ios,
opts: copyOpts{
title: "a title",
sourceOwner: "monalisa",
targetOwner: "monalisa",
number: 1,
},
client: client,
}
err := runCopy(config)
assert.NoError(t, err)
assert.Equal(t, "", stdout.String())
}
func TestRunCopy_Org(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// get org project ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query OrgProject.*",
"variables": map[string]interface{}{
"login": "github",
"number": 1,
"firstItems": 0,
"afterItems": nil,
"firstFields": 0,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"organization": map[string]interface{}{
"projectV2": map[string]string{
"id": "an ID",
},
},
},
})
// get source org ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]string{
"login": "github",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"organization": map[string]interface{}{
"id": "an ID",
"login": "github",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"user"},
},
},
})
// get target source org ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]string{
"login": "github",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"organization": map[string]interface{}{
"id": "an ID",
"login": "github",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"user"},
},
},
})
// Copy project
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation CopyProjectV2.*","variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"projectId":"an ID","ownerId":"an ID","title":"a title","includeDraftIssues":false}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"copyProjectV2": map[string]interface{}{
"projectV2": map[string]interface{}{
"title": "a title",
"url": "http://a-url.com",
"owner": map[string]string{
"login": "monalisa",
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(false)
config := copyConfig{
io: ios,
opts: copyOpts{
title: "a title",
sourceOwner: "github",
targetOwner: "github",
number: 1,
},
client: client,
}
err := runCopy(config)
assert.NoError(t, err)
assert.Equal(t, "", stdout.String())
}
func TestRunCopy_Me(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// get viewer project ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query ViewerProject.*",
"variables": map[string]interface{}{
"number": 1,
"firstItems": 0,
"afterItems": nil,
"firstFields": 0,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"projectV2": map[string]string{
"id": "an ID",
},
},
},
})
// get source viewer ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query ViewerOwner.*",
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"id": "an ID",
"login": "me",
},
},
})
// get target viewer ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query ViewerOwner.*",
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"viewer": map[string]interface{}{
"id": "an ID",
"login": "me",
},
},
})
// Copy project
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation CopyProjectV2.*","variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"projectId":"an ID","ownerId":"an ID","title":"a title","includeDraftIssues":false}}}`).Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"copyProjectV2": map[string]interface{}{
"projectV2": map[string]interface{}{
"title": "a title",
"url": "http://a-url.com",
"owner": map[string]string{
"login": "me",
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(true)
config := copyConfig{
io: ios,
opts: copyOpts{
title: "a title",
sourceOwner: "@me",
targetOwner: "@me",
number: 1,
},
client: client,
}
err := runCopy(config)
assert.NoError(t, err)
assert.Equal(
t,
"http://a-url.com\n",
stdout.String())
}
func TestRunCopy_JSON(t *testing.T) {
defer gock.Off()
// gock.Observe(gock.DumpRequest)
// get user project ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserProject.*",
"variables": map[string]interface{}{
"login": "monalisa",
"number": 1,
"firstItems": 0,
"afterItems": nil,
"firstFields": 0,
"afterFields": nil,
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"projectV2": map[string]string{
"id": "an ID",
},
},
},
})
// get source user ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]string{
"login": "monalisa",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"id": "an ID",
"login": "monalisa",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"organization"},
},
},
})
// get target user ID
gock.New("https://api.github.com").
Post("/graphql").
MatchType("json").
JSON(map[string]interface{}{
"query": "query UserOrgOwner.*",
"variables": map[string]string{
"login": "monalisa",
},
}).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"user": map[string]interface{}{
"id": "an ID",
"login": "monalisa",
},
},
"errors": []interface{}{
map[string]interface{}{
"type": "NOT_FOUND",
"path": []string{"organization"},
},
},
})
// Copy project
gock.New("https://api.github.com").
Post("/graphql").
BodyString(`{"query":"mutation CopyProjectV2.*","variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"projectId":"an ID","ownerId":"an ID","title":"a title","includeDraftIssues":false}}}`).
Reply(200).
JSON(map[string]interface{}{
"data": map[string]interface{}{
"copyProjectV2": map[string]interface{}{
"projectV2": map[string]interface{}{
"number": 1,
"title": "a title",
"url": "http://a-url.com",
"owner": map[string]string{
"login": "monalisa",
},
},
},
},
})
client := queries.NewTestClient()
ios, _, stdout, _ := iostreams.Test()
config := copyConfig{
io: ios,
opts: copyOpts{
title: "a title",
sourceOwner: "monalisa",
targetOwner: "monalisa",
number: 1,
exporter: cmdutil.NewJSONExporter(),
},
client: client,
}
err := runCopy(config)
assert.NoError(t, err)
assert.JSONEq(
t,
`{"number":1,"url":"http://a-url.com","shortDescription":"","public":false,"closed":false,"title":"a title","id":"","readme":"","items":{"totalCount":0},"fields":{"totalCount":0},"owner":{"type":"","login":"monalisa"}}`,
stdout.String())
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.