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/ruleset/view/view_test.go | pkg/cmd/ruleset/view/view_test.go | package view
import (
"bytes"
"io"
"net/http"
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/browser"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/prompter"
"github.com/cli/cli/v2/pkg/cmd/ruleset/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"
"github.com/stretchr/testify/require"
)
func Test_NewCmdView(t *testing.T) {
tests := []struct {
name string
args string
isTTY bool
want ViewOptions
wantErr string
}{
{
name: "no arguments",
args: "",
isTTY: true,
want: ViewOptions{
ID: "",
WebMode: false,
IncludeParents: true,
InteractiveMode: true,
Organization: "",
},
},
{
name: "only ID",
args: "3",
isTTY: true,
want: ViewOptions{
ID: "3",
WebMode: false,
IncludeParents: true,
InteractiveMode: false,
Organization: "",
},
},
{
name: "org",
args: "--org \"my-org\"",
isTTY: true,
want: ViewOptions{
ID: "",
WebMode: false,
IncludeParents: true,
InteractiveMode: true,
Organization: "my-org",
},
},
{
name: "web mode",
args: "--web",
isTTY: true,
want: ViewOptions{
ID: "",
WebMode: true,
IncludeParents: true,
InteractiveMode: true,
Organization: "",
},
},
{
name: "parents",
args: "--parents=false",
isTTY: true,
want: ViewOptions{
ID: "",
WebMode: false,
IncludeParents: false,
InteractiveMode: true,
Organization: "",
},
},
{
name: "repo and org specified",
args: "--org \"my-org\" -R \"owner/repo\"",
isTTY: true,
wantErr: "only one of --repo and --org may be specified",
},
{
name: "invalid ID",
args: "1.5",
isTTY: true,
wantErr: "invalid value for ruleset ID: 1.5 is not an integer",
},
{
name: "ID not provided and not TTY",
args: "",
isTTY: false,
wantErr: "a ruleset ID must be provided when not running interactively",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
ios.SetStdoutTTY(tt.isTTY)
ios.SetStdinTTY(tt.isTTY)
ios.SetStderrTTY(tt.isTTY)
f := &cmdutil.Factory{
IOStreams: ios,
}
var opts *ViewOptions
cmd := NewCmdView(f, func(o *ViewOptions) 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.ID, opts.ID)
assert.Equal(t, tt.want.WebMode, opts.WebMode)
assert.Equal(t, tt.want.IncludeParents, opts.IncludeParents)
assert.Equal(t, tt.want.InteractiveMode, opts.InteractiveMode)
assert.Equal(t, tt.want.Organization, opts.Organization)
})
}
}
func Test_viewRun(t *testing.T) {
repoRulesetStdout := heredoc.Doc(`
Test Ruleset
ID: 42
Source: my-owner/repo-name (Repository)
Enforcement: Active
You can bypass: pull requests only
Bypass List
- OrganizationAdmin (ID: 1), mode: always
- RepositoryRole (ID: 5), mode: always
Conditions
- ref_name: [exclude: []] [include: [~ALL]]
Rules
- commit_author_email_pattern: [name: ] [negate: false] [operator: ends_with] [pattern: @example.com]
- commit_message_pattern: [name: ] [negate: false] [operator: contains] [pattern: asdf]
- creation
`)
tests := []struct {
name string
isTTY bool
opts ViewOptions
httpStubs func(*httpmock.Registry)
prompterStubs func(*prompter.MockPrompter)
wantErr string
wantStdout string
wantStderr string
wantBrowse string
}{
{
name: "view repo ruleset",
isTTY: true,
opts: ViewOptions{
ID: "42",
},
wantStdout: repoRulesetStdout,
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/my-owner/repo-name/rulesets/42"),
httpmock.FileResponse("./fixtures/rulesetViewRepo.json"),
)
},
wantStderr: "",
wantBrowse: "",
},
{
name: "view org ruleset",
isTTY: true,
opts: ViewOptions{
ID: "74",
Organization: "my-owner",
},
wantStdout: heredoc.Doc(`
My Org Ruleset
ID: 74
Source: my-owner (Organization)
Enforcement: Evaluate Mode (not enforced)
Bypass List
This ruleset cannot be bypassed
Conditions
- ref_name: [exclude: []] [include: [~ALL]]
- repository_name: [exclude: []] [include: [~ALL]] [protected: true]
Rules
- commit_author_email_pattern: [name: ] [negate: false] [operator: ends_with] [pattern: @example.com]
- commit_message_pattern: [name: ] [negate: false] [operator: contains] [pattern: asdf]
- creation
`),
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "orgs/my-owner/rulesets/74"),
httpmock.FileResponse("./fixtures/rulesetViewOrg.json"),
)
},
wantStderr: "",
wantBrowse: "",
},
{
name: "interactive mode, repo, no rulesets found",
isTTY: true,
opts: ViewOptions{
InteractiveMode: true,
},
wantStdout: "",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query RepoRulesetList\b`),
httpmock.JSONResponse(shared.RulesetList{
TotalCount: 0,
Rulesets: []shared.RulesetGraphQL{},
}),
)
},
wantErr: "no rulesets found in my-owner/repo-name",
wantStderr: "",
wantBrowse: "",
},
{
name: "interactive mode, org, no rulesets found",
isTTY: true,
opts: ViewOptions{
InteractiveMode: true,
Organization: "my-owner",
},
wantStdout: "",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query OrgRulesetList\b`),
httpmock.JSONResponse(shared.RulesetList{
TotalCount: 0,
Rulesets: []shared.RulesetGraphQL{},
}),
)
},
wantErr: "no rulesets found in my-owner",
wantStderr: "",
wantBrowse: "",
},
{
name: "interactive mode, prompter",
isTTY: true,
opts: ViewOptions{
InteractiveMode: true,
},
wantStdout: repoRulesetStdout,
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query RepoRulesetList\b`),
httpmock.FileResponse("./fixtures/rulesetViewMultiple.json"),
)
reg.Register(
httpmock.REST("GET", "repos/my-owner/repo-name/rulesets/42"),
httpmock.FileResponse("./fixtures/rulesetViewRepo.json"),
)
},
prompterStubs: func(pm *prompter.MockPrompter) {
const repoRuleset = "42: Test Ruleset | active | contains 3 rules | configured in my-owner/repo-name (repo)"
pm.RegisterSelect("Which ruleset would you like to view?",
[]string{
"74: My Org Ruleset | evaluate | contains 3 rules | configured in my-owner (org)",
repoRuleset,
},
func(_, _ string, opts []string) (int, error) {
return prompter.IndexFor(opts, repoRuleset)
})
},
},
{
name: "web mode, TTY, repo",
isTTY: true,
opts: ViewOptions{
ID: "42",
WebMode: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/my-owner/repo-name/rulesets/42"),
httpmock.FileResponse("./fixtures/rulesetViewRepo.json"),
)
},
wantStdout: "Opening https://github.com/my-owner/repo-name/rules/42 in your browser.\n",
wantStderr: "",
wantBrowse: "https://github.com/my-owner/repo-name/rules/42",
},
{
name: "web mode, non-TTY, repo",
isTTY: false,
opts: ViewOptions{
ID: "42",
WebMode: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/my-owner/repo-name/rulesets/42"),
httpmock.FileResponse("./fixtures/rulesetViewRepo.json"),
)
},
wantStdout: "",
wantStderr: "",
wantBrowse: "https://github.com/my-owner/repo-name/rules/42",
},
{
name: "web mode, TTY, org",
isTTY: true,
opts: ViewOptions{
ID: "74",
Organization: "my-owner",
WebMode: true,
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "orgs/my-owner/rulesets/74"),
httpmock.FileResponse("./fixtures/rulesetViewOrg.json"),
)
},
wantStdout: "Opening https://github.com/organizations/my-owner/settings/rules/74 in your browser.\n",
wantStderr: "",
wantBrowse: "https://github.com/organizations/my-owner/settings/rules/74",
},
}
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)
pm := prompter.NewMockPrompter(t)
if tt.prompterStubs != nil {
tt.prompterStubs(pm)
}
tt.opts.Prompter = pm
reg := &httpmock.Registry{}
defer reg.Verify(t)
if tt.httpStubs != nil {
tt.httpStubs(reg)
}
tt.opts.IO = ios
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
// only set this if org is not set, because the repo isn't needed if --org is provided and
// leaving it undefined will catch potential errors
if tt.opts.Organization == "" {
tt.opts.BaseRepo = func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("my-owner/repo-name")
}
}
browser := &browser.Stub{}
tt.opts.Browser = browser
err := viewRun(&tt.opts)
if tt.wantErr != "" {
require.EqualError(t, err, tt.wantErr)
return
} else {
require.NoError(t, err)
}
if tt.wantBrowse != "" {
browser.Verify(t, tt.wantBrowse)
}
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/ruleset/shared/shared.go | pkg/cmd/ruleset/shared/shared.go | package shared
import (
"fmt"
"sort"
"strings"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmdutil"
)
type RulesetGraphQL struct {
DatabaseId int
Name string
Target string
Enforcement string
Source struct {
TypeName string `json:"__typename"`
Owner string
}
Rules struct {
TotalCount int
}
}
type RulesetREST struct {
Id int
Name string
Target string
Enforcement string
CurrentUserCanBypass string `json:"current_user_can_bypass"`
BypassActors []struct {
ActorId int `json:"actor_id"`
ActorType string `json:"actor_type"`
BypassMode string `json:"bypass_mode"`
} `json:"bypass_actors"`
Conditions map[string]map[string]interface{}
SourceType string `json:"source_type"`
Source string
Rules []RulesetRule
Links struct {
Html struct {
Href string
}
} `json:"_links"`
}
type RulesetRule struct {
Type string
Parameters map[string]interface{}
RulesetSourceType string `json:"ruleset_source_type"`
RulesetSource string `json:"ruleset_source"`
RulesetId int `json:"ruleset_id"`
}
// Returns the source of the ruleset in the format "owner/name (repo)" or "owner (org)"
func RulesetSource(rs RulesetGraphQL) string {
var level string
if rs.Source.TypeName == "Repository" {
level = "repo"
} else if rs.Source.TypeName == "Organization" {
level = "org"
} else {
level = "unknown"
}
return fmt.Sprintf("%s (%s)", rs.Source.Owner, level)
}
func ParseRulesForDisplay(rules []RulesetRule) string {
var display strings.Builder
// sort keys for consistent responses
sort.SliceStable(rules, func(i, j int) bool {
return rules[i].Type < rules[j].Type
})
for _, rule := range rules {
display.WriteString(fmt.Sprintf("- %s", rule.Type))
if len(rule.Parameters) > 0 {
display.WriteString(": ")
// sort these keys too for consistency
params := make([]string, 0, len(rule.Parameters))
for p := range rule.Parameters {
params = append(params, p)
}
sort.Strings(params)
for _, n := range params {
display.WriteString(fmt.Sprintf("[%s: %v] ", n, rule.Parameters[n]))
}
}
// ruleset source info is only returned from the "get rules for a branch" endpoint
if rule.RulesetSource != "" {
display.WriteString(
fmt.Sprintf(
"\n (configured in ruleset %d from %s %s)\n",
rule.RulesetId,
strings.ToLower(rule.RulesetSourceType),
rule.RulesetSource,
),
)
}
display.WriteString("\n")
}
return display.String()
}
func NoRulesetsFoundError(orgOption string, repoI ghrepo.Interface, includeParents bool) error {
entityName := EntityName(orgOption, repoI)
parentsMsg := ""
if includeParents {
parentsMsg = " or its parents"
}
return cmdutil.NewNoResultsError(fmt.Sprintf("no rulesets found in %s%s", entityName, parentsMsg))
}
func EntityName(orgOption string, repoI ghrepo.Interface) string {
if orgOption != "" {
return orgOption
}
return ghrepo.FullName(repoI)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/ruleset/shared/http.go | pkg/cmd/ruleset/shared/http.go | package shared
import (
"errors"
"net/http"
"strings"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghrepo"
)
type RulesetResponse struct {
Level struct {
Rulesets struct {
TotalCount int
Nodes []RulesetGraphQL
PageInfo struct {
HasNextPage bool
EndCursor string
}
}
}
}
type RulesetList struct {
TotalCount int
Rulesets []RulesetGraphQL
}
func ListRepoRulesets(httpClient *http.Client, repo ghrepo.Interface, limit int, includeParents bool) (*RulesetList, error) {
variables := map[string]interface{}{
"owner": repo.RepoOwner(),
"repo": repo.RepoName(),
"includeParents": includeParents,
}
return listRulesets(httpClient, rulesetsQuery(false), variables, limit, repo.RepoHost())
}
func ListOrgRulesets(httpClient *http.Client, orgLogin string, limit int, host string, includeParents bool) (*RulesetList, error) {
variables := map[string]interface{}{
"login": orgLogin,
"includeParents": includeParents,
}
return listRulesets(httpClient, rulesetsQuery(true), variables, limit, host)
}
func listRulesets(httpClient *http.Client, query string, variables map[string]interface{}, limit int, host string) (*RulesetList, error) {
pageLimit := min(limit, 100)
res := RulesetList{
Rulesets: []RulesetGraphQL{},
}
client := api.NewClientFromHTTP(httpClient)
for {
variables["limit"] = pageLimit
var data RulesetResponse
err := client.GraphQL(host, query, variables, &data)
if err != nil {
if strings.Contains(err.Error(), "requires one of the following scopes: ['admin:org']") {
return nil, errors.New("the 'admin:org' scope is required to view organization rulesets, try running 'gh auth refresh -s admin:org'")
}
return nil, err
}
res.TotalCount = data.Level.Rulesets.TotalCount
res.Rulesets = append(res.Rulesets, data.Level.Rulesets.Nodes...)
if len(res.Rulesets) >= limit {
break
}
if data.Level.Rulesets.PageInfo.HasNextPage {
variables["endCursor"] = data.Level.Rulesets.PageInfo.EndCursor
pageLimit = min(pageLimit, limit-len(res.Rulesets))
} else {
break
}
}
return &res, nil
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func rulesetsQuery(org bool) string {
if org {
return orgGraphQLHeader + sharedGraphQLBody
} else {
return repoGraphQLHeader + sharedGraphQLBody
}
}
const repoGraphQLHeader = `
query RepoRulesetList($limit: Int!, $endCursor: String, $includeParents: Boolean, $owner: String!, $repo: String!) {
level: repository(owner: $owner, name: $repo) {
`
const orgGraphQLHeader = `
query OrgRulesetList($limit: Int!, $endCursor: String, $includeParents: Boolean, $login: String!) {
level: organization(login: $login) {
`
const sharedGraphQLBody = `
rulesets(first: $limit, after: $endCursor, includeParents: $includeParents) {
totalCount
nodes {
databaseId
name
target
enforcement
source {
__typename
... on Repository { owner: nameWithOwner }
... on Organization { owner: login }
}
rules {
totalCount
}
}
pageInfo {
hasNextPage
endCursor
}
}}}`
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/cache/cache.go | pkg/cmd/cache/cache.go | package cache
import (
"github.com/MakeNowJust/heredoc"
cmdDelete "github.com/cli/cli/v2/pkg/cmd/cache/delete"
cmdList "github.com/cli/cli/v2/pkg/cmd/cache/list"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/spf13/cobra"
)
func NewCmdCache(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "cache <command>",
Short: "Manage GitHub Actions caches",
Long: "Work with GitHub Actions caches.",
Example: heredoc.Doc(`
$ gh cache list
$ gh cache delete --all
`),
GroupID: "actions",
}
cmdutil.EnableRepoOverride(cmd, f)
cmd.AddCommand(cmdList.NewCmdList(f, nil))
cmd.AddCommand(cmdDelete.NewCmdDelete(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/cache/delete/delete.go | pkg/cmd/cache/delete/delete.go | package delete
import (
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/cmd/cache/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type DeleteOptions struct {
BaseRepo func() (ghrepo.Interface, error)
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
DeleteAll bool
SucceedOnNoCaches bool
Identifier string
Ref string
}
func NewCmdDelete(f *cmdutil.Factory, runF func(*DeleteOptions) error) *cobra.Command {
opts := &DeleteOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
}
cmd := &cobra.Command{
Use: "delete [<cache-id> | <cache-key> | --all]",
Short: "Delete GitHub Actions caches",
Long: heredoc.Docf(`
Delete GitHub Actions caches.
Deletion requires authorization with the %[1]srepo%[1]s scope.
`, "`"),
Example: heredoc.Doc(`
# Delete a cache by id
$ gh cache delete 1234
# Delete a cache by key
$ gh cache delete cache-key
# Delete a cache by id in a specific repo
$ gh cache delete 1234 --repo cli/cli
# Delete a cache by key and branch ref
$ gh cache delete cache-key --ref refs/heads/feature-branch
# Delete a cache by key and PR ref
$ gh cache delete cache-key --ref refs/pull/<PR-number>/merge
# Delete all caches (exit code 1 on no caches)
$ gh cache delete --all
# Delete all caches (exit code 0 on no caches)
$ gh cache delete --all --succeed-on-no-caches
`),
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
// support -R/--repo flag
opts.BaseRepo = f.BaseRepo
if err := cmdutil.MutuallyExclusive(
"specify only one of cache id, cache key, or --all",
opts.DeleteAll, len(args) > 0,
); err != nil {
return err
}
if err := cmdutil.MutuallyExclusive(
"--ref cannot be used with --all",
opts.DeleteAll, opts.Ref != "",
); err != nil {
return err
}
if !opts.DeleteAll && opts.SucceedOnNoCaches {
return cmdutil.FlagErrorf("--succeed-on-no-caches must be used in conjunction with --all")
}
if opts.Ref != "" && len(args) == 0 {
return cmdutil.FlagErrorf("must provide a cache key")
}
if !opts.DeleteAll && len(args) == 0 {
return cmdutil.FlagErrorf("must provide either cache id, cache key, or use --all")
}
if len(args) > 0 && opts.Ref != "" {
if _, ok := parseCacheID(args[0]); ok {
return cmdutil.FlagErrorf("--ref cannot be used with cache ID")
}
}
if len(args) == 1 {
opts.Identifier = args[0]
}
if runF != nil {
return runF(opts)
}
return deleteRun(opts)
},
}
cmd.Flags().BoolVarP(&opts.DeleteAll, "all", "a", false, "Delete all caches")
cmd.Flags().StringVarP(&opts.Ref, "ref", "r", "", "Delete by cache key and ref, formatted as refs/heads/<branch name> or refs/pull/<number>/merge")
cmd.Flags().BoolVar(&opts.SucceedOnNoCaches, "succeed-on-no-caches", false, "Return exit code 0 if no caches found. Must be used in conjunction with `--all`")
return cmd
}
func deleteRun(opts *DeleteOptions) error {
httpClient, err := opts.HttpClient()
if err != nil {
return fmt.Errorf("failed to create http client: %w", err)
}
client := api.NewClientFromHTTP(httpClient)
repo, err := opts.BaseRepo()
if err != nil {
return fmt.Errorf("failed to determine base repo: %w", err)
}
var toDelete []string
if opts.DeleteAll {
opts.IO.StartProgressIndicator()
caches, err := shared.GetCaches(client, repo, shared.GetCachesOptions{Limit: -1})
opts.IO.StopProgressIndicator()
if err != nil {
return err
}
if len(caches.ActionsCaches) == 0 {
if opts.SucceedOnNoCaches {
if opts.IO.IsStdoutTTY() {
fmt.Fprintf(opts.IO.Out, "%s No caches to delete\n", opts.IO.ColorScheme().SuccessIcon())
}
return nil
} else {
return fmt.Errorf("%s No caches to delete", opts.IO.ColorScheme().FailureIcon())
}
}
for _, cache := range caches.ActionsCaches {
toDelete = append(toDelete, strconv.Itoa(cache.Id))
}
} else {
toDelete = append(toDelete, opts.Identifier)
}
return deleteCaches(opts, client, repo, toDelete)
}
func deleteCaches(opts *DeleteOptions, client *api.Client, repo ghrepo.Interface, toDelete []string) error {
cs := opts.IO.ColorScheme()
repoName := ghrepo.FullName(repo)
opts.IO.StartProgressIndicator()
totalDeleted := 0
for _, cache := range toDelete {
var count int
var err error
if id, ok := parseCacheID(cache); ok {
err = deleteCacheByID(client, repo, id)
count = 1
} else {
count, err = deleteCacheByKey(client, repo, cache, opts.Ref)
}
if err != nil {
var httpErr api.HTTPError
if errors.As(err, &httpErr) {
if httpErr.StatusCode == http.StatusNotFound {
if opts.Ref == "" {
err = fmt.Errorf("%s Could not find a cache matching %s in %s", cs.FailureIcon(), cache, repoName)
} else {
err = fmt.Errorf("%s Could not find a cache matching %s (with ref %s) in %s", cs.FailureIcon(), cache, opts.Ref, repoName)
}
} else {
err = fmt.Errorf("%s Failed to delete cache: %w", cs.FailureIcon(), err)
}
}
opts.IO.StopProgressIndicator()
return err
}
totalDeleted += count
}
opts.IO.StopProgressIndicator()
if opts.IO.IsStdoutTTY() {
fmt.Fprintf(opts.IO.Out, "%s Deleted %s from %s\n", cs.SuccessIcon(), text.Pluralize(totalDeleted, "cache"), repoName)
}
return nil
}
func deleteCacheByID(client *api.Client, repo ghrepo.Interface, id int) error {
// returns HTTP 204 (NO CONTENT) on success
path := fmt.Sprintf("repos/%s/actions/caches/%d", ghrepo.FullName(repo), id)
return client.REST(repo.RepoHost(), "DELETE", path, nil, nil)
}
// deleteCacheByKey deletes cache entries by given key (and optional ref) and
// returns the number of deleted entries.
//
// Note that a key/ref combination does not necessarily map to a single cache
// entry. There may be more than one entries with the same key/ref combination,
// but those entries will have different IDs.
func deleteCacheByKey(client *api.Client, repo ghrepo.Interface, key, ref string) (int, error) {
path := fmt.Sprintf("repos/%s/actions/caches?key=%s", ghrepo.FullName(repo), url.QueryEscape(key))
if ref != "" {
path += fmt.Sprintf("&ref=%s", url.QueryEscape(ref))
}
var payload shared.CachePayload
err := client.REST(repo.RepoHost(), "DELETE", path, nil, &payload)
if err != nil {
return 0, err
}
return payload.TotalCount, nil
}
func parseCacheID(arg string) (int, bool) {
id, err := strconv.Atoi(arg)
return id, err == nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/cache/delete/delete_test.go | pkg/cmd/cache/delete/delete_test.go | package delete
import (
"bytes"
"net/http"
"net/url"
"testing"
"time"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmd/cache/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 TestNewCmdDelete(t *testing.T) {
tests := []struct {
name string
cli string
wants DeleteOptions
wantsErr string
}{
{
name: "no arguments",
cli: "",
wantsErr: "must provide either cache id, cache key, or use --all",
},
{
name: "id argument",
cli: "123",
wants: DeleteOptions{Identifier: "123"},
},
{
name: "key argument",
cli: "A-Cache-Key",
wants: DeleteOptions{Identifier: "A-Cache-Key"},
},
{
name: "delete all flag",
cli: "--all",
wants: DeleteOptions{DeleteAll: true},
},
{
name: "delete all and succeed-on-no-caches flags",
cli: "--all --succeed-on-no-caches",
wants: DeleteOptions{DeleteAll: true, SucceedOnNoCaches: true},
},
{
name: "succeed-on-no-caches flag",
cli: "--succeed-on-no-caches",
wantsErr: "--succeed-on-no-caches must be used in conjunction with --all",
},
{
name: "succeed-on-no-caches flag and id argument",
cli: "--succeed-on-no-caches 123",
wantsErr: "--succeed-on-no-caches must be used in conjunction with --all",
},
{
name: "key argument and delete all flag",
cli: "cache-key --all",
wantsErr: "specify only one of cache id, cache key, or --all",
},
{
name: "id argument and delete all flag",
cli: "1 --all",
wantsErr: "specify only one of cache id, cache key, or --all",
},
{
name: "key argument with ref",
cli: "cache-key --ref refs/heads/main",
wants: DeleteOptions{Identifier: "cache-key", Ref: "refs/heads/main"},
},
{
name: "ref flag without cache key",
cli: "--ref refs/heads/main",
wantsErr: "must provide a cache key",
},
{
name: "ref flag with cache id",
cli: "123 --ref refs/heads/main",
wantsErr: "--ref cannot be used with cache ID",
},
{
name: "ref flag with all flag",
cli: "--all --ref refs/heads/main",
wantsErr: "--ref cannot be used with --all",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f := &cmdutil.Factory{}
argv, err := shlex.Split(tt.cli)
assert.NoError(t, err)
var gotOpts *DeleteOptions
cmd := NewCmdDelete(f, func(opts *DeleteOptions) 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.wantsErr != "" {
assert.EqualError(t, err, tt.wantsErr)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.wants.DeleteAll, gotOpts.DeleteAll)
assert.Equal(t, tt.wants.SucceedOnNoCaches, gotOpts.SucceedOnNoCaches)
assert.Equal(t, tt.wants.Identifier, gotOpts.Identifier)
assert.Equal(t, tt.wants.Ref, gotOpts.Ref)
})
}
}
func TestDeleteRun(t *testing.T) {
tests := []struct {
name string
opts DeleteOptions
stubs func(*httpmock.Registry)
tty bool
wantErr bool
wantErrMsg string
wantStderr string
wantStdout string
}{
{
name: "deletes cache tty",
opts: DeleteOptions{Identifier: "123"},
stubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("DELETE", "repos/OWNER/REPO/actions/caches/123"),
httpmock.StatusStringResponse(204, ""),
)
},
tty: true,
wantStdout: "✓ Deleted 1 cache from OWNER/REPO\n",
},
{
name: "deletes cache notty",
opts: DeleteOptions{Identifier: "123"},
stubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("DELETE", "repos/OWNER/REPO/actions/caches/123"),
httpmock.StatusStringResponse(204, ""),
)
},
tty: false,
wantStdout: "",
},
{
name: "non-existent cache",
opts: DeleteOptions{Identifier: "123"},
stubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("DELETE", "repos/OWNER/REPO/actions/caches/123"),
httpmock.StatusStringResponse(404, ""),
)
},
wantErr: true,
wantErrMsg: "X Could not find a cache matching 123 in OWNER/REPO",
},
{
name: "deletes all caches",
opts: DeleteOptions{DeleteAll: true},
stubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/caches"),
httpmock.JSONResponse(shared.CachePayload{
ActionsCaches: []shared.Cache{
{
Id: 123,
Key: "foo",
CreatedAt: time.Date(2021, 1, 1, 1, 1, 1, 1, time.UTC),
LastAccessedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
},
{
Id: 456,
Key: "bar",
CreatedAt: time.Date(2021, 1, 1, 1, 1, 1, 1, time.UTC),
LastAccessedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
},
},
TotalCount: 2,
}),
)
reg.Register(
httpmock.REST("DELETE", "repos/OWNER/REPO/actions/caches/123"),
httpmock.StatusStringResponse(204, ""),
)
reg.Register(
httpmock.REST("DELETE", "repos/OWNER/REPO/actions/caches/456"),
httpmock.StatusStringResponse(204, ""),
)
},
tty: true,
wantStdout: "✓ Deleted 2 caches from OWNER/REPO\n",
},
{
name: "attempts to delete all caches but api errors",
opts: DeleteOptions{DeleteAll: true},
stubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/caches"),
httpmock.StatusStringResponse(500, ""),
)
},
tty: true,
wantErr: true,
wantErrMsg: "HTTP 500 (https://api.github.com/repos/OWNER/REPO/actions/caches?per_page=100)",
},
{
name: "displays delete error",
opts: DeleteOptions{Identifier: "123"},
stubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("DELETE", "repos/OWNER/REPO/actions/caches/123"),
httpmock.StatusStringResponse(500, ""),
)
},
wantErr: true,
wantErrMsg: "X Failed to delete cache: HTTP 500 (https://api.github.com/repos/OWNER/REPO/actions/caches/123)",
},
{
name: "keys must be percent-encoded before being used as query params",
opts: DeleteOptions{Identifier: "a weird_cache+key"},
stubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.QueryMatcher("DELETE", "repos/OWNER/REPO/actions/caches", url.Values{
"key": []string{"a weird_cache+key"},
}),
httpmock.JSONResponse(shared.CachePayload{
TotalCount: 1,
}),
)
},
tty: true,
wantStdout: "✓ Deleted 1 cache from OWNER/REPO\n",
},
{
name: "deletes multiple caches by key",
opts: DeleteOptions{Identifier: "shared-cache-key"},
stubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.QueryMatcher("DELETE", "repos/OWNER/REPO/actions/caches", url.Values{
"key": []string{"shared-cache-key"},
}),
httpmock.JSONResponse(shared.CachePayload{
TotalCount: 5,
}),
)
},
tty: true,
wantStdout: "✓ Deleted 5 caches from OWNER/REPO\n",
},
{
name: "no caches to delete when deleting all",
opts: DeleteOptions{DeleteAll: true},
stubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/caches"),
httpmock.JSONResponse(shared.CachePayload{
ActionsCaches: []shared.Cache{},
TotalCount: 0,
}),
)
},
tty: false,
wantErr: true,
wantErrMsg: "X No caches to delete",
},
{
name: "no caches to delete when deleting all but succeed on no cache tty",
opts: DeleteOptions{DeleteAll: true, SucceedOnNoCaches: true},
stubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/caches"),
httpmock.JSONResponse(shared.CachePayload{
ActionsCaches: []shared.Cache{},
TotalCount: 0,
}),
)
},
tty: true,
wantErr: false,
wantStdout: "✓ No caches to delete\n",
},
{
name: "no caches to delete when deleting all but succeed on no cache non-tty",
opts: DeleteOptions{DeleteAll: true, SucceedOnNoCaches: true},
stubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/caches"),
httpmock.JSONResponse(shared.CachePayload{
ActionsCaches: []shared.Cache{},
TotalCount: 0,
}),
)
},
tty: false,
wantErr: false,
wantStdout: "",
},
{
name: "deletes cache with ref tty",
opts: DeleteOptions{Identifier: "cache-key", Ref: "refs/heads/main"},
stubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.QueryMatcher("DELETE", "repos/OWNER/REPO/actions/caches", url.Values{
"key": []string{"cache-key"},
"ref": []string{"refs/heads/main"},
}),
httpmock.JSONResponse(shared.CachePayload{
TotalCount: 1,
}),
)
},
tty: true,
wantStdout: "✓ Deleted 1 cache from OWNER/REPO\n",
},
{
name: "deletes cache with ref non-tty",
opts: DeleteOptions{Identifier: "cache-key", Ref: "refs/heads/main"},
stubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.QueryMatcher("DELETE", "repos/OWNER/REPO/actions/caches", url.Values{
"key": []string{"cache-key"},
"ref": []string{"refs/heads/main"},
}),
httpmock.JSONResponse(shared.CachePayload{
TotalCount: 1,
}),
)
},
tty: false,
wantStdout: "",
},
{
name: "deletes multiple caches by key and ref",
opts: DeleteOptions{Identifier: "cache-key", Ref: "refs/heads/feature"},
stubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.QueryMatcher("DELETE", "repos/OWNER/REPO/actions/caches", url.Values{
"key": []string{"cache-key"},
"ref": []string{"refs/heads/feature"},
}),
httpmock.JSONResponse(shared.CachePayload{
TotalCount: 3,
}),
)
},
tty: true,
wantStdout: "✓ Deleted 3 caches from OWNER/REPO\n",
},
{
// As of now, the API returns HTTP 404 for invalid or non-existent refs.
name: "cache key exists but ref is invalid/not-found",
opts: DeleteOptions{Identifier: "existing-cache-key", Ref: "invalid-ref"},
stubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.QueryMatcher("DELETE", "repos/OWNER/REPO/actions/caches", url.Values{
"key": []string{"existing-cache-key"},
"ref": []string{"invalid-ref"},
}),
httpmock.StatusStringResponse(404, ""),
)
},
wantErr: true,
wantErrMsg: "X Could not find a cache matching existing-cache-key (with ref invalid-ref) in OWNER/REPO",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
if tt.stubs != nil {
tt.stubs(reg)
}
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdoutTTY(tt.tty)
ios.SetStdinTTY(tt.tty)
ios.SetStderrTTY(tt.tty)
tt.opts.IO = ios
tt.opts.BaseRepo = func() (ghrepo.Interface, error) {
return ghrepo.New("OWNER", "REPO"), nil
}
defer reg.Verify(t)
err := deleteRun(&tt.opts)
if tt.wantErr {
if tt.wantErrMsg != "" {
assert.EqualError(t, err, tt.wantErrMsg)
} else {
assert.Error(t, err)
}
} 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/cache/list/list_test.go | pkg/cmd/cache/list/list_test.go | package list
import (
"bytes"
"fmt"
"net/http"
"testing"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmd/cache/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 TestNewCmdList(t *testing.T) {
tests := []struct {
name string
input string
wants ListOptions
wantsErr string
}{
{
name: "no arguments",
input: "",
wants: ListOptions{
Limit: 30,
Order: "desc",
Sort: "last_accessed_at",
Key: "",
Ref: "",
},
},
{
name: "with limit",
input: "--limit 100",
wants: ListOptions{
Limit: 100,
Order: "desc",
Sort: "last_accessed_at",
Key: "",
Ref: "",
},
},
{
name: "invalid limit",
input: "-L 0",
wantsErr: "invalid limit: 0",
},
{
name: "with sort",
input: "--sort created_at",
wants: ListOptions{
Limit: 30,
Order: "desc",
Sort: "created_at",
Key: "",
Ref: "",
},
},
{
name: "with order",
input: "--order asc",
wants: ListOptions{
Limit: 30,
Order: "asc",
Sort: "last_accessed_at",
Key: "",
Ref: "",
},
},
{
name: "with key",
input: "--key cache-key-prefix-",
wants: ListOptions{
Limit: 30,
Order: "desc",
Sort: "last_accessed_at",
Key: "cache-key-prefix-",
Ref: "",
},
},
{
name: "with ref",
input: "--ref refs/heads/main",
wants: ListOptions{
Limit: 30,
Order: "desc",
Sort: "last_accessed_at",
Key: "",
Ref: "refs/heads/main",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f := &cmdutil.Factory{}
argv, err := shlex.Split(tt.input)
assert.NoError(t, err)
var gotOpts *ListOptions
cmd := NewCmdList(f, func(opts *ListOptions) 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.wantsErr != "" {
assert.EqualError(t, err, tt.wantsErr)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.wants.Limit, gotOpts.Limit)
assert.Equal(t, tt.wants.Sort, gotOpts.Sort)
assert.Equal(t, tt.wants.Order, gotOpts.Order)
assert.Equal(t, tt.wants.Key, gotOpts.Key)
})
}
}
func TestListRun(t *testing.T) {
var now = time.Date(2023, 1, 1, 1, 1, 1, 1, time.UTC)
tests := []struct {
name string
opts ListOptions
stubs func(*httpmock.Registry)
tty bool
wantErr bool
wantErrMsg string
wantStderr string
wantStdout string
}{
{
name: "displays results tty",
tty: true,
stubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/caches"),
httpmock.JSONResponse(shared.CachePayload{
ActionsCaches: []shared.Cache{
{
Id: 1,
Key: "foo",
CreatedAt: time.Date(2021, 1, 1, 1, 1, 1, 1, time.UTC),
LastAccessedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
SizeInBytes: 100,
},
{
Id: 2,
Key: "bar",
CreatedAt: time.Date(2021, 1, 1, 1, 1, 1, 1, time.UTC),
LastAccessedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
SizeInBytes: 1024,
},
},
TotalCount: 2,
}),
)
},
wantStdout: heredoc.Doc(`
Showing 2 of 2 caches in OWNER/REPO
ID KEY SIZE CREATED ACCESSED
1 foo 100 B about 2 years ago about 1 year ago
2 bar 1.00 KiB about 2 years ago about 1 year ago
`),
},
{
name: "displays results non-tty",
tty: false,
stubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/caches"),
httpmock.JSONResponse(shared.CachePayload{
ActionsCaches: []shared.Cache{
{
Id: 1,
Key: "foo",
CreatedAt: time.Date(2021, 1, 1, 1, 1, 1, 1, time.UTC),
LastAccessedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
SizeInBytes: 100,
},
{
Id: 2,
Key: "bar",
CreatedAt: time.Date(2021, 1, 1, 1, 1, 1, 1, time.UTC),
LastAccessedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
SizeInBytes: 1024,
},
},
TotalCount: 2,
}),
)
},
wantStdout: "1\tfoo\t100 B\t2021-01-01T01:01:01Z\t2022-01-01T01:01:01Z\n2\tbar\t1.00 KiB\t2021-01-01T01:01:01Z\t2022-01-01T01:01:01Z\n",
},
{
name: "only requests caches with the provided key prefix",
opts: ListOptions{
Key: "test-key",
},
stubs: func(reg *httpmock.Registry) {
reg.Register(
func(req *http.Request) bool {
return req.URL.Query().Get("key") == "test-key"
},
httpmock.JSONResponse(shared.CachePayload{
ActionsCaches: []shared.Cache{},
TotalCount: 0,
}))
},
// We could put anything here, we're really asserting that the key is passed
// to the API.
wantErr: true,
wantErrMsg: "No caches found in OWNER/REPO",
},
{
name: "only requests caches with the provided ref",
opts: ListOptions{
Ref: "refs/heads/main",
},
stubs: func(reg *httpmock.Registry) {
reg.Register(
func(req *http.Request) bool {
return req.URL.Query().Get("ref") == "refs/heads/main"
},
httpmock.JSONResponse(shared.CachePayload{
ActionsCaches: []shared.Cache{},
TotalCount: 0,
}))
},
// We could put anything here, we're really asserting that the key is passed
// to the API.
wantErr: true,
wantErrMsg: "No caches found in OWNER/REPO",
},
{
name: "displays no results when there is a tty",
tty: true,
stubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/caches"),
httpmock.JSONResponse(shared.CachePayload{
ActionsCaches: []shared.Cache{},
TotalCount: 0,
}),
)
},
wantErr: true,
wantErrMsg: "No caches found in OWNER/REPO",
},
{
name: "displays list error",
stubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/caches"),
httpmock.StatusStringResponse(404, "Not Found"),
)
},
wantErr: true,
wantErrMsg: "X Failed to get caches: HTTP 404 (https://api.github.com/repos/OWNER/REPO/actions/caches?per_page=100)",
},
{
name: "calls the exporter when requested",
opts: ListOptions{
Exporter: &verboseExporter{},
},
stubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/caches"),
httpmock.JSONResponse(shared.CachePayload{
ActionsCaches: []shared.Cache{
{
Id: 1,
Key: "foo",
CreatedAt: time.Date(2021, 1, 1, 1, 1, 1, 1, time.UTC),
LastAccessedAt: time.Date(2022, 1, 1, 1, 1, 1, 1, time.UTC),
SizeInBytes: 100,
},
},
TotalCount: 1,
}),
)
},
wantErr: false,
wantStdout: "[{CreatedAt:2021-01-01 01:01:01.000000001 +0000 UTC Id:1 Key:foo LastAccessedAt:2022-01-01 01:01:01.000000001 +0000 UTC Ref: SizeInBytes:100 Version:}]",
},
{
name: "calls the exporter even when there are no results",
opts: ListOptions{
Exporter: &verboseExporter{},
},
stubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/caches"),
httpmock.JSONResponse(shared.CachePayload{
ActionsCaches: []shared.Cache{},
TotalCount: 0,
}),
)
},
wantErr: false,
wantStdout: "[]",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
if tt.stubs != nil {
tt.stubs(reg)
}
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdoutTTY(tt.tty)
ios.SetStdinTTY(tt.tty)
ios.SetStderrTTY(tt.tty)
tt.opts.IO = ios
tt.opts.Now = now
tt.opts.BaseRepo = func() (ghrepo.Interface, error) {
return ghrepo.New("OWNER", "REPO"), nil
}
defer reg.Verify(t)
err := listRun(&tt.opts)
if tt.wantErr {
if tt.wantErrMsg != "" {
assert.EqualError(t, err, tt.wantErrMsg)
} else {
assert.Error(t, err)
}
} else {
assert.NoError(t, err)
}
assert.Equal(t, tt.wantStdout, stdout.String())
assert.Equal(t, tt.wantStderr, stderr.String())
})
}
}
// The verboseExporter just writes data formatted as %+v to stdout.
// This allows for easy assertion on the data provided to the exporter.
type verboseExporter struct{}
func (e *verboseExporter) Fields() []string {
return nil
}
func (e *verboseExporter) Write(io *iostreams.IOStreams, data interface{}) error {
_, err := io.Out.Write([]byte(fmt.Sprintf("%+v", data)))
if err != nil {
return err
}
return nil
}
func Test_humanFileSize(t *testing.T) {
tests := []struct {
name string
size int64
want string
}{
{
name: "min bytes",
size: 1,
want: "1 B",
},
{
name: "max bytes",
size: 1023,
want: "1023 B",
},
{
name: "min kibibytes",
size: 1024,
want: "1.00 KiB",
},
{
name: "max kibibytes",
size: 1024*1024 - 1,
want: "1023.99 KiB",
},
{
name: "min mibibytes",
size: 1024 * 1024,
want: "1.00 MiB",
},
{
name: "fractional mibibytes",
size: 1024*1024*12 + 1024*350,
want: "12.34 MiB",
},
{
name: "max mibibytes",
size: 1024*1024*1024 - 1,
want: "1023.99 MiB",
},
{
name: "min gibibytes",
size: 1024 * 1024 * 1024,
want: "1.00 GiB",
},
{
name: "fractional gibibytes",
size: 1024 * 1024 * 1024 * 1.5,
want: "1.50 GiB",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := humanFileSize(tt.size); got != tt.want {
t.Errorf("humanFileSize() = %v, want %v", got, tt.want)
}
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/cache/list/list.go | pkg/cmd/cache/list/list.go | package list
import (
"fmt"
"net/http"
"strings"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/tableprinter"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/cmd/cache/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type ListOptions struct {
BaseRepo func() (ghrepo.Interface, error)
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
Exporter cmdutil.Exporter
Now time.Time
Limit int
Order string
Sort string
Key string
Ref string
}
func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Command {
opts := ListOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
}
cmd := &cobra.Command{
Use: "list",
Short: "List GitHub Actions caches",
Example: heredoc.Doc(`
# List caches for current repository
$ gh cache list
# List caches for specific repository
$ gh cache list --repo cli/cli
# List caches sorted by least recently accessed
$ gh cache list --sort last_accessed_at --order asc
# List caches that have keys matching a prefix (or that match exactly)
$ gh cache list --key key-prefix
# List caches for a specific branch, replace <branch-name> with the actual branch name
$ gh cache list --ref refs/heads/<branch-name>
# List caches for a specific pull request, replace <pr-number> with the actual pull request number
$ gh cache list --ref refs/pull/<pr-number>/merge
`),
Aliases: []string{"ls"},
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
// support `-R, --repo` override
opts.BaseRepo = f.BaseRepo
if opts.Limit < 1 {
return cmdutil.FlagErrorf("invalid limit: %v", opts.Limit)
}
if runF != nil {
return runF(&opts)
}
return listRun(&opts)
},
}
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum number of caches to fetch")
cmdutil.StringEnumFlag(cmd, &opts.Order, "order", "O", "desc", []string{"asc", "desc"}, "Order of caches returned")
cmdutil.StringEnumFlag(cmd, &opts.Sort, "sort", "S", "last_accessed_at", []string{"created_at", "last_accessed_at", "size_in_bytes"}, "Sort fetched caches")
cmd.Flags().StringVarP(&opts.Key, "key", "k", "", "Filter by cache key prefix")
cmd.Flags().StringVarP(&opts.Ref, "ref", "r", "", "Filter by ref, formatted as refs/heads/<branch name> or refs/pull/<number>/merge")
cmdutil.AddJSONFlags(cmd, &opts.Exporter, shared.CacheFields)
return cmd
}
func listRun(opts *ListOptions) error {
repo, err := opts.BaseRepo()
if err != nil {
return err
}
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
client := api.NewClientFromHTTP(httpClient)
cs := opts.IO.ColorScheme()
opts.IO.StartProgressIndicator()
result, err := shared.GetCaches(client, repo, shared.GetCachesOptions{Limit: opts.Limit, Sort: opts.Sort, Order: opts.Order, Key: opts.Key, Ref: opts.Ref})
opts.IO.StopProgressIndicator()
if err != nil {
return fmt.Errorf("%s Failed to get caches: %w", cs.FailureIcon(), err)
}
if len(result.ActionsCaches) == 0 && opts.Exporter == nil {
return cmdutil.NewNoResultsError(fmt.Sprintf("No caches found in %s", ghrepo.FullName(repo)))
}
if err := opts.IO.StartPager(); err == nil {
defer opts.IO.StopPager()
} else {
fmt.Fprintf(opts.IO.Out, "Failed to start pager: %v\n", err)
}
if opts.Exporter != nil {
return opts.Exporter.Write(opts.IO, result.ActionsCaches)
}
if opts.IO.IsStdoutTTY() {
fmt.Fprintf(opts.IO.Out, "\nShowing %d of %s in %s\n\n", len(result.ActionsCaches), text.Pluralize(result.TotalCount, "cache"), ghrepo.FullName(repo))
}
if opts.Now.IsZero() {
opts.Now = time.Now()
}
tp := tableprinter.New(opts.IO, tableprinter.WithHeader("ID", "KEY", "SIZE", "CREATED", "ACCESSED"))
for _, cache := range result.ActionsCaches {
tp.AddField(cs.Cyanf("%d", cache.Id))
tp.AddField(cache.Key)
tp.AddField(humanFileSize(cache.SizeInBytes))
tp.AddTimeField(opts.Now, cache.CreatedAt, cs.Muted)
tp.AddTimeField(opts.Now, cache.LastAccessedAt, cs.Muted)
tp.EndRow()
}
return tp.Render()
}
func humanFileSize(s int64) string {
if s < 1024 {
return fmt.Sprintf("%d B", s)
}
kb := float64(s) / 1024
if kb < 1024 {
return fmt.Sprintf("%s KiB", floatToString(kb, 2))
}
mb := kb / 1024
if mb < 1024 {
return fmt.Sprintf("%s MiB", floatToString(mb, 2))
}
gb := mb / 1024
return fmt.Sprintf("%s GiB", floatToString(gb, 2))
}
func floatToString(f float64, p uint8) string {
fs := fmt.Sprintf("%#f%0*s", f, p, "")
idx := strings.IndexRune(fs, '.')
return fs[:idx+int(p)+1]
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/cache/shared/shared_test.go | pkg/cmd/cache/shared/shared_test.go | package shared
import (
"bytes"
"encoding/json"
"net/http"
"strings"
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/httpmock"
)
func TestGetCaches(t *testing.T) {
tests := []struct {
name string
opts GetCachesOptions
stubs func(*httpmock.Registry)
wantsCount int
}{
{
name: "no caches",
opts: GetCachesOptions{},
stubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/caches"),
httpmock.StringResponse(`{"actions_caches": [], "total_count": 0}`),
)
},
wantsCount: 0,
},
{
name: "limits cache count",
opts: GetCachesOptions{Limit: 1},
stubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/caches"),
httpmock.StringResponse(`{"actions_caches": [{"id": 1}, {"id": 2}], "total_count": 2}`),
)
},
wantsCount: 1,
},
{
name: "negative limit returns all caches",
opts: GetCachesOptions{Limit: -1},
stubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("GET", "repos/OWNER/REPO/actions/caches"),
httpmock.StringResponse(`{"actions_caches": [{"id": 1}, {"id": 2}], "total_count": 2}`),
)
},
wantsCount: 2,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
tt.stubs(reg)
httpClient := &http.Client{Transport: reg}
client := api.NewClientFromHTTP(httpClient)
repo, err := ghrepo.FromFullName("OWNER/REPO")
assert.NoError(t, err)
result, err := GetCaches(client, repo, tt.opts)
assert.NoError(t, err)
assert.Equal(t, tt.wantsCount, len(result.ActionsCaches))
})
}
}
func TestCache_ExportData(t *testing.T) {
src := heredoc.Doc(
`
{
"id": 505,
"ref": "refs/heads/main",
"key": "Linux-node-958aff96db2d75d67787d1e634ae70b659de937b",
"version": "73885106f58cc52a7df9ec4d4a5622a5614813162cb516c759a30af6bf56e6f0",
"last_accessed_at": "2019-01-24T22:45:36.000Z",
"created_at": "2019-01-24T22:45:36.000Z",
"size_in_bytes": 1024
}
`,
)
tests := []struct {
name string
fields []string
inputJSON string
outputJSON string
}{
{
name: "basic",
fields: []string{"id", "key"},
inputJSON: src,
outputJSON: heredoc.Doc(
`
{
"id": 505,
"key": "Linux-node-958aff96db2d75d67787d1e634ae70b659de937b"
}
`,
),
},
{
name: "full",
fields: []string{"id", "ref", "key", "version", "lastAccessedAt", "createdAt", "sizeInBytes"},
inputJSON: src,
outputJSON: heredoc.Doc(
`
{
"createdAt": "2019-01-24T22:45:36Z",
"id": 505,
"key": "Linux-node-958aff96db2d75d67787d1e634ae70b659de937b",
"lastAccessedAt": "2019-01-24T22:45:36Z",
"ref": "refs/heads/main",
"sizeInBytes": 1024,
"version": "73885106f58cc52a7df9ec4d4a5622a5614813162cb516c759a30af6bf56e6f0"
}
`,
),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var cache Cache
dec := json.NewDecoder(strings.NewReader(tt.inputJSON))
require.NoError(t, dec.Decode(&cache))
exported := cache.ExportData(tt.fields)
buf := bytes.Buffer{}
enc := json.NewEncoder(&buf)
enc.SetIndent("", "\t")
require.NoError(t, enc.Encode(exported))
assert.Equal(t, tt.outputJSON, buf.String())
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/cache/shared/shared.go | pkg/cmd/cache/shared/shared.go | package shared
import (
"fmt"
"net/url"
"time"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmdutil"
)
var CacheFields = []string{
"createdAt",
"id",
"key",
"lastAccessedAt",
"ref",
"sizeInBytes",
"version",
}
type Cache struct {
CreatedAt time.Time `json:"created_at"`
Id int `json:"id"`
Key string `json:"key"`
LastAccessedAt time.Time `json:"last_accessed_at"`
Ref string `json:"ref"`
SizeInBytes int64 `json:"size_in_bytes"`
Version string `json:"version"`
}
type CachePayload struct {
ActionsCaches []Cache `json:"actions_caches"`
TotalCount int `json:"total_count"`
}
type GetCachesOptions struct {
Limit int
Order string
Sort string
Key string
Ref string
}
// Return a list of caches for a repository. Pass a negative limit to request
// all pages from the API until all caches have been fetched.
func GetCaches(client *api.Client, repo ghrepo.Interface, opts GetCachesOptions) (*CachePayload, error) {
path := fmt.Sprintf("repos/%s/actions/caches", ghrepo.FullName(repo))
perPage := 100
if opts.Limit > 0 && opts.Limit < 100 {
perPage = opts.Limit
}
path += fmt.Sprintf("?per_page=%d", perPage)
if opts.Sort != "" {
path += fmt.Sprintf("&sort=%s", opts.Sort)
}
if opts.Order != "" {
path += fmt.Sprintf("&direction=%s", opts.Order)
}
if opts.Key != "" {
path += fmt.Sprintf("&key=%s", url.QueryEscape(opts.Key))
}
if opts.Ref != "" {
path += fmt.Sprintf("&ref=%s", url.QueryEscape(opts.Ref))
}
var result *CachePayload
pagination:
for path != "" {
var response CachePayload
var err error
path, err = client.RESTWithNext(repo.RepoHost(), "GET", path, nil, &response)
if err != nil {
return nil, err
}
if result == nil {
result = &response
} else {
result.ActionsCaches = append(result.ActionsCaches, response.ActionsCaches...)
}
if opts.Limit > 0 && len(result.ActionsCaches) >= opts.Limit {
result.ActionsCaches = result.ActionsCaches[:opts.Limit]
break pagination
}
}
return result, nil
}
func (c *Cache) ExportData(fields []string) map[string]interface{} {
return cmdutil.StructExportData(c, fields)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/preview/preview.go | pkg/cmd/preview/preview.go | package preview
import (
"github.com/MakeNowJust/heredoc"
cmdPrompter "github.com/cli/cli/v2/pkg/cmd/preview/prompter"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/spf13/cobra"
)
func NewCmdPreview(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "preview <command>",
Short: "Execute previews for gh features",
Long: heredoc.Doc(`
Preview commands are for testing, demonstrative, and development purposes only.
They should be considered unstable and can change at any time.
`),
}
cmdutil.DisableAuthCheck(cmd)
cmd.AddCommand(cmdPrompter.NewCmdPrompter(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/preview/prompter/prompter.go | pkg/cmd/preview/prompter/prompter.go | package prompter
import (
"fmt"
"github.com/MakeNowJust/heredoc"
"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 prompterOptions struct {
IO *iostreams.IOStreams
Config func() (gh.Config, error)
PromptsToRun []func(prompter.Prompter, *iostreams.IOStreams) error
}
func NewCmdPrompter(f *cmdutil.Factory, runF func(*prompterOptions) error) *cobra.Command {
opts := &prompterOptions{
IO: f.IOStreams,
Config: f.Config,
}
const (
selectPrompt = "select"
multiSelectPrompt = "multi-select"
inputPrompt = "input"
passwordPrompt = "password"
confirmPrompt = "confirm"
authTokenPrompt = "auth-token"
confirmDeletionPrompt = "confirm-deletion"
inputHostnamePrompt = "input-hostname"
markdownEditorPrompt = "markdown-editor"
)
prompterTypeFuncMap := map[string]func(prompter.Prompter, *iostreams.IOStreams) error{
selectPrompt: runSelect,
multiSelectPrompt: runMultiSelect,
inputPrompt: runInput,
passwordPrompt: runPassword,
confirmPrompt: runConfirm,
authTokenPrompt: runAuthToken,
confirmDeletionPrompt: runConfirmDeletion,
inputHostnamePrompt: runInputHostname,
markdownEditorPrompt: runMarkdownEditor,
}
allPromptsOrder := []string{
selectPrompt,
multiSelectPrompt,
inputPrompt,
passwordPrompt,
confirmPrompt,
authTokenPrompt,
confirmDeletionPrompt,
inputHostnamePrompt,
markdownEditorPrompt,
}
cmd := &cobra.Command{
Use: "prompter [prompt type]",
Short: "Execute a test program to preview the prompter",
Long: heredoc.Doc(`
Execute a test program to preview the prompter.
Without an argument, all prompts will be run.
Available prompt types:
- select
- multi-select
- input
- password
- confirm
- auth-token
- confirm-deletion
- input-hostname
- markdown-editor
`),
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if runF != nil {
return runF(opts)
}
if len(args) == 0 {
// All prompts, in a fixed order
for _, promptType := range allPromptsOrder {
f := prompterTypeFuncMap[promptType]
opts.PromptsToRun = append(opts.PromptsToRun, f)
}
} else {
// Only the one specified
for _, arg := range args {
f, ok := prompterTypeFuncMap[arg]
if !ok {
return fmt.Errorf("unknown prompter type: %q", arg)
}
opts.PromptsToRun = append(opts.PromptsToRun, f)
}
}
return prompterRun(opts)
},
}
return cmd
}
func prompterRun(opts *prompterOptions) error {
editor, err := cmdutil.DetermineEditor(opts.Config)
if err != nil {
return err
}
p := prompter.New(editor, opts.IO)
for _, f := range opts.PromptsToRun {
if err := f(p, opts.IO); err != nil {
return err
}
}
return nil
}
func runSelect(p prompter.Prompter, io *iostreams.IOStreams) error {
fmt.Fprintln(io.Out, "Demonstrating Single Select")
cuisines := []string{"Italian", "Greek", "Indian", "Japanese", "American"}
favorite, err := p.Select("Favorite cuisine?", "Italian", cuisines)
if err != nil {
return err
}
fmt.Fprintf(io.Out, "Favorite cuisine: %s\n", cuisines[favorite])
return nil
}
func runMultiSelect(p prompter.Prompter, io *iostreams.IOStreams) error {
fmt.Fprintln(io.Out, "Demonstrating Multi Select")
cuisines := []string{"Italian", "Greek", "Indian", "Japanese", "American"}
favorites, err := p.MultiSelect("Favorite cuisines?", []string{}, cuisines)
if err != nil {
return err
}
for _, f := range favorites {
fmt.Fprintf(io.Out, "Favorite cuisine: %s\n", cuisines[f])
}
return nil
}
func runInput(p prompter.Prompter, io *iostreams.IOStreams) error {
fmt.Fprintln(io.Out, "Demonstrating Text Input")
text, err := p.Input("Favorite meal?", "Breakfast")
if err != nil {
return err
}
fmt.Fprintf(io.Out, "You typed: %s\n", text)
return nil
}
func runPassword(p prompter.Prompter, io *iostreams.IOStreams) error {
fmt.Fprintln(io.Out, "Demonstrating Password Input")
safeword, err := p.Password("Safe word?")
if err != nil {
return err
}
fmt.Fprintf(io.Out, "Safe word: %s\n", safeword)
return nil
}
func runConfirm(p prompter.Prompter, io *iostreams.IOStreams) error {
fmt.Fprintln(io.Out, "Demonstrating Confirmation")
confirmation, err := p.Confirm("Are you sure?", true)
if err != nil {
return err
}
fmt.Fprintf(io.Out, "Confirmation: %t\n", confirmation)
return nil
}
func runAuthToken(p prompter.Prompter, io *iostreams.IOStreams) error {
fmt.Fprintln(io.Out, "Demonstrating Auth Token (can't be blank)")
token, err := p.AuthToken()
if err != nil {
return err
}
fmt.Fprintf(io.Out, "Auth token: %s\n", token)
return nil
}
func runConfirmDeletion(p prompter.Prompter, io *iostreams.IOStreams) error {
fmt.Fprintln(io.Out, "Demonstrating Deletion Confirmation")
err := p.ConfirmDeletion("delete-me")
if err != nil {
return err
}
fmt.Fprintln(io.Out, "Item deleted")
return nil
}
func runInputHostname(p prompter.Prompter, io *iostreams.IOStreams) error {
fmt.Fprintln(io.Out, "Demonstrating Hostname")
hostname, err := p.InputHostname()
if err != nil {
return err
}
fmt.Fprintf(io.Out, "Hostname: %s\n", hostname)
return nil
}
func runMarkdownEditor(p prompter.Prompter, io *iostreams.IOStreams) error {
defaultText := "default text value"
fmt.Fprintln(io.Out, "Demonstrating Markdown Editor with blanks allowed and default text")
editorText, err := p.MarkdownEditor("Edit your text:", defaultText, true)
if err != nil {
return err
}
fmt.Fprintf(io.Out, "Returned text: %s\n\n", editorText)
fmt.Fprintln(io.Out, "Demonstrating Markdown Editor with blanks disallowed and default text")
editorText2, err := p.MarkdownEditor("Edit your text:", defaultText, false)
if err != nil {
return err
}
fmt.Fprintf(io.Out, "Returned text: %s\n\n", editorText2)
fmt.Fprintln(io.Out, "Demonstrating Markdown Editor with blanks disallowed and no default text")
editorText3, err := p.MarkdownEditor("Edit your text:", "", false)
if err != nil {
return err
}
fmt.Fprintf(io.Out, "Returned text: %s\n", editorText3)
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/root/help_topic.go | pkg/cmd/root/help_topic.go | package root
import (
"fmt"
"io"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type helpTopic struct {
name string
short string
long string
example string
}
var HelpTopics = []helpTopic{
{
name: "mintty",
short: "Information about using gh with MinTTY",
long: heredoc.Docf(`
MinTTY is the terminal emulator that comes by default with Git
for Windows. It has known issues with gh's ability to prompt a
user for input.
There are a few workarounds to make gh work with MinTTY:
- Reinstall Git for Windows, checking "Enable experimental support for pseudo consoles".
- Use a different terminal emulator with Git for Windows like Windows Terminal.
You can run %[1]sC:\Program Files\Git\bin\bash.exe%[1]s from any terminal emulator to continue
using all of the tooling in Git For Windows without MinTTY.
- Prefix invocations of gh with %[1]swinpty%[1]s, eg: %[1]swinpty gh auth login%[1]s.
NOTE: this can lead to some UI bugs.
`, "`"),
},
{
name: "environment",
short: "Environment variables that can be used with gh",
long: heredoc.Docf(`
%[1]sGH_TOKEN%[1]s, %[1]sGITHUB_TOKEN%[1]s (in order of precedence): an authentication token that will be used when
a command targets either %[1]sgithub.com%[1]s or a subdomain of %[1]sghe.com%[1]s. Setting this avoids being prompted to
authenticate and takes precedence over previously stored credentials.
%[1]sGH_ENTERPRISE_TOKEN%[1]s, %[1]sGITHUB_ENTERPRISE_TOKEN%[1]s (in order of precedence): an authentication
token that will be used when a command targets a GitHub Enterprise Server host.
%[1]sGH_HOST%[1]s: specify the GitHub hostname for commands where a hostname has not been provided, or
cannot be inferred from the context of a local Git repository. If this host was previously
authenticated with, the stored credentials will be used. Otherwise, setting %[1]sGH_TOKEN%[1]s or
%[1]sGH_ENTERPRISE_TOKEN%[1]s is required, depending on the targeted host.
%[1]sGH_REPO%[1]s: specify the GitHub repository in the %[1]s[HOST/]OWNER/REPO%[1]s format for commands
that otherwise operate on a local repository.
%[1]sGH_EDITOR%[1]s, %[1]sGIT_EDITOR%[1]s, %[1]sVISUAL%[1]s, %[1]sEDITOR%[1]s (in order of precedence): the editor tool to use
for authoring text.
%[1]sGH_BROWSER%[1]s, %[1]sBROWSER%[1]s (in order of precedence): the web browser to use for opening links.
%[1]sGH_DEBUG%[1]s: set to a truthy value to enable verbose output on standard error. Set to %[1]sapi%[1]s
to additionally log details of HTTP traffic.
%[1]sDEBUG%[1]s (deprecated): set to %[1]s1%[1]s, %[1]strue%[1]s, or %[1]syes%[1]s to enable verbose output on standard
error.
%[1]sGH_PAGER%[1]s, %[1]sPAGER%[1]s (in order of precedence): a terminal paging program to send standard output
to, e.g. %[1]sless%[1]s.
%[1]sGLAMOUR_STYLE%[1]s: the style to use for rendering Markdown. See
<https://github.com/charmbracelet/glamour#styles>
%[1]sNO_COLOR%[1]s: set to any value to avoid printing ANSI escape sequences for color output.
%[1]sCLICOLOR%[1]s: set to %[1]s0%[1]s to disable printing ANSI colors in output.
%[1]sCLICOLOR_FORCE%[1]s: set to a value other than %[1]s0%[1]s to keep ANSI colors in output
even when the output is piped.
%[1]sGH_COLOR_LABELS%[1]s: set to any value to display labels using their RGB hex color codes in terminals that
support truecolor.
%[1]sGH_ACCESSIBLE_COLORS%[1]s (preview): set to a truthy value to use customizable, 4-bit accessible colors.
%[1]sGH_FORCE_TTY%[1]s: set to any value to force terminal-style output even when the output is
redirected. When the value is a number, it is interpreted as the number of columns
available in the viewport. When the value is a percentage, it will be applied against
the number of columns available in the current viewport.
%[1]sGH_NO_UPDATE_NOTIFIER%[1]s: set to any value to disable GitHub CLI update notifications.
When any command is executed, gh checks for new versions once every 24 hours.
If a newer version was found, an upgrade notice is displayed on standard error.
%[1]sGH_NO_EXTENSION_UPDATE_NOTIFIER%[1]s: set to any value to disable GitHub CLI extension update notifications.
When an extension is executed, gh checks for new versions for the executed extension once every 24 hours.
If a newer version was found, an upgrade notice is displayed on standard error.
%[1]sGH_CONFIG_DIR%[1]s: the directory where gh will store configuration files. If not specified,
the default value will be one of the following paths (in order of precedence):
- %[1]s$XDG_CONFIG_HOME/gh%[1]s (if %[1]s$XDG_CONFIG_HOME%[1]s is set),
- %[1]s$AppData/GitHub CLI%[1]s (on Windows if %[1]s$AppData%[1]s is set), or
- %[1]s$HOME/.config/gh%[1]s.
%[1]sGH_PROMPT_DISABLED%[1]s: set to any value to disable interactive prompting in the terminal.
%[1]sGH_PATH%[1]s: set the path to the gh executable, useful for when gh can not properly determine
its own path such as in the cygwin terminal.
%[1]sGH_MDWIDTH%[1]s: default maximum width for markdown render wrapping. The max width of lines
wrapped on the terminal will be taken as the lesser of the terminal width, this value, or 120 if
not specified. This value is used, for example, with %[1]spr view%[1]s subcommand.
%[1]sGH_ACCESSIBLE_PROMPTER%[1]s (preview): set to a truthy value to enable prompts that are
more compatible with speech synthesis and braille screen readers.
%[1]sGH_SPINNER_DISABLED%[1]s: set to a truthy value to replace the spinner animation with
a textual progress indicator.
`, "`"),
},
{
name: "reference",
short: "A comprehensive reference of all gh commands",
},
{
name: "formatting",
short: "Formatting options for JSON data exported from gh",
long: heredoc.Docf(`
By default, the result of %[1]sgh%[1]s commands are output in line-based plain text format.
Some commands support passing the %[1]s--json%[1]s flag, which converts the output to JSON format.
Once in JSON, the output can be further formatted according to a required formatting string by
adding either the %[1]s--jq%[1]s or %[1]s--template%[1]s flag. This is useful for selecting a subset of data,
creating new data structures, displaying the data in a different format, or as input to another
command line script.
The %[1]s--json%[1]s flag requires a comma separated list of fields to fetch. To view the possible JSON
field names for a command omit the string argument to the %[1]s--json%[1]s flag when you run the command.
Note that you must pass the %[1]s--json%[1]s flag and field names to use the %[1]s--jq%[1]s or %[1]s--template%[1]s flags.
The %[1]s--jq%[1]s flag requires a string argument in jq query syntax, and will only print
those JSON values which match the query. jq queries can be used to select elements from an
array, fields from an object, create a new array, and more. The %[1]sjq%[1]s utility does not need
to be installed on the system to use this formatting directive. When connected to a terminal,
the output is automatically pretty-printed. To learn about jq query syntax, see:
<https://jqlang.github.io/jq/manual/>
The %[1]s--template%[1]s flag requires a string argument in Go template syntax, and will only print
those JSON values which match the query.
In addition to the Go template functions in the standard library, the following functions can be used
with this formatting directive:
- %[1]sautocolor%[1]s: like %[1]scolor%[1]s, but only emits color to terminals
- %[1]scolor <style> <input>%[1]s: colorize input using <https://github.com/mgutz/ansi>
- %[1]sjoin <sep> <list>%[1]s: joins values in the list using a separator
- %[1]spluck <field> <list>%[1]s: collects values of a field from all items in the input
- %[1]stablerow <fields>...%[1]s: aligns fields in output vertically as a table
- %[1]stablerender%[1]s: renders fields added by tablerow in place
- %[1]stimeago <time>%[1]s: renders a timestamp as relative to now
- %[1]stimefmt <format> <time>%[1]s: formats a timestamp using Go's %[1]sTime.Format%[1]s function
- %[1]struncate <length> <input>%[1]s: ensures input fits within length
- %[1]shyperlink <url> <text>%[1]s: renders a terminal hyperlink
The following Sprig template library functions can also be used with this formatting directive:
- %[1]scontains <arg> <string>%[1]s: checks if %[1]sstring%[1]s contains %[1]sarg%[1]s
- %[1]shasPrefix <prefix> <string>%[1]s: checks if %[1]sstring%[1]s starts with %[1]sprefix%[1]s
- %[1]shasSuffix <suffix> <string>%[1]s: checks if %[1]sstring%[1]s ends with %[1]ssuffix%[1]s
- %[1]sregexMatch <regex> <string>%[1]s: checks if %[1]sstring%[1]s has any matches for %[1]sregex%[1]s
For more information about the Sprig library, see <https://masterminds.github.io/sprig/>.
To learn more about Go templates, see: <https://golang.org/pkg/text/template/>.
`, "`"),
example: heredoc.Doc(`
# Default output format
$ gh pr list
Showing 23 of 23 open pull requests in cli/cli
#123 A helpful contribution contribution-branch about 1 day ago
#124 Improve the docs docs-branch about 2 days ago
#125 An exciting new feature feature-branch about 2 days ago
# Adding the --json flag with a list of field names
$ gh pr list --json number,title,author
[
{
"author": {
"login": "monalisa"
},
"number": 123,
"title": "A helpful contribution"
},
{
"author": {
"login": "codercat"
},
"number": 124,
"title": "Improve the docs"
},
{
"author": {
"login": "cli-maintainer"
},
"number": 125,
"title": "An exciting new feature"
}
]
# Adding the --jq flag and selecting fields from the array
$ gh pr list --json author --jq '.[].author.login'
monalisa
codercat
cli-maintainer
# --jq can be used to implement more complex filtering and output changes
$ gh issue list --json number,title,labels --jq \
'map(select((.labels | length) > 0)) # must have labels
| map(.labels = (.labels | map(.name))) # show only the label names
| .[:3] # select the first 3 results'
[
{
"labels": [
"enhancement",
"needs triage"
],
"number": 123,
"title": "A helpful contribution"
},
{
"labels": [
"help wanted",
"docs",
"good first issue"
],
"number": 125,
"title": "Improve the docs"
},
{
"labels": [
"enhancement",
],
"number": 7221,
"title": "An exciting new feature"
}
]
# Using the --template flag with the hyperlink helper
$ gh issue list --json title,url --template '{{range .}}{{hyperlink .url .title}}{{"\n"}}{{end}}'
# Adding the --template flag and modifying the display format
$ gh pr list --json number,title,headRefName,updatedAt --template \
'{{range .}}{{tablerow (printf "#%v" .number | autocolor "green") .title .headRefName (timeago .updatedAt)}}{{end}}'
#123 A helpful contribution contribution-branch about 1 day ago
#124 Improve the docs docs-branch about 2 days ago
#125 An exciting new feature feature-branch about 2 days ago
# A more complex example with the --template flag which formats a pull request using multiple tables with headers
$ gh pr view 3519 --json number,title,body,reviews,assignees --template \
'{{printf "#%v" .number}} {{.title}}
{{.body}}
{{tablerow "ASSIGNEE" "NAME"}}{{range .assignees}}{{tablerow .login .name}}{{end}}{{tablerender}}
{{tablerow "REVIEWER" "STATE" "COMMENT"}}{{range .reviews}}{{tablerow .author.login .state .body}}{{end}}
'
#3519 Add table and helper template functions
Resolves #3488
ASSIGNEE NAME
mislav Mislav Marohnić
REVIEWER STATE COMMENT
mislav COMMENTED This is going along great! Thanks for working on this ❤️
`),
},
{
name: "exit-codes",
short: "Exit codes used by gh",
long: heredoc.Doc(`
gh follows normal conventions regarding exit codes.
- If a command completes successfully, the exit code will be 0
- If a command fails for any reason, the exit code will be 1
- If a command is running but gets cancelled, the exit code will be 2
- If a command requires authentication, the exit code will be 4
NOTE: It is possible that a particular command may have more exit codes, so it is a good
practice to check documentation for the command if you are relying on exit codes to
control some behavior.
`),
},
}
func NewCmdHelpTopic(ios *iostreams.IOStreams, ht helpTopic) *cobra.Command {
cmd := &cobra.Command{
Use: ht.name,
Short: ht.short,
Long: ht.long,
Example: ht.example,
Hidden: true,
Annotations: map[string]string{
"markdown:generate": "true",
"markdown:basename": "gh_help_" + ht.name,
},
}
cmd.SetUsageFunc(func(c *cobra.Command) error {
return helpTopicUsageFunc(ios.ErrOut, c)
})
cmd.SetHelpFunc(func(c *cobra.Command, _ []string) {
helpTopicHelpFunc(ios.Out, c)
})
return cmd
}
func helpTopicHelpFunc(w io.Writer, command *cobra.Command) {
fmt.Fprint(w, command.Long)
if command.Example != "" {
fmt.Fprintf(w, "\n\nEXAMPLES\n")
fmt.Fprint(w, text.Indent(command.Example, " "))
}
}
func helpTopicUsageFunc(w io.Writer, command *cobra.Command) error {
fmt.Fprintf(w, "Usage: gh help %s", command.Use)
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/root/root.go | pkg/cmd/root/root.go | package root
import (
"fmt"
"os"
"strings"
"github.com/MakeNowJust/heredoc"
accessibilityCmd "github.com/cli/cli/v2/pkg/cmd/accessibility"
actionsCmd "github.com/cli/cli/v2/pkg/cmd/actions"
agentTaskCmd "github.com/cli/cli/v2/pkg/cmd/agent-task"
aliasCmd "github.com/cli/cli/v2/pkg/cmd/alias"
"github.com/cli/cli/v2/pkg/cmd/alias/shared"
apiCmd "github.com/cli/cli/v2/pkg/cmd/api"
attestationCmd "github.com/cli/cli/v2/pkg/cmd/attestation"
authCmd "github.com/cli/cli/v2/pkg/cmd/auth"
browseCmd "github.com/cli/cli/v2/pkg/cmd/browse"
cacheCmd "github.com/cli/cli/v2/pkg/cmd/cache"
codespaceCmd "github.com/cli/cli/v2/pkg/cmd/codespace"
completionCmd "github.com/cli/cli/v2/pkg/cmd/completion"
configCmd "github.com/cli/cli/v2/pkg/cmd/config"
extensionCmd "github.com/cli/cli/v2/pkg/cmd/extension"
"github.com/cli/cli/v2/pkg/cmd/factory"
gistCmd "github.com/cli/cli/v2/pkg/cmd/gist"
gpgKeyCmd "github.com/cli/cli/v2/pkg/cmd/gpg-key"
issueCmd "github.com/cli/cli/v2/pkg/cmd/issue"
labelCmd "github.com/cli/cli/v2/pkg/cmd/label"
orgCmd "github.com/cli/cli/v2/pkg/cmd/org"
prCmd "github.com/cli/cli/v2/pkg/cmd/pr"
previewCmd "github.com/cli/cli/v2/pkg/cmd/preview"
projectCmd "github.com/cli/cli/v2/pkg/cmd/project"
releaseCmd "github.com/cli/cli/v2/pkg/cmd/release"
repoCmd "github.com/cli/cli/v2/pkg/cmd/repo"
creditsCmd "github.com/cli/cli/v2/pkg/cmd/repo/credits"
rulesetCmd "github.com/cli/cli/v2/pkg/cmd/ruleset"
runCmd "github.com/cli/cli/v2/pkg/cmd/run"
searchCmd "github.com/cli/cli/v2/pkg/cmd/search"
secretCmd "github.com/cli/cli/v2/pkg/cmd/secret"
sshKeyCmd "github.com/cli/cli/v2/pkg/cmd/ssh-key"
statusCmd "github.com/cli/cli/v2/pkg/cmd/status"
variableCmd "github.com/cli/cli/v2/pkg/cmd/variable"
versionCmd "github.com/cli/cli/v2/pkg/cmd/version"
workflowCmd "github.com/cli/cli/v2/pkg/cmd/workflow"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/google/shlex"
"github.com/spf13/cobra"
)
type AuthError struct {
err error
}
func (ae *AuthError) Error() string {
return ae.err.Error()
}
func NewCmdRoot(f *cmdutil.Factory, version, buildDate string) (*cobra.Command, error) {
io := f.IOStreams
cfg, err := f.Config()
if err != nil {
return nil, fmt.Errorf("failed to read configuration: %s\n", err)
}
cmd := &cobra.Command{
Use: "gh <command> <subcommand> [flags]",
Short: "GitHub CLI",
Long: `Work seamlessly with GitHub from the command line.`,
Example: heredoc.Doc(`
$ gh issue create
$ gh repo clone cli/cli
$ gh pr checkout 321
`),
Annotations: map[string]string{
"versionInfo": versionCmd.Format(version, buildDate),
},
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
// require that the user is authenticated before running most commands
if cmdutil.IsAuthCheckEnabled(cmd) && !cmdutil.CheckAuth(cfg) {
parent := cmd.Parent()
if parent != nil && parent.Use == "codespace" {
fmt.Fprintln(io.ErrOut, "To get started with GitHub CLI, please run: gh auth login -s codespace")
} else {
fmt.Fprint(io.ErrOut, authHelp())
}
return &AuthError{}
}
return nil
},
}
// cmd.SetOut(f.IOStreams.Out) // can't use due to https://github.com/spf13/cobra/issues/1708
// cmd.SetErr(f.IOStreams.ErrOut) // just let it default to os.Stderr instead
cmd.PersistentFlags().Bool("help", false, "Show help for command")
// override Cobra's default behaviors unless an opt-out has been set
if os.Getenv("GH_COBRA") == "" {
cmd.SilenceErrors = true
cmd.SilenceUsage = true
// this --version flag is checked in rootHelpFunc
cmd.Flags().Bool("version", false, "Show gh version")
cmd.SetHelpFunc(func(c *cobra.Command, args []string) {
rootHelpFunc(f, c, args)
})
cmd.SetUsageFunc(func(c *cobra.Command) error {
return rootUsageFunc(f.IOStreams.ErrOut, c)
})
cmd.SetFlagErrorFunc(rootFlagErrorFunc)
}
cmd.AddGroup(&cobra.Group{
ID: "core",
Title: "Core commands",
})
cmd.AddGroup(&cobra.Group{
ID: "actions",
Title: "GitHub Actions commands",
})
cmd.AddGroup(&cobra.Group{
ID: "extension",
Title: "Extension commands",
})
// Child commands
cmd.AddCommand(versionCmd.NewCmdVersion(f, version, buildDate))
cmd.AddCommand(accessibilityCmd.NewCmdAccessibility(f))
cmd.AddCommand(actionsCmd.NewCmdActions(f))
cmd.AddCommand(aliasCmd.NewCmdAlias(f))
cmd.AddCommand(authCmd.NewCmdAuth(f))
cmd.AddCommand(attestationCmd.NewCmdAttestation(f))
cmd.AddCommand(configCmd.NewCmdConfig(f))
cmd.AddCommand(creditsCmd.NewCmdCredits(f, nil))
cmd.AddCommand(gistCmd.NewCmdGist(f))
cmd.AddCommand(gpgKeyCmd.NewCmdGPGKey(f))
cmd.AddCommand(completionCmd.NewCmdCompletion(f.IOStreams))
cmd.AddCommand(extensionCmd.NewCmdExtension(f))
cmd.AddCommand(searchCmd.NewCmdSearch(f))
cmd.AddCommand(secretCmd.NewCmdSecret(f))
cmd.AddCommand(variableCmd.NewCmdVariable(f))
cmd.AddCommand(sshKeyCmd.NewCmdSSHKey(f))
cmd.AddCommand(statusCmd.NewCmdStatus(f, nil))
cmd.AddCommand(codespaceCmd.NewCmdCodespace(f))
cmd.AddCommand(projectCmd.NewCmdProject(f))
cmd.AddCommand(previewCmd.NewCmdPreview(f))
// below here at the commands that require the "intelligent" BaseRepo resolver
repoResolvingCmdFactory := *f
repoResolvingCmdFactory.BaseRepo = factory.SmartBaseRepoFunc(f)
cmd.AddCommand(agentTaskCmd.NewCmdAgentTask(&repoResolvingCmdFactory))
cmd.AddCommand(browseCmd.NewCmdBrowse(&repoResolvingCmdFactory, nil))
cmd.AddCommand(prCmd.NewCmdPR(&repoResolvingCmdFactory))
cmd.AddCommand(orgCmd.NewCmdOrg(&repoResolvingCmdFactory))
cmd.AddCommand(issueCmd.NewCmdIssue(&repoResolvingCmdFactory))
cmd.AddCommand(releaseCmd.NewCmdRelease(&repoResolvingCmdFactory))
cmd.AddCommand(repoCmd.NewCmdRepo(&repoResolvingCmdFactory))
cmd.AddCommand(rulesetCmd.NewCmdRuleset(&repoResolvingCmdFactory))
cmd.AddCommand(runCmd.NewCmdRun(&repoResolvingCmdFactory))
cmd.AddCommand(workflowCmd.NewCmdWorkflow(&repoResolvingCmdFactory))
cmd.AddCommand(labelCmd.NewCmdLabel(&repoResolvingCmdFactory))
cmd.AddCommand(cacheCmd.NewCmdCache(&repoResolvingCmdFactory))
cmd.AddCommand(apiCmd.NewCmdApi(&repoResolvingCmdFactory, nil))
// Help topics
var referenceCmd *cobra.Command
for _, ht := range HelpTopics {
helpTopicCmd := NewCmdHelpTopic(f.IOStreams, ht)
cmd.AddCommand(helpTopicCmd)
// See bottom of the function for why we explicitly care about the reference cmd
if ht.name == "reference" {
referenceCmd = helpTopicCmd
}
}
// Extensions
em := f.ExtensionManager
for _, e := range em.List() {
extensionCmd := NewCmdExtension(io, em, e, nil)
cmd.AddCommand(extensionCmd)
}
// Aliases
aliases := cfg.Aliases()
validAliasName := shared.ValidAliasNameFunc(cmd)
validAliasExpansion := shared.ValidAliasExpansionFunc(cmd)
for k, v := range aliases.All() {
aliasName := k
aliasValue := v
if validAliasName(aliasName) && validAliasExpansion(aliasValue) {
split, _ := shlex.Split(aliasName)
parentCmd, parentArgs, _ := cmd.Find(split)
if !parentCmd.ContainsGroup("alias") {
parentCmd.AddGroup(&cobra.Group{
ID: "alias",
Title: "Alias commands",
})
}
if strings.HasPrefix(aliasValue, "!") {
shellAliasCmd := NewCmdShellAlias(io, parentArgs[0], aliasValue)
parentCmd.AddCommand(shellAliasCmd)
} else {
aliasCmd := NewCmdAlias(io, parentArgs[0], aliasValue)
split, _ := shlex.Split(aliasValue)
child, _, _ := cmd.Find(split)
aliasCmd.SetUsageFunc(func(_ *cobra.Command) error {
return rootUsageFunc(f.IOStreams.ErrOut, child)
})
aliasCmd.SetHelpFunc(func(_ *cobra.Command, args []string) {
rootHelpFunc(f, child, args)
})
parentCmd.AddCommand(aliasCmd)
}
}
}
cmdutil.DisableAuthCheck(cmd)
// The reference command produces paged output that displays information on every other command.
// Therefore, we explicitly set the Long text and HelpFunc here after all other commands are registered.
// We experimented with producing the paged output dynamically when the HelpFunc is called but since
// doc generation makes use of the Long text, it is simpler to just be explicit here that this command
// is special.
referenceCmd.Long = stringifyReference(cmd)
referenceCmd.SetHelpFunc(longPager(f.IOStreams))
return cmd, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/root/alias.go | pkg/cmd/root/alias.go | package root
import (
"errors"
"fmt"
"os/exec"
"regexp"
"runtime"
"strings"
"github.com/cli/cli/v2/internal/run"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/findsh"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/spf13/cobra"
)
func NewCmdShellAlias(io *iostreams.IOStreams, aliasName, aliasValue string) *cobra.Command {
return &cobra.Command{
Use: aliasName,
Short: fmt.Sprintf("Shell alias for %q", text.Truncate(80, aliasValue)),
RunE: func(c *cobra.Command, args []string) error {
expandedArgs, err := expandShellAlias(aliasValue, args, nil)
if err != nil {
return err
}
externalCmd := exec.Command(expandedArgs[0], expandedArgs[1:]...)
externalCmd.Stderr = io.ErrOut
externalCmd.Stdout = io.Out
externalCmd.Stdin = io.In
preparedCmd := run.PrepareCmd(externalCmd)
if err = preparedCmd.Run(); err != nil {
var execError *exec.ExitError
if errors.As(err, &execError) {
return &ExternalCommandExitError{execError}
}
return fmt.Errorf("failed to run external command: %w\n", err)
}
return nil
},
GroupID: "alias",
Annotations: map[string]string{
"skipAuthCheck": "true",
},
DisableFlagParsing: true,
}
}
func NewCmdAlias(io *iostreams.IOStreams, aliasName, aliasValue string) *cobra.Command {
return &cobra.Command{
Use: aliasName,
Short: fmt.Sprintf("Alias for %q", text.Truncate(80, aliasValue)),
RunE: func(c *cobra.Command, args []string) error {
expandedArgs, err := expandAlias(aliasValue, args)
if err != nil {
return err
}
root := c.Root()
root.SetArgs(expandedArgs)
return root.Execute()
},
GroupID: "alias",
Annotations: map[string]string{
"skipAuthCheck": "true",
},
DisableFlagParsing: true,
}
}
// ExpandAlias processes argv to see if it should be rewritten according to a user's aliases.
func expandAlias(expansion string, args []string) ([]string, error) {
extraArgs := []string{}
for i, a := range args {
if !strings.Contains(expansion, "$") {
extraArgs = append(extraArgs, a)
} else {
expansion = strings.ReplaceAll(expansion, fmt.Sprintf("$%d", i+1), a)
}
}
lingeringRE := regexp.MustCompile(`\$\d`)
if lingeringRE.MatchString(expansion) {
return nil, fmt.Errorf("not enough arguments for alias: %s", expansion)
}
newArgs, err := shlex.Split(expansion)
if err != nil {
return nil, err
}
expanded := append(newArgs, extraArgs...)
return expanded, nil
}
// ExpandShellAlias processes argv to see if it should be rewritten according to a user's aliases.
func expandShellAlias(expansion string, args []string, findShFunc func() (string, error)) ([]string, error) {
if findShFunc == nil {
findShFunc = findSh
}
shPath, shErr := findShFunc()
if shErr != nil {
return nil, shErr
}
expanded := []string{shPath, "-c", expansion[1:]}
if len(args) > 0 {
expanded = append(expanded, "--")
expanded = append(expanded, args...)
}
return expanded, nil
}
func findSh() (string, error) {
shPath, err := findsh.Find()
if err != nil {
if errors.Is(err, exec.ErrNotFound) {
if runtime.GOOS == "windows" {
return "", errors.New("unable to locate sh to execute the shell alias with. The sh.exe interpreter is typically distributed with Git for Windows.")
}
return "", errors.New("unable to locate sh to execute shell alias with")
}
return "", err
}
return shPath, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/root/extension_test.go | pkg/cmd/root/extension_test.go | package root_test
import (
"fmt"
"io"
"testing"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/update"
"github.com/cli/cli/v2/pkg/cmd/root"
"github.com/cli/cli/v2/pkg/extensions"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewCmdExtension_Updates(t *testing.T) {
tests := []struct {
name string
extCurrentVersion string
extIsPinned bool
extLatestVersion string
extName string
extUpdateAvailable bool
extURL string
wantStderr string
}{
{
name: "no update available",
extName: "no-update",
extUpdateAvailable: false,
extCurrentVersion: "1.0.0",
extLatestVersion: "1.0.0",
extURL: "https//github.com/dne/no-update",
},
{
name: "major update",
extName: "major-update",
extUpdateAvailable: true,
extCurrentVersion: "1.0.0",
extLatestVersion: "2.0.0",
extURL: "https//github.com/dne/major-update",
wantStderr: heredoc.Doc(`
A new release of major-update is available: 1.0.0 → 2.0.0
To upgrade, run: gh extension upgrade major-update
https//github.com/dne/major-update
`),
},
{
name: "major update, pinned",
extName: "major-update-pin",
extUpdateAvailable: true,
extCurrentVersion: "1.0.0",
extLatestVersion: "2.0.0",
extIsPinned: true,
extURL: "https//github.com/dne/major-update",
wantStderr: heredoc.Doc(`
A new release of major-update-pin is available: 1.0.0 → 2.0.0
To upgrade, run: gh extension upgrade major-update-pin --force
https//github.com/dne/major-update
`),
},
{
name: "minor update",
extName: "minor-update",
extUpdateAvailable: true,
extCurrentVersion: "1.0.0",
extLatestVersion: "1.1.0",
extURL: "https//github.com/dne/minor-update",
wantStderr: heredoc.Doc(`
A new release of minor-update is available: 1.0.0 → 1.1.0
To upgrade, run: gh extension upgrade minor-update
https//github.com/dne/minor-update
`),
},
{
name: "minor update, pinned",
extName: "minor-update-pin",
extUpdateAvailable: true,
extCurrentVersion: "1.0.0",
extLatestVersion: "1.1.0",
extURL: "https//github.com/dne/minor-update",
extIsPinned: true,
wantStderr: heredoc.Doc(`
A new release of minor-update-pin is available: 1.0.0 → 1.1.0
To upgrade, run: gh extension upgrade minor-update-pin --force
https//github.com/dne/minor-update
`),
},
{
name: "patch update",
extName: "patch-update",
extUpdateAvailable: true,
extCurrentVersion: "1.0.0",
extLatestVersion: "1.0.1",
extURL: "https//github.com/dne/patch-update",
wantStderr: heredoc.Doc(`
A new release of patch-update is available: 1.0.0 → 1.0.1
To upgrade, run: gh extension upgrade patch-update
https//github.com/dne/patch-update
`),
},
{
name: "patch update, pinned",
extName: "patch-update-pin",
extUpdateAvailable: true,
extCurrentVersion: "1.0.0",
extLatestVersion: "1.0.1",
extURL: "https//github.com/dne/patch-update",
extIsPinned: true,
wantStderr: heredoc.Doc(`
A new release of patch-update-pin is available: 1.0.0 → 1.0.1
To upgrade, run: gh extension upgrade patch-update-pin --force
https//github.com/dne/patch-update
`),
},
}
for _, tt := range tests {
ios, _, _, stderr := iostreams.Test()
em := &extensions.ExtensionManagerMock{
DispatchFunc: func(args []string, stdin io.Reader, stdout io.Writer, stderr io.Writer) (bool, error) {
// Assume extension executed / dispatched without problems as test is focused on upgrade checking.
// Sleep for 100 milliseconds to allow update checking logic to complete. This would be better
// served by making the behaviour controllable by channels, but it's a larger change than desired
// just to improve the test.
time.Sleep(100 * time.Millisecond)
return true, nil
},
}
ext := &extensions.ExtensionMock{
CurrentVersionFunc: func() string {
return tt.extCurrentVersion
},
IsPinnedFunc: func() bool {
return tt.extIsPinned
},
LatestVersionFunc: func() string {
return tt.extLatestVersion
},
NameFunc: func() string {
return tt.extName
},
UpdateAvailableFunc: func() bool {
return tt.extUpdateAvailable
},
URLFunc: func() string {
return tt.extURL
},
}
checkFunc := func(em extensions.ExtensionManager, ext extensions.Extension) (*update.ReleaseInfo, error) {
if !tt.extUpdateAvailable {
return nil, nil
}
return &update.ReleaseInfo{
Version: tt.extLatestVersion,
URL: tt.extURL,
}, nil
}
cmd := root.NewCmdExtension(ios, em, ext, checkFunc)
_, err := cmd.ExecuteC()
require.NoError(t, err)
if tt.wantStderr == "" {
assert.Emptyf(t, stderr.String(), "executing extension command should output nothing to stderr")
} else {
assert.Containsf(t, stderr.String(), tt.wantStderr, "executing extension command should output message about upgrade to stderr")
}
}
}
func TestNewCmdExtension_UpdateCheckIsNonblocking(t *testing.T) {
ios, _, _, _ := iostreams.Test()
em := &extensions.ExtensionManagerMock{
DispatchFunc: func(args []string, stdin io.Reader, stdout io.Writer, stderr io.Writer) (bool, error) {
// Assume extension executed / dispatched without problems as test is focused on upgrade checking.
return true, nil
},
}
ext := &extensions.ExtensionMock{
CurrentVersionFunc: func() string {
return "1.0.0"
},
IsPinnedFunc: func() bool {
return false
},
LatestVersionFunc: func() string {
return "2.0.0"
},
NameFunc: func() string {
return "major-update"
},
UpdateAvailableFunc: func() bool {
return true
},
URLFunc: func() string {
return "https//github.com/dne/major-update"
},
}
// When the extension command is executed, the checkFunc will run in the background longer than the extension dispatch.
// If the update check is non-blocking, then the extension command will complete immediately while checkFunc is still running.
checkFunc := func(em extensions.ExtensionManager, ext extensions.Extension) (*update.ReleaseInfo, error) {
time.Sleep(30 * time.Second)
return nil, fmt.Errorf("update check should not have completed")
}
cmd := root.NewCmdExtension(ios, em, ext, checkFunc)
// The test whether update check is non-blocking is based on how long it takes for the extension command execution.
// If there is no wait time as checkFunc is sleeping sufficiently long, we can trust update check is non-blocking.
// Otherwise, if any amount of wait is encountered, it is a decent indicator that update checking is blocking.
// This is not an ideal test and indicates the update design should be revisited to be easier to understand and manage.
completed := make(chan struct{})
go func() {
_, err := cmd.ExecuteC()
require.NoError(t, err)
close(completed)
}()
select {
case <-completed:
// Expected behavior assuming extension dispatch exits immediately while checkFunc is still running.
case <-time.After(1 * time.Second):
t.Fatal("extension update check should have exited")
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/root/help_test.go | pkg/cmd/root/help_test.go | package root
import (
"fmt"
"testing"
"github.com/cli/cli/v2/internal/browser"
"github.com/cli/cli/v2/internal/config"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/extensions"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
"github.com/stretchr/testify/require"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/ast"
"github.com/yuin/goldmark/text"
)
func TestDedent(t *testing.T) {
type c struct {
input string
expected string
}
cases := []c{
{
input: " --help Show help for command\n --version Show gh version\n",
expected: "--help Show help for command\n--version Show gh version\n",
},
{
input: " --help Show help for command\n -R, --repo OWNER/REPO Select another repository using the OWNER/REPO format\n",
expected: " --help Show help for command\n-R, --repo OWNER/REPO Select another repository using the OWNER/REPO format\n",
},
{
input: " line 1\n\n line 2\n line 3",
expected: " line 1\n\n line 2\nline 3",
},
{
input: " line 1\n line 2\n line 3\n\n",
expected: "line 1\nline 2\nline 3\n\n",
},
{
input: "\n\n\n\n\n\n",
expected: "\n\n\n\n\n\n",
},
{
input: "",
expected: "",
},
}
for _, tt := range cases {
got := dedent(tt.input)
if got != tt.expected {
t.Errorf("expected: %q, got: %q", tt.expected, got)
}
}
}
// Since our online docs website renders pages by using the kramdown (a superset
// of Markdown) engine, we have to check against some known quirks of the
// syntax.
func TestKramdownCompatibleDocs(t *testing.T) {
ios, _, _, _ := iostreams.Test()
f := &cmdutil.Factory{
IOStreams: ios,
Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil },
Browser: &browser.Stub{},
ExtensionManager: &extensions.ExtensionManagerMock{
ListFunc: func() []extensions.Extension {
return nil
},
},
}
cmd, err := NewCmdRoot(f, "N/A", "")
require.NoError(t, err)
var walk func(*cobra.Command)
walk = func(cmd *cobra.Command) {
name := fmt.Sprintf("%q: test pipes are in code blocks", cmd.UseLine())
t.Run(name, func(t *testing.T) {
assertPipesAreInCodeBlocks(t, cmd)
})
for _, child := range cmd.Commands() {
walk(child)
}
}
walk(cmd)
}
// If not in a code block or a code span, kramdown treats pipes ("|") as table
// column separators, even if there's no table header, or left/right table row
// borders (i.e. lines starting and ending with a pipe).
//
// We need to assert there's no pipe in the text unless it's in a code-block or
// code-span.
//
// (See https://github.com/cli/cli/issues/10348)
func assertPipesAreInCodeBlocks(t *testing.T, cmd *cobra.Command) {
md := goldmark.New()
reader := text.NewReader([]byte(cmd.Long))
doc := md.Parser().Parse(reader)
var checkNode func(node ast.Node)
checkNode = func(node ast.Node) {
if node.Kind() == ast.KindCodeSpan || node.Kind() == ast.KindCodeBlock {
return
}
if node.Kind() == ast.KindText {
text := string(node.(*ast.Text).Segment.Value(reader.Source()))
require.NotContains(t, text, "|", `found pipe ("|") in plain text in %q docs`, cmd.CommandPath())
}
for child := node.FirstChild(); child != nil; child = child.NextSibling() {
checkNode(child)
}
}
checkNode(doc)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/root/alias_test.go | pkg/cmd/root/alias_test.go | package root
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
)
func TestExpandAlias(t *testing.T) {
tests := []struct {
name string
expansion string
args []string
wantExpanded []string
wantErr string
}{
{
name: "no expansion",
expansion: "pr status",
args: []string{},
wantExpanded: []string{"pr", "status"},
},
{
name: "adding arguments after expansion",
expansion: "pr checkout",
args: []string{"123"},
wantExpanded: []string{"pr", "checkout", "123"},
},
{
name: "not enough arguments for expansion",
expansion: `issue list --author="$1" --label="$2"`,
args: []string{},
wantErr: `not enough arguments for alias: issue list --author="$1" --label="$2"`,
},
{
name: "not enough arguments for expansion 2",
expansion: `issue list --author="$1" --label="$2"`,
args: []string{"vilmibm"},
wantErr: `not enough arguments for alias: issue list --author="vilmibm" --label="$2"`,
},
{
name: "satisfy expansion arguments",
expansion: `issue list --author="$1" --label="$2"`,
args: []string{"vilmibm", "help wanted"},
wantExpanded: []string{"issue", "list", "--author=vilmibm", "--label=help wanted"},
},
{
name: "mixed positional and non-positional arguments",
expansion: `issue list --author="$1" --label="$2"`,
args: []string{"vilmibm", "epic", "-R", "monalisa/testing"},
wantExpanded: []string{"issue", "list", "--author=vilmibm", "--label=epic", "-R", "monalisa/testing"},
},
{
name: "dollar in expansion",
expansion: `issue list --author="$1" --assignee="$1"`,
args: []string{"$coolmoney$"},
wantExpanded: []string{"issue", "list", "--author=$coolmoney$", "--assignee=$coolmoney$"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotExpanded, err := expandAlias(tt.expansion, tt.args)
if tt.wantErr != "" {
assert.Nil(t, gotExpanded)
assert.EqualError(t, err, tt.wantErr)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.wantExpanded, gotExpanded)
})
}
}
func TestExpandShellAlias(t *testing.T) {
findShFunc := func() (string, error) {
return "/usr/bin/sh", nil
}
tests := []struct {
name string
expansion string
args []string
findSh func() (string, error)
wantExpanded []string
wantErr string
}{
{
name: "simple expansion",
expansion: "!git branch --show-current",
args: []string{},
findSh: findShFunc,
wantExpanded: []string{"/usr/bin/sh", "-c", "git branch --show-current"},
},
{
name: "adding arguments after expansion",
expansion: "!git branch checkout",
args: []string{"123"},
findSh: findShFunc,
wantExpanded: []string{"/usr/bin/sh", "-c", "git branch checkout", "--", "123"},
},
{
name: "unable to find sh",
expansion: "!git branch --show-current",
args: []string{},
findSh: func() (string, error) {
return "", errors.New("unable to locate sh")
},
wantErr: "unable to locate sh",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotExpanded, err := expandShellAlias(tt.expansion, tt.args, tt.findSh)
if tt.wantErr != "" {
assert.Nil(t, gotExpanded)
assert.EqualError(t, err, tt.wantErr)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.wantExpanded, gotExpanded)
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/root/extension.go | pkg/cmd/root/extension.go | package root
import (
"errors"
"fmt"
"os/exec"
"strings"
"time"
"github.com/cli/cli/v2/internal/update"
"github.com/cli/cli/v2/pkg/extensions"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/utils"
"github.com/spf13/cobra"
)
type ExternalCommandExitError struct {
*exec.ExitError
}
func NewCmdExtension(io *iostreams.IOStreams, em extensions.ExtensionManager, ext extensions.Extension, checkExtensionReleaseInfo func(extensions.ExtensionManager, extensions.Extension) (*update.ReleaseInfo, error)) *cobra.Command {
updateMessageChan := make(chan *update.ReleaseInfo)
cs := io.ColorScheme()
hasDebug, _ := utils.IsDebugEnabled()
if checkExtensionReleaseInfo == nil {
checkExtensionReleaseInfo = checkForExtensionUpdate
}
return &cobra.Command{
Use: ext.Name(),
Short: fmt.Sprintf("Extension %s", ext.Name()),
// PreRun handles looking up whether extension has a latest version only when the command is ran.
PreRun: func(c *cobra.Command, args []string) {
go func() {
releaseInfo, err := checkExtensionReleaseInfo(em, ext)
if err != nil && hasDebug {
fmt.Fprintf(io.ErrOut, "warning: checking for update failed: %v", err)
}
updateMessageChan <- releaseInfo
}()
},
RunE: func(c *cobra.Command, args []string) error {
args = append([]string{ext.Name()}, args...)
if _, err := em.Dispatch(args, io.In, io.Out, io.ErrOut); err != nil {
var execError *exec.ExitError
if errors.As(err, &execError) {
return &ExternalCommandExitError{execError}
}
return fmt.Errorf("failed to run extension: %w\n", err)
}
return nil
},
// PostRun handles communicating extension release information if found
PostRun: func(c *cobra.Command, args []string) {
select {
case releaseInfo := <-updateMessageChan:
if releaseInfo != nil {
stderr := io.ErrOut
fmt.Fprintf(stderr, "\n\n%s %s → %s\n",
cs.Yellowf("A new release of %s is available:", ext.Name()),
cs.Cyan(strings.TrimPrefix(ext.CurrentVersion(), "v")),
cs.Cyan(strings.TrimPrefix(releaseInfo.Version, "v")))
if ext.IsPinned() {
fmt.Fprintf(stderr, "To upgrade, run: gh extension upgrade %s --force\n", ext.Name())
} else {
fmt.Fprintf(stderr, "To upgrade, run: gh extension upgrade %s\n", ext.Name())
}
fmt.Fprintf(stderr, "%s\n\n",
cs.Yellow(releaseInfo.URL))
}
default:
// Do not make the user wait for extension update check if incomplete by this time.
// This is being handled in non-blocking default as there is no context to cancel like in gh update checks.
}
},
GroupID: "extension",
Annotations: map[string]string{
"skipAuthCheck": "true",
},
DisableFlagParsing: true,
}
}
func checkForExtensionUpdate(em extensions.ExtensionManager, ext extensions.Extension) (*update.ReleaseInfo, error) {
if !update.ShouldCheckForExtensionUpdate() {
return nil, nil
}
return update.CheckForExtensionUpdate(em, ext, time.Now())
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/root/help_reference.go | pkg/cmd/root/help_reference.go | package root
import (
"bytes"
"fmt"
"io"
"strings"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/pkg/markdown"
"github.com/spf13/cobra"
)
// longPager provides a pager over a commands Long message.
// It is currently only used for the reference command
func longPager(io *iostreams.IOStreams) func(*cobra.Command, []string) {
return func(cmd *cobra.Command, args []string) {
wrapWidth := 0
if io.IsStdoutTTY() {
io.DetectTerminalTheme()
wrapWidth = io.TerminalWidth()
}
md, err := markdown.Render(cmd.Long,
markdown.WithTheme(io.TerminalTheme()),
markdown.WithWrap(wrapWidth))
if err != nil {
fmt.Fprintln(io.ErrOut, err)
return
}
if !io.IsStdoutTTY() {
fmt.Fprint(io.Out, dedent(md))
return
}
_ = io.StartPager()
defer io.StopPager()
fmt.Fprint(io.Out, md)
}
}
func stringifyReference(cmd *cobra.Command) string {
buf := bytes.NewBufferString("# gh reference\n\n")
for _, c := range cmd.Commands() {
if c.Hidden {
continue
}
cmdRef(buf, c, 2)
}
return buf.String()
}
func cmdRef(w io.Writer, cmd *cobra.Command, depth int) {
// Name + Description
fmt.Fprintf(w, "%s `%s`\n\n", strings.Repeat("#", depth), cmd.UseLine())
fmt.Fprintf(w, "%s\n\n", cmd.Short)
// Flags
// TODO: fold in InheritedFlags/PersistentFlags, but omit `--help` due to repetitiveness
if flagUsages := cmd.Flags().FlagUsages(); flagUsages != "" {
fmt.Fprintf(w, "```\n%s````\n\n", dedent(flagUsages))
}
// Aliases
if len(cmd.Aliases) > 0 {
fmt.Fprintf(w, "%s\n\n", "Aliases")
fmt.Fprintf(w, "\n%s\n\n", dedent(strings.Join(BuildAliasList(cmd, cmd.Aliases), ", ")))
}
// Subcommands
for _, c := range cmd.Commands() {
if c.Hidden {
continue
}
cmdRef(w, c, depth+1)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/root/help.go | pkg/cmd/root/help.go | package root
import (
"bytes"
"fmt"
"io"
"os"
"sort"
"strings"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
func rootUsageFunc(w io.Writer, command *cobra.Command) error {
fmt.Fprintf(w, "Usage: %s", command.UseLine())
var subcommands []*cobra.Command
for _, c := range command.Commands() {
if !c.IsAvailableCommand() {
continue
}
subcommands = append(subcommands, c)
}
if len(subcommands) > 0 {
fmt.Fprint(w, "\n\nAvailable commands:\n")
for _, c := range subcommands {
fmt.Fprintf(w, " %s\n", c.Name())
}
return nil
}
flagUsages := command.LocalFlags().FlagUsages()
if flagUsages != "" {
fmt.Fprintln(w, "\n\nFlags:")
fmt.Fprint(w, text.Indent(dedent(flagUsages), " "))
}
return nil
}
func rootFlagErrorFunc(cmd *cobra.Command, err error) error {
if err == pflag.ErrHelp {
return err
}
return cmdutil.FlagErrorWrap(err)
}
var hasFailed bool
// HasFailed signals that the main process should exit with non-zero status
func HasFailed() bool {
return hasFailed
}
// Display helpful error message in case subcommand name was mistyped.
// This matches Cobra's behavior for root command, which Cobra
// confusingly doesn't apply to nested commands.
func nestedSuggestFunc(w io.Writer, command *cobra.Command, arg string) {
fmt.Fprintf(w, "unknown command %q for %q\n", arg, command.CommandPath())
var candidates []string
if arg == "help" {
candidates = []string{"--help"}
} else {
if command.SuggestionsMinimumDistance <= 0 {
command.SuggestionsMinimumDistance = 2
}
candidates = command.SuggestionsFor(arg)
}
if len(candidates) > 0 {
fmt.Fprint(w, "\nDid you mean this?\n")
for _, c := range candidates {
fmt.Fprintf(w, "\t%s\n", c)
}
}
fmt.Fprint(w, "\n")
_ = rootUsageFunc(w, command)
}
func isRootCmd(command *cobra.Command) bool {
return command != nil && !command.HasParent()
}
func rootHelpFunc(f *cmdutil.Factory, command *cobra.Command, _ []string) {
flags := command.Flags()
if isRootCmd(command) {
if versionVal, err := flags.GetBool("version"); err == nil && versionVal {
fmt.Fprint(f.IOStreams.Out, command.Annotations["versionInfo"])
return
} else if err != nil {
fmt.Fprintln(f.IOStreams.ErrOut, err)
hasFailed = true
return
}
}
cs := f.IOStreams.ColorScheme()
if help, _ := flags.GetBool("help"); !help && !command.Runnable() && len(flags.Args()) > 0 {
nestedSuggestFunc(f.IOStreams.ErrOut, command, flags.Args()[0])
hasFailed = true
return
}
type helpEntry struct {
Title string
Body string
}
longText := command.Long
if longText == "" {
longText = command.Short
}
if longText != "" && command.LocalFlags().Lookup("jq") != nil {
longText = strings.TrimRight(longText, "\n") +
"\n\nFor more information about output formatting flags, see `gh help formatting`."
}
helpEntries := []helpEntry{}
if longText != "" {
helpEntries = append(helpEntries, helpEntry{"", longText})
}
helpEntries = append(helpEntries, helpEntry{"USAGE", command.UseLine()})
if len(command.Aliases) > 0 {
helpEntries = append(helpEntries, helpEntry{"ALIASES", strings.Join(BuildAliasList(command, command.Aliases), ", ") + "\n"})
}
// Statically calculated padding for non-extension commands,
// longest is `gh accessibility` with 13 characters + 1 space.
//
// Should consider novel way to calculate this in the future [AF]
namePadding := 14
for _, g := range GroupedCommands(command) {
var names []string
for _, c := range g.Commands {
names = append(names, rpad(c.Name()+":", namePadding)+c.Short)
}
helpEntries = append(helpEntries, helpEntry{
Title: strings.ToUpper(g.Title),
Body: strings.Join(names, "\n"),
})
}
if isRootCmd(command) {
var helpTopics []string
if c := findCommand(command, "accessibility"); c != nil {
helpTopics = append(helpTopics, rpad(c.Name()+":", namePadding)+c.Short)
}
if c := findCommand(command, "actions"); c != nil {
helpTopics = append(helpTopics, rpad(c.Name()+":", namePadding)+c.Short)
}
for _, helpTopic := range HelpTopics {
helpTopics = append(helpTopics, rpad(helpTopic.name+":", namePadding)+helpTopic.short)
}
sort.Strings(helpTopics)
helpEntries = append(helpEntries, helpEntry{"HELP TOPICS", strings.Join(helpTopics, "\n")})
}
flagUsages := command.LocalFlags().FlagUsages()
if flagUsages != "" {
helpEntries = append(helpEntries, helpEntry{"FLAGS", dedent(flagUsages)})
}
inheritedFlagUsages := command.InheritedFlags().FlagUsages()
if inheritedFlagUsages != "" {
helpEntries = append(helpEntries, helpEntry{"INHERITED FLAGS", dedent(inheritedFlagUsages)})
}
if _, ok := command.Annotations["help:json-fields"]; ok {
fields := strings.Split(command.Annotations["help:json-fields"], ",")
helpEntries = append(helpEntries, helpEntry{"JSON FIELDS", text.FormatSlice(fields, 80, 0, "", "", true)})
}
if _, ok := command.Annotations["help:arguments"]; ok {
helpEntries = append(helpEntries, helpEntry{"ARGUMENTS", command.Annotations["help:arguments"]})
}
if command.Example != "" {
helpEntries = append(helpEntries, helpEntry{"EXAMPLES", command.Example})
}
if _, ok := command.Annotations["help:environment"]; ok {
helpEntries = append(helpEntries, helpEntry{"ENVIRONMENT VARIABLES", command.Annotations["help:environment"]})
}
helpEntries = append(helpEntries, helpEntry{"LEARN MORE", heredoc.Docf(`
Use %[1]sgh <command> <subcommand> --help%[1]s for more information about a command.
Read the manual at https://cli.github.com/manual
Learn about exit codes using %[1]sgh help exit-codes%[1]s
Learn about accessibility experiences using %[1]sgh help accessibility%[1]s
`, "`")})
out := f.IOStreams.Out
for _, e := range helpEntries {
if e.Title != "" {
// If there is a title, add indentation to each line in the body
fmt.Fprintln(out, cs.Bold(e.Title))
fmt.Fprintln(out, text.Indent(strings.Trim(e.Body, "\r\n"), " "))
} else {
// If there is no title print the body as is
fmt.Fprintln(out, e.Body)
}
fmt.Fprintln(out)
}
}
func authHelp() string {
if os.Getenv("GITHUB_ACTIONS") == "true" {
return heredoc.Doc(`
gh: To use GitHub CLI in a GitHub Actions workflow, set the GH_TOKEN environment variable. Example:
env:
GH_TOKEN: ${{ github.token }}
`)
}
if os.Getenv("CI") != "" {
return heredoc.Doc(`
gh: To use GitHub CLI in automation, set the GH_TOKEN environment variable.
`)
}
return heredoc.Doc(`
To get started with GitHub CLI, please run: gh auth login
Alternatively, populate the GH_TOKEN environment variable with a GitHub API authentication token.
`)
}
func findCommand(cmd *cobra.Command, name string) *cobra.Command {
for _, c := range cmd.Commands() {
if c.Name() == name {
return c
}
}
return nil
}
type CommandGroup struct {
Title string
Commands []*cobra.Command
}
func GroupedCommands(cmd *cobra.Command) []CommandGroup {
var res []CommandGroup
for _, g := range cmd.Groups() {
var cmds []*cobra.Command
for _, c := range cmd.Commands() {
if c.GroupID == g.ID && c.IsAvailableCommand() {
cmds = append(cmds, c)
}
}
if len(cmds) > 0 {
res = append(res, CommandGroup{
Title: g.Title,
Commands: cmds,
})
}
}
var cmds []*cobra.Command
for _, c := range cmd.Commands() {
if c.GroupID == "" && c.IsAvailableCommand() {
cmds = append(cmds, c)
}
}
if len(cmds) > 0 {
defaultGroupTitle := "Additional commands"
if len(cmd.Groups()) == 0 {
defaultGroupTitle = "Available commands"
}
res = append(res, CommandGroup{
Title: defaultGroupTitle,
Commands: cmds,
})
}
return res
}
// rpad adds padding to the right of a string.
func rpad(s string, padding int) string {
template := fmt.Sprintf("%%-%ds ", padding)
return fmt.Sprintf(template, s)
}
func dedent(s string) string {
lines := strings.Split(s, "\n")
minIndent := -1
for _, l := range lines {
if len(l) == 0 {
continue
}
indent := len(l) - len(strings.TrimLeft(l, " "))
if minIndent == -1 || indent < minIndent {
minIndent = indent
}
}
if minIndent <= 0 {
return s
}
var buf bytes.Buffer
for _, l := range lines {
fmt.Fprintln(&buf, strings.TrimPrefix(l, strings.Repeat(" ", minIndent)))
}
return strings.TrimSuffix(buf.String(), "\n")
}
func BuildAliasList(cmd *cobra.Command, aliases []string) []string {
if !cmd.HasParent() {
return aliases
}
parentAliases := append(cmd.Parent().Aliases, cmd.Parent().Name())
sort.Strings(parentAliases)
var aliasesWithParentAliases []string
// e.g aliases = [ls]
for _, alias := range aliases {
// e.g parentAliases = [codespaces, cs]
for _, parentAlias := range parentAliases {
// e.g. aliasesWithParentAliases = [codespaces list, codespaces ls, cs list, cs ls]
aliasesWithParentAliases = append(aliasesWithParentAliases, fmt.Sprintf("%s %s", parentAlias, alias))
}
}
return BuildAliasList(cmd.Parent(), aliasesWithParentAliases)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/root/help_topic_test.go | pkg/cmd/root/help_topic_test.go | package root
import (
"testing"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/stretchr/testify/require"
)
func TestCmdHelpTopic(t *testing.T) {
t.Parallel()
tests := []struct {
name string
topic helpTopic
args []string
flags []string
errorAssertion require.ErrorAssertionFunc
expectedAnnotations map[string]string
}{
{
name: "when there are no args or flags, prints the long message to stdout",
topic: helpTopic{name: "test-topic", long: "test-topic-long"},
args: []string{},
flags: []string{},
errorAssertion: require.NoError,
},
{
name: "when an arg is provided, it is ignored and help is printed",
topic: helpTopic{name: "test-topic"},
args: []string{"anything"},
flags: []string{},
errorAssertion: require.NoError,
},
{
name: "when a flag is provided, returns an error",
topic: helpTopic{name: "test-topic"},
args: []string{},
flags: []string{"--anything"},
errorAssertion: require.Error,
},
{
name: "when there is an example, include it in the stdout",
topic: helpTopic{name: "test-topic", example: "test-topic-example"},
args: []string{},
flags: []string{},
errorAssertion: require.NoError,
},
{
name: "sets important markdown annotations on the command",
topic: helpTopic{name: "test-topic"},
args: []string{},
flags: []string{},
errorAssertion: require.NoError,
expectedAnnotations: map[string]string{
"markdown:generate": "true",
"markdown:basename": "gh_help_test-topic",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
ios, _, stdout, _ := iostreams.Test()
cmd := NewCmdHelpTopic(ios, tt.topic)
cmd.SetArgs(append(tt.args, tt.flags...))
_, err := cmd.ExecuteC()
tt.errorAssertion(t, err)
if tt.topic.long != "" {
require.Contains(t, stdout.String(), tt.topic.long)
}
if tt.topic.example != "" {
require.Contains(t, stdout.String(), tt.topic.example)
}
if len(tt.expectedAnnotations) > 0 {
require.Equal(t, cmd.Annotations, tt.expectedAnnotations)
}
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/version/version_test.go | pkg/cmd/version/version_test.go | package version
import (
"testing"
)
func TestFormat(t *testing.T) {
expects := "gh version 1.4.0 (2020-12-15)\nhttps://github.com/cli/cli/releases/tag/v1.4.0\n"
if got := Format("1.4.0", "2020-12-15"); got != expects {
t.Errorf("Format() = %q, wants %q", got, expects)
}
}
func TestChangelogURL(t *testing.T) {
tag := "0.3.2"
url := "https://github.com/cli/cli/releases/tag/v0.3.2"
result := changelogURL(tag)
if result != url {
t.Errorf("expected %s to create url %s but got %s", tag, url, result)
}
tag = "v0.3.2"
url = "https://github.com/cli/cli/releases/tag/v0.3.2"
result = changelogURL(tag)
if result != url {
t.Errorf("expected %s to create url %s but got %s", tag, url, result)
}
tag = "0.3.2-pre.1"
url = "https://github.com/cli/cli/releases/tag/v0.3.2-pre.1"
result = changelogURL(tag)
if result != url {
t.Errorf("expected %s to create url %s but got %s", tag, url, result)
}
tag = "0.3.5-90-gdd3f0e0"
url = "https://github.com/cli/cli/releases/latest"
result = changelogURL(tag)
if result != url {
t.Errorf("expected %s to create url %s but got %s", tag, url, result)
}
tag = "deadbeef"
url = "https://github.com/cli/cli/releases/latest"
result = changelogURL(tag)
if result != url {
t.Errorf("expected %s to create url %s but got %s", tag, url, result)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/version/version.go | pkg/cmd/version/version.go | package version
import (
"fmt"
"regexp"
"strings"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/spf13/cobra"
)
func NewCmdVersion(f *cmdutil.Factory, version, buildDate string) *cobra.Command {
cmd := &cobra.Command{
Use: "version",
Hidden: true,
Run: func(cmd *cobra.Command, args []string) {
fmt.Fprint(f.IOStreams.Out, cmd.Root().Annotations["versionInfo"])
},
}
cmdutil.DisableAuthCheck(cmd)
return cmd
}
func Format(version, buildDate string) string {
version = strings.TrimPrefix(version, "v")
var dateStr string
if buildDate != "" {
dateStr = fmt.Sprintf(" (%s)", buildDate)
}
return fmt.Sprintf("gh version %s%s\n%s\n", version, dateStr, changelogURL(version))
}
func changelogURL(version string) string {
path := "https://github.com/cli/cli"
r := regexp.MustCompile(`^v?\d+\.\d+\.\d+(-[\w.]+)?$`)
if !r.MatchString(version) {
return fmt.Sprintf("%s/releases/latest", path)
}
url := fmt.Sprintf("%s/releases/tag/v%s", path, strings.TrimPrefix(version, "v"))
return url
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/agent-task/agent_task.go | pkg/cmd/agent-task/agent_task.go | package agent
import (
"errors"
"fmt"
"strings"
"github.com/MakeNowJust/heredoc"
cmdCreate "github.com/cli/cli/v2/pkg/cmd/agent-task/create"
cmdList "github.com/cli/cli/v2/pkg/cmd/agent-task/list"
cmdView "github.com/cli/cli/v2/pkg/cmd/agent-task/view"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/go-gh/v2/pkg/auth"
"github.com/spf13/cobra"
)
// NewCmdAgentTask creates the base `agent-task` command.
func NewCmdAgentTask(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "agent-task <command>",
Aliases: []string{"agent-tasks", "agent", "agents"},
Short: "Work with agent tasks (preview)",
Long: heredoc.Doc(`
Working with agent tasks in the GitHub CLI is in preview and
subject to change without notice.
`),
Annotations: map[string]string{
"help:arguments": heredoc.Doc(`
A task can be identified as argument in any of the following formats:
- by pull request number, e.g. "123"; or
- by session ID, e.g. "12345abc-12345-12345-12345-12345abc"; or
- by URL, e.g. "https://github.com/OWNER/REPO/pull/123/agent-sessions/12345abc-12345-12345-12345-12345abc";
Identifying tasks by pull request is not recommended for non-interactive use cases as
there may be multiple tasks for a given pull request that require disambiguation.
`),
},
Example: heredoc.Doc(`
# List your most recent agent tasks
$ gh agent-task list
# Create a new agent task on the current repository
$ gh agent-task create "Improve the performance of the data processing pipeline"
# View details about agent tasks associated with a pull request
$ gh agent-task view 123
# View details about a specific agent task
$ gh agent-task view 12345abc-12345-12345-12345-12345abc
`),
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
return requireOAuthToken(f)
},
// This is required to run this root command. We want to
// run it to test PersistentPreRunE behavior.
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}
// register subcommands
cmd.AddCommand(cmdList.NewCmdList(f, nil))
cmd.AddCommand(cmdCreate.NewCmdCreate(f, nil))
cmd.AddCommand(cmdView.NewCmdView(f, nil))
return cmd
}
// requireOAuthToken ensures an OAuth (device flow) token is present and valid.
// agent-task subcommands inherit this check via PersistentPreRunE.
func requireOAuthToken(f *cmdutil.Factory) error {
cfg, err := f.Config()
if err != nil {
return err
}
authCfg := cfg.Authentication()
host, _ := authCfg.DefaultHost()
if host == "" {
return errors.New("no default host configured; run 'gh auth login'")
}
if auth.IsEnterprise(host) {
return errors.New("agent tasks are not supported on this host")
}
token, source := authCfg.ActiveToken(host)
// Tokens from sources "oauth_token" and "keyring" are likely
// minted through our device flow.
tokenSourceIsDeviceFlow := source == "oauth_token" || source == "keyring"
// Tokens with "gho_" prefix are OAuth tokens.
tokenIsOAuth := strings.HasPrefix(token, "gho_")
// Reject if the token is not from a device flow source or is not an OAuth token
if !tokenSourceIsDeviceFlow || !tokenIsOAuth {
return fmt.Errorf("this command requires an OAuth token. Re-authenticate with: gh auth login")
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/agent-task/agent_task_test.go | pkg/cmd/agent-task/agent_task_test.go | package agent
import (
"testing"
"github.com/cli/cli/v2/internal/config"
"github.com/cli/cli/v2/internal/gh"
ghmock "github.com/cli/cli/v2/internal/gh/mock"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/stretchr/testify/require"
)
// setupMockOAuthConfig configures a blank config with a default host and optional token behavior.
func setupMockOAuthConfig(t *testing.T, tokenSource string) gh.Config {
t.Helper()
c := config.NewBlankConfig()
switch tokenSource {
case "oauth_token":
// valid OAuth device flow token stored in config
c.Set("github.com", "oauth_token", "gho_OAUTH123")
case "keyring":
// valid OAuth device flow token stored in keyring
c.Set("github.com", "oauth_token", "gho_OAUTH123")
case "GH_TOKEN":
// classic style token stored in config (will fail prefix check)
c.Set("github.com", "oauth_token", "ghp_CLASSIC123")
case "GH_ENTERPRISE_TOKEN":
// enterprise style token stored in config (will fail prefix check)
c.Set("something.ghes.com", "oauth_token", "ghe_ENTERPRISE123")
}
return c
}
func TestNewCmdAgentTask(t *testing.T) {
tests := []struct {
name string
tokenSource string
customConfig func() (gh.Config, error)
wantErr bool
wantErrContains string
wantStdout string
}{
{
name: "oauth token is accepted",
tokenSource: "oauth_token",
wantErr: false,
wantStdout: "",
},
{
name: "keyring oauth token is accepted",
tokenSource: "keyring",
wantErr: false,
wantStdout: "",
},
{
name: "env var token is rejected",
tokenSource: "GH_TOKEN",
wantErr: true,
wantErrContains: "requires an OAuth token",
},
{
name: "enterprise token alone is ignored and rejected",
tokenSource: "GH_ENTERPRISE_TOKEN",
wantErr: true,
},
{
name: "github.com oauth is accepted and enterprise token ignored",
customConfig: func() (gh.Config, error) {
c := config.NewBlankConfig()
c.Set("something.ghes.com", "oauth_token", "ghe_ENTERPRISE123")
c.Set("github.com", "oauth_token", "gho_OAUTH123")
return c, nil
},
wantErr: false,
wantStdout: "",
},
{
name: "enterprise host is rejected",
customConfig: func() (gh.Config, error) {
return &ghmock.ConfigMock{
AuthenticationFunc: func() gh.AuthConfig {
c := &config.AuthConfig{}
c.SetDefaultHost("something.ghes.com", "GH_HOST")
return c
},
}, nil
},
wantErr: true,
wantErrContains: "not supported on this host",
},
{
name: "empty host is rejected",
customConfig: func() (gh.Config, error) {
return &ghmock.ConfigMock{
AuthenticationFunc: func() gh.AuthConfig {
c := &config.AuthConfig{}
c.SetDefaultHost("", "GH_HOST")
return c
},
}, nil
},
wantErr: true,
wantErrContains: "no default host configured",
},
{
name: "no auth is rejected",
tokenSource: "",
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f := &cmdutil.Factory{}
ios, _, stdout, _ := iostreams.Test()
f.IOStreams = ios
if tt.customConfig != nil {
f.Config = tt.customConfig
} else {
f.Config = func() (gh.Config, error) { return setupMockOAuthConfig(t, tt.tokenSource), nil }
}
cmd := NewCmdAgentTask(f)
err := cmd.Execute()
if tt.wantErr {
require.Error(t, err)
if tt.wantErrContains != "" {
require.Contains(t, err.Error(), tt.wantErrContains)
}
} else {
require.NoError(t, err)
require.Equal(t, tt.wantStdout, stdout.String())
}
})
}
}
func TestAliasAreSet(t *testing.T) {
f := &cmdutil.Factory{}
ios, _, _, _ := iostreams.Test()
f.IOStreams = ios
f.Config = func() (gh.Config, error) { return setupMockOAuthConfig(t, "oauth_token"), nil }
cmd := NewCmdAgentTask(f)
require.ElementsMatch(t, []string{"agent-tasks", "agent", "agents"}, cmd.Aliases)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/agent-task/capi/job_test.go | pkg/cmd/agent-task/capi/job_test.go | package capi
import (
"context"
"net/http"
"testing"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestGetJobRequiresRepoAndJobID(t *testing.T) {
client := &CAPIClient{}
_, err := client.GetJob(context.Background(), "", "", "only-job-id")
assert.EqualError(t, err, "owner, repo, and jobID are required")
_, err = client.GetJob(context.Background(), "", "only-repo", "")
assert.EqualError(t, err, "owner, repo, and jobID are required")
_, err = client.GetJob(context.Background(), "only-owner", "", "")
assert.EqualError(t, err, "owner, repo, and jobID are required")
_, err = client.GetJob(context.Background(), "", "", "")
assert.EqualError(t, err, "owner, repo, and jobID are required")
}
func TestGetJob(t *testing.T) {
sampleDateString := "2025-08-29T00:00:00Z"
sampleDate, err := time.Parse(time.RFC3339, sampleDateString)
require.NoError(t, err)
tests := []struct {
name string
httpStubs func(*testing.T, *httpmock.Registry)
wantErr string
wantOut *Job
}{
{
name: "job without PR",
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.WithHost(httpmock.REST("GET", "agents/swe/v1/jobs/OWNER/REPO/job123"), "api.githubcopilot.com"),
httpmock.StatusStringResponse(200, heredoc.Docf(`
{
"job_id": "job123",
"session_id": "sess1",
"problem_statement": "Do the thing",
"event_type": "foo",
"content_filter_mode": "foo",
"status": "foo",
"result": "foo",
"actor": {
"id": 1,
"login": "octocat"
},
"created_at": "%[1]s",
"updated_at": "%[1]s"
}`,
sampleDateString,
)),
)
},
wantOut: &Job{
ID: "job123",
SessionID: "sess1",
ProblemStatement: "Do the thing",
EventType: "foo",
ContentFilterMode: "foo",
Status: "foo",
Result: "foo",
Actor: &JobActor{
ID: 1,
Login: "octocat",
},
CreatedAt: sampleDate,
UpdatedAt: sampleDate,
},
},
{
name: "job with PR",
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.WithHost(httpmock.REST("GET", "agents/swe/v1/jobs/OWNER/REPO/job123"), "api.githubcopilot.com"),
httpmock.StatusStringResponse(200, heredoc.Docf(`
{
"job_id": "job123",
"session_id": "sess1",
"problem_statement": "Do the thing",
"event_type": "foo",
"content_filter_mode": "foo",
"status": "foo",
"result": "foo",
"actor": {
"id": 1,
"login": "octocat"
},
"created_at": "%[1]s",
"updated_at": "%[1]s",
"pull_request": {
"id": 101,
"number": 42
}
}`,
sampleDateString,
)),
)
},
wantOut: &Job{
ID: "job123",
SessionID: "sess1",
ProblemStatement: "Do the thing",
EventType: "foo",
ContentFilterMode: "foo",
Status: "foo",
Result: "foo",
Actor: &JobActor{
ID: 1,
Login: "octocat",
},
CreatedAt: sampleDate,
UpdatedAt: sampleDate,
PullRequest: &JobPullRequest{
ID: 101,
Number: 42,
},
},
},
{
name: "job not found",
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.WithHost(httpmock.REST("GET", "agents/swe/v1/jobs/OWNER/REPO/job123"), "api.githubcopilot.com"),
httpmock.StatusStringResponse(404, `{}`),
)
},
wantErr: "failed to get job: 404 Not Found",
},
{
name: "API error",
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.WithHost(httpmock.REST("GET", "agents/swe/v1/jobs/OWNER/REPO/job123"), "api.githubcopilot.com"),
httpmock.StatusStringResponse(500, `{}`),
)
},
wantErr: "failed to get job: 500 Internal Server Error",
},
{
name: "invalid JSON response",
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.WithHost(httpmock.REST("GET", "agents/swe/v1/jobs/OWNER/REPO/job123"), "api.githubcopilot.com"),
httpmock.StatusStringResponse(200, ``),
)
},
wantErr: "failed to decode get job response: EOF",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
if tt.httpStubs != nil {
tt.httpStubs(t, reg)
}
defer reg.Verify(t)
httpClient := &http.Client{Transport: reg}
capiClient := NewCAPIClient(httpClient, "", "github.com")
job, err := capiClient.GetJob(context.Background(), "OWNER", "REPO", "job123")
if tt.wantErr != "" {
require.EqualError(t, err, tt.wantErr)
require.Nil(t, job)
return
}
require.NoError(t, err)
require.Equal(t, tt.wantOut, job)
})
}
}
func TestCreateJobRequiresRepoAndProblemStatement(t *testing.T) {
client := &CAPIClient{}
_, err := client.CreateJob(context.Background(), "", "only-repo", "", "", "")
assert.EqualError(t, err, "owner and repo are required")
_, err = client.CreateJob(context.Background(), "only-owner", "", "", "", "")
assert.EqualError(t, err, "owner and repo are required")
_, err = client.CreateJob(context.Background(), "", "", "", "", "")
assert.EqualError(t, err, "owner and repo are required")
_, err = client.CreateJob(context.Background(), "owner", "repo", "", "", "")
assert.EqualError(t, err, "problem statement is required")
}
func TestCreateJob(t *testing.T) {
sampleDateString := "2025-08-29T00:00:00Z"
sampleDate, err := time.Parse(time.RFC3339, sampleDateString)
require.NoError(t, err)
tests := []struct {
name string
baseBranch string
customAgent string
httpStubs func(*testing.T, *httpmock.Registry)
wantErr string
wantOut *Job
}{
{
name: "success",
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.WithHost(httpmock.REST("POST", "agents/swe/v1/jobs/OWNER/REPO"), "api.githubcopilot.com"),
httpmock.RESTPayload(201,
heredoc.Docf(`
{
"job_id": "job123",
"session_id": "sess1",
"problem_statement": "Do the thing",
"event_type": "foo",
"content_filter_mode": "foo",
"status": "foo",
"result": "foo",
"actor": {
"id": 1,
"login": "octocat"
},
"created_at": "%[1]s",
"updated_at": "%[1]s"
}
`, sampleDateString),
func(payload map[string]interface{}) {
assert.Equal(t, "Do the thing", payload["problem_statement"])
assert.Equal(t, "gh_cli", payload["event_type"])
},
),
)
},
wantOut: &Job{
ID: "job123",
SessionID: "sess1",
ProblemStatement: "Do the thing",
EventType: "foo",
ContentFilterMode: "foo",
Status: "foo",
Result: "foo",
Actor: &JobActor{
ID: 1,
Login: "octocat",
},
CreatedAt: sampleDate,
UpdatedAt: sampleDate,
},
},
{
name: "success with base branch",
baseBranch: "some-branch",
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.WithHost(httpmock.REST("POST", "agents/swe/v1/jobs/OWNER/REPO"), "api.githubcopilot.com"),
httpmock.RESTPayload(201,
heredoc.Docf(`
{
"job_id": "job123",
"session_id": "sess1",
"problem_statement": "Do the thing",
"event_type": "foo",
"content_filter_mode": "foo",
"status": "foo",
"result": "foo",
"actor": {
"id": 1,
"login": "octocat"
},
"created_at": "%[1]s",
"updated_at": "%[1]s"
}
`, sampleDateString),
func(payload map[string]interface{}) {
assert.Equal(t, "Do the thing", payload["problem_statement"])
assert.Equal(t, "gh_cli", payload["event_type"])
assert.Equal(t, "refs/heads/some-branch", payload["pull_request"].(map[string]interface{})["base_ref"])
},
),
)
},
wantOut: &Job{
ID: "job123",
SessionID: "sess1",
ProblemStatement: "Do the thing",
EventType: "foo",
ContentFilterMode: "foo",
Status: "foo",
Result: "foo",
Actor: &JobActor{
ID: 1,
Login: "octocat",
},
CreatedAt: sampleDate,
UpdatedAt: sampleDate,
},
},
{
name: "Success with custom agent",
customAgent: "my-custom-agent",
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.WithHost(httpmock.REST("POST", "agents/swe/v1/jobs/OWNER/REPO"), "api.githubcopilot.com"),
httpmock.RESTPayload(201,
heredoc.Docf(`
{
"job_id": "job123",
"session_id": "sess1",
"problem_statement": "Do the thing",
"custom_agent": "my-custom-agent",
"event_type": "foo",
"content_filter_mode": "foo",
"status": "foo",
"result": "foo",
"actor": {
"id": 1,
"login": "octocat"
},
"created_at": "%[1]s",
"updated_at": "%[1]s"
}
`, sampleDateString),
func(payload map[string]interface{}) {
assert.Equal(t, "Do the thing", payload["problem_statement"])
assert.Equal(t, "gh_cli", payload["event_type"])
assert.Equal(t, "my-custom-agent", payload["custom_agent"])
},
),
)
},
wantOut: &Job{
ID: "job123",
SessionID: "sess1",
ProblemStatement: "Do the thing",
CustomAgent: "my-custom-agent",
EventType: "foo",
ContentFilterMode: "foo",
Status: "foo",
Result: "foo",
Actor: &JobActor{
ID: 1,
Login: "octocat",
},
CreatedAt: sampleDate,
UpdatedAt: sampleDate,
},
},
{
name: "API error, included in response body",
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.WithHost(httpmock.REST("POST", "agents/swe/v1/jobs/OWNER/REPO"), "api.githubcopilot.com"),
httpmock.StatusStringResponse(500, heredoc.Doc(`{
"error": {
"message": "some error"
}
}`)),
)
},
wantErr: "failed to create job: 500 Internal Server Error: some error",
},
{
name: "API error",
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.WithHost(httpmock.REST("POST", "agents/swe/v1/jobs/OWNER/REPO"), "api.githubcopilot.com"),
httpmock.StatusStringResponse(500, `{}`),
)
},
wantErr: "failed to create job: 500 Internal Server Error: ",
},
{
name: "invalid JSON response, non-HTTP 200",
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.WithHost(httpmock.REST("POST", "agents/swe/v1/jobs/OWNER/REPO"), "api.githubcopilot.com"),
httpmock.StatusStringResponse(401, `Unauthorized`),
)
},
wantErr: "failed to create job: 401 Unauthorized",
},
{
name: "invalid JSON response, HTTP 200",
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.WithHost(httpmock.REST("POST", "agents/swe/v1/jobs/OWNER/REPO"), "api.githubcopilot.com"),
httpmock.StatusStringResponse(200, ``),
)
},
wantErr: "failed to decode create job response: EOF",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
if tt.httpStubs != nil {
tt.httpStubs(t, reg)
}
defer reg.Verify(t)
httpClient := &http.Client{Transport: reg}
capiClient := NewCAPIClient(httpClient, "", "github.com")
job, err := capiClient.CreateJob(context.Background(), "OWNER", "REPO", "Do the thing", tt.baseBranch, tt.customAgent)
if tt.wantErr != "" {
require.EqualError(t, err, tt.wantErr)
require.Nil(t, job)
return
}
require.NoError(t, err)
require.Equal(t, tt.wantOut, job)
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/agent-task/capi/job.go | pkg/cmd/agent-task/capi/job.go | package capi
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"time"
)
const defaultEventType = "gh_cli"
// Job represents a coding agent's task. Used to request a new session.
type Job struct {
ID string `json:"job_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
ProblemStatement string `json:"problem_statement,omitempty"`
CustomAgent string `json:"custom_agent,omitempty"`
EventType string `json:"event_type,omitempty"`
ContentFilterMode string `json:"content_filter_mode,omitempty"`
Status string `json:"status,omitempty"`
Result string `json:"result,omitempty"`
Actor *JobActor `json:"actor,omitempty"`
CreatedAt time.Time `json:"created_at,omitempty"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
PullRequest *JobPullRequest `json:"pull_request,omitempty"`
WorkflowRun *struct {
ID string `json:"id"`
} `json:"workflow_run,omitempty"`
ErrorInfo *JobError `json:"error,omitempty"`
}
type JobActor struct {
ID int `json:"id"`
Login string `json:"login"`
}
type JobPullRequest struct {
ID int `json:"id"`
Number int `json:"number"`
BaseRef string `json:"base_ref,omitempty"`
}
type JobError struct {
Message string `json:"message"`
ResponseStatusCode int `json:"response_status_code,string"`
Service string `json:"service"`
}
const jobsBasePathV1 = baseCAPIURL + "/agents/swe/v1/jobs"
// CreateJob queues a new job using the v1 Jobs API. It may or may not
// return Pull Request information. If Pull Request information is required
// following up by polling GetJob with the job ID is necessary.
func (c *CAPIClient) CreateJob(ctx context.Context, owner, repo, problemStatement, baseBranch, customAgent string) (*Job, error) {
if owner == "" || repo == "" {
return nil, errors.New("owner and repo are required")
}
if problemStatement == "" {
return nil, errors.New("problem statement is required")
}
url := fmt.Sprintf("%s/%s/%s", jobsBasePathV1, url.PathEscape(owner), url.PathEscape(repo))
prOpts := JobPullRequest{}
if baseBranch != "" {
prOpts.BaseRef = "refs/heads/" + baseBranch
}
payload := &Job{
ProblemStatement: problemStatement,
CustomAgent: customAgent,
EventType: defaultEventType,
PullRequest: &prOpts,
}
b, _ := json.Marshal(payload)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(b))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
res, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
var j Job
if err := json.NewDecoder(bytes.NewReader(body)).Decode(&j); err != nil {
if res.StatusCode != http.StatusCreated && res.StatusCode != http.StatusOK { // accept 201 or 200
// This happens when there's an error like unauthorized (401).
statusText := fmt.Sprintf("%d %s", res.StatusCode, http.StatusText(res.StatusCode))
return nil, fmt.Errorf("failed to create job: %s", statusText)
}
return nil, fmt.Errorf("failed to decode create job response: %w", err)
}
if res.StatusCode != http.StatusCreated && res.StatusCode != http.StatusOK { // accept 201 or 200
statusText := fmt.Sprintf("%d %s", res.StatusCode, http.StatusText(res.StatusCode))
// If the response has error embeded, we can use that.
// TODO: Does this really ever happen?
if j.ErrorInfo != nil {
return nil, fmt.Errorf("failed to create job: %s: %s", statusText, j.ErrorInfo.Message)
}
// If the response doesn't have error embedded,
// try to decode the response itself as a jobError.
var errInfo JobError
if err := json.NewDecoder(bytes.NewReader(body)).Decode(&errInfo); err != nil {
return nil, fmt.Errorf("failed to create job: %s", statusText)
}
return nil, fmt.Errorf("failed to create job: %s: %s", statusText, errInfo.Message)
}
return &j, nil
}
// GetJob retrieves a agent job
func (c *CAPIClient) GetJob(ctx context.Context, owner, repo, jobID string) (*Job, error) {
if owner == "" || repo == "" || jobID == "" {
return nil, errors.New("owner, repo, and jobID are required")
}
url := fmt.Sprintf("%s/%s/%s/%s", jobsBasePathV1, url.PathEscape(owner), url.PathEscape(repo), url.PathEscape(jobID))
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody)
if err != nil {
return nil, err
}
res, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
// Normalize to "<code> <text>" form
statusText := fmt.Sprintf("%d %s", res.StatusCode, http.StatusText(res.StatusCode))
return nil, fmt.Errorf("failed to get job: %s", statusText)
}
var j Job
if err := json.NewDecoder(res.Body).Decode(&j); err != nil {
return nil, fmt.Errorf("failed to decode get job response: %w", err)
}
return &j, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/agent-task/capi/client.go | pkg/cmd/agent-task/capi/client.go | package capi
import (
"context"
"net/http"
)
//go:generate moq -rm -out client_mock.go . CapiClient
const baseCAPIURL = "https://api.githubcopilot.com"
const capiHost = "api.githubcopilot.com"
// CapiClient defines the methods used by the caller. Implementations
// may be replaced with test doubles in unit tests.
type CapiClient interface {
ListLatestSessionsForViewer(ctx context.Context, limit int) ([]*Session, error)
CreateJob(ctx context.Context, owner, repo, problemStatement, baseBranch string, customAgent string) (*Job, error)
GetJob(ctx context.Context, owner, repo, jobID string) (*Job, error)
GetSession(ctx context.Context, id string) (*Session, error)
GetSessionLogs(ctx context.Context, id string) ([]byte, error)
ListSessionsByResourceID(ctx context.Context, resourceType string, resourceID int64, limit int) ([]*Session, error)
GetPullRequestDatabaseID(ctx context.Context, hostname string, owner string, repo string, number int) (int64, string, error)
}
// CAPIClient is a client for interacting with the Copilot API
type CAPIClient struct {
httpClient *http.Client
host string
}
// NewCAPIClient creates a new CAPI client. Provide a token, host, and an HTTP client which
// will be used as the base transport for CAPI requests.
//
// The provided HTTP client will be mutated for use with CAPI, so it should not
// be reused elsewhere.
func NewCAPIClient(httpClient *http.Client, token string, host string) *CAPIClient {
httpClient.Transport = newCAPITransport(token, httpClient.Transport)
return &CAPIClient{
httpClient: httpClient,
host: host,
}
}
// capiTransport adds the Copilot auth headers
type capiTransport struct {
rp http.RoundTripper
token string
}
func newCAPITransport(token string, rp http.RoundTripper) *capiTransport {
return &capiTransport{
rp: rp,
token: token,
}
}
func (ct *capiTransport) RoundTrip(req *http.Request) (*http.Response, error) {
req.Header.Set("Authorization", "Bearer "+ct.token)
// Since this RoundTrip is reused for both Copilot API and
// GitHub API requests, we conditionally add the integration
// ID only when performing requests to the Copilot API.
if req.URL.Host == capiHost {
req.Header.Add("Copilot-Integration-Id", "copilot-4-cli")
}
return ct.rp.RoundTrip(req)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/agent-task/capi/client_mock.go | pkg/cmd/agent-task/capi/client_mock.go | // Code generated by moq; DO NOT EDIT.
// github.com/matryer/moq
package capi
import (
"context"
"sync"
)
// Ensure, that CapiClientMock does implement CapiClient.
// If this is not the case, regenerate this file with moq.
var _ CapiClient = &CapiClientMock{}
// CapiClientMock is a mock implementation of CapiClient.
//
// func TestSomethingThatUsesCapiClient(t *testing.T) {
//
// // make and configure a mocked CapiClient
// mockedCapiClient := &CapiClientMock{
// CreateJobFunc: func(ctx context.Context, owner string, repo string, problemStatement string, baseBranch string, customAgent string) (*Job, error) {
// panic("mock out the CreateJob method")
// },
// GetJobFunc: func(ctx context.Context, owner string, repo string, jobID string) (*Job, error) {
// panic("mock out the GetJob method")
// },
// GetPullRequestDatabaseIDFunc: func(ctx context.Context, hostname string, owner string, repo string, number int) (int64, string, error) {
// panic("mock out the GetPullRequestDatabaseID method")
// },
// GetSessionFunc: func(ctx context.Context, id string) (*Session, error) {
// panic("mock out the GetSession method")
// },
// GetSessionLogsFunc: func(ctx context.Context, id string) ([]byte, error) {
// panic("mock out the GetSessionLogs method")
// },
// ListLatestSessionsForViewerFunc: func(ctx context.Context, limit int) ([]*Session, error) {
// panic("mock out the ListLatestSessionsForViewer method")
// },
// ListSessionsByResourceIDFunc: func(ctx context.Context, resourceType string, resourceID int64, limit int) ([]*Session, error) {
// panic("mock out the ListSessionsByResourceID method")
// },
// }
//
// // use mockedCapiClient in code that requires CapiClient
// // and then make assertions.
//
// }
type CapiClientMock struct {
// CreateJobFunc mocks the CreateJob method.
CreateJobFunc func(ctx context.Context, owner string, repo string, problemStatement string, baseBranch string, customAgent string) (*Job, error)
// GetJobFunc mocks the GetJob method.
GetJobFunc func(ctx context.Context, owner string, repo string, jobID string) (*Job, error)
// GetPullRequestDatabaseIDFunc mocks the GetPullRequestDatabaseID method.
GetPullRequestDatabaseIDFunc func(ctx context.Context, hostname string, owner string, repo string, number int) (int64, string, error)
// GetSessionFunc mocks the GetSession method.
GetSessionFunc func(ctx context.Context, id string) (*Session, error)
// GetSessionLogsFunc mocks the GetSessionLogs method.
GetSessionLogsFunc func(ctx context.Context, id string) ([]byte, error)
// ListLatestSessionsForViewerFunc mocks the ListLatestSessionsForViewer method.
ListLatestSessionsForViewerFunc func(ctx context.Context, limit int) ([]*Session, error)
// ListSessionsByResourceIDFunc mocks the ListSessionsByResourceID method.
ListSessionsByResourceIDFunc func(ctx context.Context, resourceType string, resourceID int64, limit int) ([]*Session, error)
// calls tracks calls to the methods.
calls struct {
// CreateJob holds details about calls to the CreateJob method.
CreateJob []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Owner is the owner argument value.
Owner string
// Repo is the repo argument value.
Repo string
// ProblemStatement is the problemStatement argument value.
ProblemStatement string
// BaseBranch is the baseBranch argument value.
BaseBranch string
// CustomAgent is the customAgent argument value.
CustomAgent string
}
// GetJob holds details about calls to the GetJob method.
GetJob []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Owner is the owner argument value.
Owner string
// Repo is the repo argument value.
Repo string
// JobID is the jobID argument value.
JobID string
}
// GetPullRequestDatabaseID holds details about calls to the GetPullRequestDatabaseID method.
GetPullRequestDatabaseID []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Hostname is the hostname argument value.
Hostname string
// Owner is the owner argument value.
Owner string
// Repo is the repo argument value.
Repo string
// Number is the number argument value.
Number int
}
// GetSession holds details about calls to the GetSession method.
GetSession []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// ID is the id argument value.
ID string
}
// GetSessionLogs holds details about calls to the GetSessionLogs method.
GetSessionLogs []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// ID is the id argument value.
ID string
}
// ListLatestSessionsForViewer holds details about calls to the ListLatestSessionsForViewer method.
ListLatestSessionsForViewer []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// Limit is the limit argument value.
Limit int
}
// ListSessionsByResourceID holds details about calls to the ListSessionsByResourceID method.
ListSessionsByResourceID []struct {
// Ctx is the ctx argument value.
Ctx context.Context
// ResourceType is the resourceType argument value.
ResourceType string
// ResourceID is the resourceID argument value.
ResourceID int64
// Limit is the limit argument value.
Limit int
}
}
lockCreateJob sync.RWMutex
lockGetJob sync.RWMutex
lockGetPullRequestDatabaseID sync.RWMutex
lockGetSession sync.RWMutex
lockGetSessionLogs sync.RWMutex
lockListLatestSessionsForViewer sync.RWMutex
lockListSessionsByResourceID sync.RWMutex
}
// CreateJob calls CreateJobFunc.
func (mock *CapiClientMock) CreateJob(ctx context.Context, owner string, repo string, problemStatement string, baseBranch string, customAgent string) (*Job, error) {
if mock.CreateJobFunc == nil {
panic("CapiClientMock.CreateJobFunc: method is nil but CapiClient.CreateJob was just called")
}
callInfo := struct {
Ctx context.Context
Owner string
Repo string
ProblemStatement string
BaseBranch string
CustomAgent string
}{
Ctx: ctx,
Owner: owner,
Repo: repo,
ProblemStatement: problemStatement,
BaseBranch: baseBranch,
CustomAgent: customAgent,
}
mock.lockCreateJob.Lock()
mock.calls.CreateJob = append(mock.calls.CreateJob, callInfo)
mock.lockCreateJob.Unlock()
return mock.CreateJobFunc(ctx, owner, repo, problemStatement, baseBranch, customAgent)
}
// CreateJobCalls gets all the calls that were made to CreateJob.
// Check the length with:
//
// len(mockedCapiClient.CreateJobCalls())
func (mock *CapiClientMock) CreateJobCalls() []struct {
Ctx context.Context
Owner string
Repo string
ProblemStatement string
BaseBranch string
CustomAgent string
} {
var calls []struct {
Ctx context.Context
Owner string
Repo string
ProblemStatement string
BaseBranch string
CustomAgent string
}
mock.lockCreateJob.RLock()
calls = mock.calls.CreateJob
mock.lockCreateJob.RUnlock()
return calls
}
// GetJob calls GetJobFunc.
func (mock *CapiClientMock) GetJob(ctx context.Context, owner string, repo string, jobID string) (*Job, error) {
if mock.GetJobFunc == nil {
panic("CapiClientMock.GetJobFunc: method is nil but CapiClient.GetJob was just called")
}
callInfo := struct {
Ctx context.Context
Owner string
Repo string
JobID string
}{
Ctx: ctx,
Owner: owner,
Repo: repo,
JobID: jobID,
}
mock.lockGetJob.Lock()
mock.calls.GetJob = append(mock.calls.GetJob, callInfo)
mock.lockGetJob.Unlock()
return mock.GetJobFunc(ctx, owner, repo, jobID)
}
// GetJobCalls gets all the calls that were made to GetJob.
// Check the length with:
//
// len(mockedCapiClient.GetJobCalls())
func (mock *CapiClientMock) GetJobCalls() []struct {
Ctx context.Context
Owner string
Repo string
JobID string
} {
var calls []struct {
Ctx context.Context
Owner string
Repo string
JobID string
}
mock.lockGetJob.RLock()
calls = mock.calls.GetJob
mock.lockGetJob.RUnlock()
return calls
}
// GetPullRequestDatabaseID calls GetPullRequestDatabaseIDFunc.
func (mock *CapiClientMock) GetPullRequestDatabaseID(ctx context.Context, hostname string, owner string, repo string, number int) (int64, string, error) {
if mock.GetPullRequestDatabaseIDFunc == nil {
panic("CapiClientMock.GetPullRequestDatabaseIDFunc: method is nil but CapiClient.GetPullRequestDatabaseID was just called")
}
callInfo := struct {
Ctx context.Context
Hostname string
Owner string
Repo string
Number int
}{
Ctx: ctx,
Hostname: hostname,
Owner: owner,
Repo: repo,
Number: number,
}
mock.lockGetPullRequestDatabaseID.Lock()
mock.calls.GetPullRequestDatabaseID = append(mock.calls.GetPullRequestDatabaseID, callInfo)
mock.lockGetPullRequestDatabaseID.Unlock()
return mock.GetPullRequestDatabaseIDFunc(ctx, hostname, owner, repo, number)
}
// GetPullRequestDatabaseIDCalls gets all the calls that were made to GetPullRequestDatabaseID.
// Check the length with:
//
// len(mockedCapiClient.GetPullRequestDatabaseIDCalls())
func (mock *CapiClientMock) GetPullRequestDatabaseIDCalls() []struct {
Ctx context.Context
Hostname string
Owner string
Repo string
Number int
} {
var calls []struct {
Ctx context.Context
Hostname string
Owner string
Repo string
Number int
}
mock.lockGetPullRequestDatabaseID.RLock()
calls = mock.calls.GetPullRequestDatabaseID
mock.lockGetPullRequestDatabaseID.RUnlock()
return calls
}
// GetSession calls GetSessionFunc.
func (mock *CapiClientMock) GetSession(ctx context.Context, id string) (*Session, error) {
if mock.GetSessionFunc == nil {
panic("CapiClientMock.GetSessionFunc: method is nil but CapiClient.GetSession was just called")
}
callInfo := struct {
Ctx context.Context
ID string
}{
Ctx: ctx,
ID: id,
}
mock.lockGetSession.Lock()
mock.calls.GetSession = append(mock.calls.GetSession, callInfo)
mock.lockGetSession.Unlock()
return mock.GetSessionFunc(ctx, id)
}
// GetSessionCalls gets all the calls that were made to GetSession.
// Check the length with:
//
// len(mockedCapiClient.GetSessionCalls())
func (mock *CapiClientMock) GetSessionCalls() []struct {
Ctx context.Context
ID string
} {
var calls []struct {
Ctx context.Context
ID string
}
mock.lockGetSession.RLock()
calls = mock.calls.GetSession
mock.lockGetSession.RUnlock()
return calls
}
// GetSessionLogs calls GetSessionLogsFunc.
func (mock *CapiClientMock) GetSessionLogs(ctx context.Context, id string) ([]byte, error) {
if mock.GetSessionLogsFunc == nil {
panic("CapiClientMock.GetSessionLogsFunc: method is nil but CapiClient.GetSessionLogs was just called")
}
callInfo := struct {
Ctx context.Context
ID string
}{
Ctx: ctx,
ID: id,
}
mock.lockGetSessionLogs.Lock()
mock.calls.GetSessionLogs = append(mock.calls.GetSessionLogs, callInfo)
mock.lockGetSessionLogs.Unlock()
return mock.GetSessionLogsFunc(ctx, id)
}
// GetSessionLogsCalls gets all the calls that were made to GetSessionLogs.
// Check the length with:
//
// len(mockedCapiClient.GetSessionLogsCalls())
func (mock *CapiClientMock) GetSessionLogsCalls() []struct {
Ctx context.Context
ID string
} {
var calls []struct {
Ctx context.Context
ID string
}
mock.lockGetSessionLogs.RLock()
calls = mock.calls.GetSessionLogs
mock.lockGetSessionLogs.RUnlock()
return calls
}
// ListLatestSessionsForViewer calls ListLatestSessionsForViewerFunc.
func (mock *CapiClientMock) ListLatestSessionsForViewer(ctx context.Context, limit int) ([]*Session, error) {
if mock.ListLatestSessionsForViewerFunc == nil {
panic("CapiClientMock.ListLatestSessionsForViewerFunc: method is nil but CapiClient.ListLatestSessionsForViewer was just called")
}
callInfo := struct {
Ctx context.Context
Limit int
}{
Ctx: ctx,
Limit: limit,
}
mock.lockListLatestSessionsForViewer.Lock()
mock.calls.ListLatestSessionsForViewer = append(mock.calls.ListLatestSessionsForViewer, callInfo)
mock.lockListLatestSessionsForViewer.Unlock()
return mock.ListLatestSessionsForViewerFunc(ctx, limit)
}
// ListLatestSessionsForViewerCalls gets all the calls that were made to ListLatestSessionsForViewer.
// Check the length with:
//
// len(mockedCapiClient.ListLatestSessionsForViewerCalls())
func (mock *CapiClientMock) ListLatestSessionsForViewerCalls() []struct {
Ctx context.Context
Limit int
} {
var calls []struct {
Ctx context.Context
Limit int
}
mock.lockListLatestSessionsForViewer.RLock()
calls = mock.calls.ListLatestSessionsForViewer
mock.lockListLatestSessionsForViewer.RUnlock()
return calls
}
// ListSessionsByResourceID calls ListSessionsByResourceIDFunc.
func (mock *CapiClientMock) ListSessionsByResourceID(ctx context.Context, resourceType string, resourceID int64, limit int) ([]*Session, error) {
if mock.ListSessionsByResourceIDFunc == nil {
panic("CapiClientMock.ListSessionsByResourceIDFunc: method is nil but CapiClient.ListSessionsByResourceID was just called")
}
callInfo := struct {
Ctx context.Context
ResourceType string
ResourceID int64
Limit int
}{
Ctx: ctx,
ResourceType: resourceType,
ResourceID: resourceID,
Limit: limit,
}
mock.lockListSessionsByResourceID.Lock()
mock.calls.ListSessionsByResourceID = append(mock.calls.ListSessionsByResourceID, callInfo)
mock.lockListSessionsByResourceID.Unlock()
return mock.ListSessionsByResourceIDFunc(ctx, resourceType, resourceID, limit)
}
// ListSessionsByResourceIDCalls gets all the calls that were made to ListSessionsByResourceID.
// Check the length with:
//
// len(mockedCapiClient.ListSessionsByResourceIDCalls())
func (mock *CapiClientMock) ListSessionsByResourceIDCalls() []struct {
Ctx context.Context
ResourceType string
ResourceID int64
Limit int
} {
var calls []struct {
Ctx context.Context
ResourceType string
ResourceID int64
Limit int
}
mock.lockListSessionsByResourceID.RLock()
calls = mock.calls.ListSessionsByResourceID
mock.lockListSessionsByResourceID.RUnlock()
return calls
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/agent-task/capi/sessions_test.go | pkg/cmd/agent-task/capi/sessions_test.go | package capi
import (
"context"
"net/http"
"net/url"
"testing"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestListLatestSessionsForViewer(t *testing.T) {
sampleDateString := "2025-08-29T00:00:00Z"
sampleDate, err := time.Parse(time.RFC3339, sampleDateString)
require.NoError(t, err)
tests := []struct {
name string
perPage int
limit int
httpStubs func(*testing.T, *httpmock.Registry)
wantErr string
wantOut []*Session
}{
{
name: "zero limit",
limit: 0,
wantOut: nil,
},
{
name: "no sessions",
limit: 10,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.WithHost(
httpmock.QueryMatcher("GET", "agents/sessions", url.Values{
"page_number": {"1"},
"page_size": {"50"},
}),
"api.githubcopilot.com",
),
httpmock.StringResponse(`{"sessions":[]}`),
)
},
wantOut: nil,
},
{
name: "single session",
limit: 10,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.WithHost(
httpmock.QueryMatcher("GET", "agents/sessions", url.Values{
"page_number": {"1"},
"page_size": {"50"},
}),
"api.githubcopilot.com",
),
httpmock.StringResponse(heredoc.Docf(`
{
"sessions": [
{
"id": "sess1",
"name": "Build artifacts",
"user_id": 1,
"agent_id": 2,
"logs": "",
"state": "completed",
"owner_id": 10,
"repo_id": 1000,
"resource_type": "pull",
"resource_id": 2000,
"created_at": "%[1]s",
"premium_requests": 0.1
}
]
}`,
sampleDateString,
)),
)
// GraphQL hydration
reg.Register(
httpmock.GraphQL(`query FetchPRsAndUsersForAgentTaskSessions\b`),
httpmock.GraphQLQuery(heredoc.Docf(`
{
"data": {
"nodes": [
{
"__typename": "PullRequest",
"id": "PR_node",
"fullDatabaseId": "2000",
"number": 42,
"title": "Improve docs",
"state": "OPEN",
"isDraft": true,
"url": "https://github.com/OWNER/REPO/pull/42",
"body": "",
"createdAt": "%[1]s",
"updatedAt": "%[1]s",
"repository": {
"nameWithOwner": "OWNER/REPO"
}
},
{
"__typename": "User",
"login": "octocat",
"name": "Octocat",
"databaseId": 1
}
]
}
}`,
sampleDateString,
), func(q string, vars map[string]interface{}) {
assert.Equal(t, []interface{}{"PR_kwDNA-jNB9A", "U_kgAB"}, vars["ids"])
}),
)
},
wantOut: []*Session{
{
ID: "sess1",
Name: "Build artifacts",
UserID: 1,
AgentID: 2,
Logs: "",
State: "completed",
OwnerID: 10,
RepoID: 1000,
ResourceType: "pull",
ResourceID: 2000,
CreatedAt: sampleDate,
PremiumRequests: 0.1,
PullRequest: &api.PullRequest{
ID: "PR_node",
FullDatabaseID: "2000",
Number: 42,
Title: "Improve docs",
State: "OPEN",
IsDraft: true,
URL: "https://github.com/OWNER/REPO/pull/42",
Body: "",
CreatedAt: sampleDate,
UpdatedAt: sampleDate,
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
User: &api.GitHubUser{
Login: "octocat",
Name: "Octocat",
DatabaseID: 1,
},
},
},
},
{
// This happens at the early moments of a session lifecycle, before a PR is created and associated with it.
name: "single session, no pull request resource",
limit: 10,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.WithHost(
httpmock.QueryMatcher("GET", "agents/sessions", url.Values{
"page_number": {"1"},
"page_size": {"50"},
}),
"api.githubcopilot.com",
),
httpmock.StringResponse(heredoc.Docf(`
{
"sessions": [
{
"id": "sess1",
"name": "Build artifacts",
"user_id": 1,
"agent_id": 2,
"logs": "",
"state": "completed",
"owner_id": 10,
"repo_id": 1000,
"resource_type": "",
"resource_id": 0,
"created_at": "%[1]s",
"premium_requests": 0.1
}
]
}`,
sampleDateString,
)),
)
// GraphQL hydration
reg.Register(
httpmock.GraphQL(`query FetchPRsAndUsersForAgentTaskSessions\b`),
httpmock.GraphQLQuery(heredoc.Docf(`
{
"data": {
"nodes": [
{
"__typename": "User",
"login": "octocat",
"name": "Octocat",
"databaseId": 1
}
]
}
}`,
sampleDateString,
), func(q string, vars map[string]interface{}) {
assert.Equal(t, []interface{}{"U_kgAB"}, vars["ids"])
}),
)
},
wantOut: []*Session{
{
ID: "sess1",
Name: "Build artifacts",
UserID: 1,
AgentID: 2,
Logs: "",
State: "completed",
OwnerID: 10,
RepoID: 1000,
ResourceType: "",
ResourceID: 0,
CreatedAt: sampleDate,
PremiumRequests: 0.1,
User: &api.GitHubUser{
Login: "octocat",
Name: "Octocat",
DatabaseID: 1,
},
},
},
},
{
name: "multiple sessions, paginated",
perPage: 1, // to enforce pagination
limit: 2,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.WithHost(
httpmock.QueryMatcher("GET", "agents/sessions", url.Values{
"page_number": {"1"},
"page_size": {"1"},
}),
"api.githubcopilot.com",
),
httpmock.StringResponse(heredoc.Docf(`
{
"sessions": [
{
"id": "sess1",
"name": "Build artifacts",
"user_id": 1,
"agent_id": 2,
"logs": "",
"state": "completed",
"owner_id": 10,
"repo_id": 1000,
"resource_type": "pull",
"resource_id": 2000,
"created_at": "%[1]s",
"premium_requests": 0.1
}
]
}`,
sampleDateString,
)),
)
// Second page
reg.Register(
httpmock.WithHost(
httpmock.QueryMatcher("GET", "agents/sessions", url.Values{
"page_number": {"2"},
"page_size": {"1"},
}),
"api.githubcopilot.com",
),
httpmock.StringResponse(heredoc.Docf(`
{
"sessions": [
{
"id": "sess2",
"name": "Build artifacts",
"user_id": 1,
"agent_id": 2,
"logs": "",
"state": "completed",
"owner_id": 10,
"repo_id": 1000,
"resource_type": "pull",
"resource_id": 2001,
"created_at": "%[1]s",
"premium_requests": 0.1
}
]
}`,
sampleDateString,
)),
)
// GraphQL hydration
reg.Register(
httpmock.GraphQL(`query FetchPRsAndUsersForAgentTaskSessions\b`),
httpmock.GraphQLQuery(heredoc.Docf(`
{
"data": {
"nodes": [
{
"__typename": "PullRequest",
"id": "PR_node",
"fullDatabaseId": "2000",
"number": 42,
"title": "Improve docs",
"state": "OPEN",
"isDraft": true,
"url": "https://github.com/OWNER/REPO/pull/42",
"body": "",
"createdAt": "%[1]s",
"updatedAt": "%[1]s",
"repository": {
"nameWithOwner": "OWNER/REPO"
}
},
{
"__typename": "PullRequest",
"id": "PR_node",
"fullDatabaseId": "2001",
"number": 43,
"title": "Improve docs",
"state": "OPEN",
"isDraft": true,
"url": "https://github.com/OWNER/REPO/pull/43",
"body": "",
"createdAt": "%[1]s",
"updatedAt": "%[1]s",
"repository": {
"nameWithOwner": "OWNER/REPO"
}
},
{
"__typename": "User",
"login": "octocat",
"name": "Octocat",
"databaseId": 1
}
]
}
}`,
sampleDateString,
), func(q string, vars map[string]interface{}) {
assert.Equal(t, []interface{}{"PR_kwDNA-jNB9A", "PR_kwDNA-jNB9E", "U_kgAB"}, vars["ids"])
}),
)
},
wantOut: []*Session{
{
ID: "sess1",
Name: "Build artifacts",
UserID: 1,
AgentID: 2,
Logs: "",
State: "completed",
OwnerID: 10,
RepoID: 1000,
ResourceType: "pull",
ResourceID: 2000,
CreatedAt: sampleDate,
PremiumRequests: 0.1,
PullRequest: &api.PullRequest{
ID: "PR_node",
FullDatabaseID: "2000",
Number: 42,
Title: "Improve docs",
State: "OPEN",
IsDraft: true,
URL: "https://github.com/OWNER/REPO/pull/42",
Body: "",
CreatedAt: sampleDate,
UpdatedAt: sampleDate,
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
User: &api.GitHubUser{
Login: "octocat",
Name: "Octocat",
DatabaseID: 1,
},
},
{
ID: "sess2",
Name: "Build artifacts",
UserID: 1,
AgentID: 2,
Logs: "",
State: "completed",
OwnerID: 10,
RepoID: 1000,
ResourceType: "pull",
ResourceID: 2001,
CreatedAt: sampleDate,
PremiumRequests: 0.1,
PullRequest: &api.PullRequest{
ID: "PR_node",
FullDatabaseID: "2001",
Number: 43,
Title: "Improve docs",
State: "OPEN",
IsDraft: true,
URL: "https://github.com/OWNER/REPO/pull/43",
Body: "",
CreatedAt: sampleDate,
UpdatedAt: sampleDate,
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
User: &api.GitHubUser{
Login: "octocat",
Name: "Octocat",
DatabaseID: 1,
},
},
},
},
{
name: "multiple pages with duplicates per PR only newest kept",
perPage: 2,
limit: 3,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
// Page 1 returns newest sessions (ordered newest first overall)
reg.Register(
httpmock.WithHost(
httpmock.QueryMatcher("GET", "agents/sessions", url.Values{
"page_number": {"1"},
"page_size": {"2"},
"sort": {"last_updated_at,desc"},
}),
"api.githubcopilot.com",
),
httpmock.StringResponse(heredoc.Docf(`
{
"sessions": [
{
"id": "sessA-new",
"name": "Build artifacts",
"user_id": 1,
"agent_id": 2,
"logs": "",
"state": "completed",
"owner_id": 10,
"repo_id": 1000,
"resource_type": "pull",
"resource_id": 3000,
"created_at": "%[1]s"
},
{
"id": "sessB-new",
"name": "Build artifacts",
"user_id": 1,
"agent_id": 2,
"logs": "",
"state": "completed",
"owner_id": 10,
"repo_id": 1000,
"resource_type": "pull",
"resource_id": 3001,
"created_at": "%[1]s"
}
]
}`,
sampleDateString,
)),
)
// Page 2 returns older duplicate sessions for 3000, plus another new PR 3002
reg.Register(
httpmock.WithHost(
httpmock.QueryMatcher("GET", "agents/sessions", url.Values{
"page_number": {"2"},
"page_size": {"2"},
"sort": {"last_updated_at,desc"},
}),
"api.githubcopilot.com",
),
httpmock.StringResponse(heredoc.Docf(`
{
"sessions": [
{
"id": "sessA-old",
"name": "Build artifacts",
"user_id": 1,
"agent_id": 2,
"logs": "",
"state": "completed",
"owner_id": 10,
"repo_id": 1000,
"resource_type": "pull",
"resource_id": 3000,
"created_at": "%[1]s"
},
{
"id": "sessC-new",
"name": "Build artifacts",
"user_id": 1,
"agent_id": 2,
"logs": "",
"state": "completed",
"owner_id": 10,
"repo_id": 1000,
"resource_type": "pull",
"resource_id": 3002,
"created_at": "%[1]s"
}
]
}`,
sampleDateString,
)),
)
// GraphQL hydration for PRs 3000, 3001, 3002 and user 1
reg.Register(
httpmock.GraphQL(`query FetchPRsAndUsersForAgentTaskSessions\b`),
httpmock.GraphQLQuery(heredoc.Docf(`
{
"data": {
"nodes": [
{
"__typename": "PullRequest",
"id": "PR_node3000",
"fullDatabaseId": "3000",
"number": 100,
"title": "Improve docs",
"state": "OPEN",
"isDraft": true,
"url": "https://github.com/OWNER/REPO/pull/100",
"body": "",
"createdAt": "%[1]s",
"updatedAt": "%[1]s",
"repository": {"nameWithOwner": "OWNER/REPO"}
},
{
"__typename": "PullRequest",
"id": "PR_node3001",
"fullDatabaseId": "3001",
"number": 101,
"title": "Improve docs",
"state": "OPEN",
"isDraft": true,
"url": "https://github.com/OWNER/REPO/pull/101",
"body": "",
"createdAt": "%[1]s",
"updatedAt": "%[1]s",
"repository": {"nameWithOwner": "OWNER/REPO"}
},
{
"__typename": "PullRequest",
"id": "PR_node3002",
"fullDatabaseId": "3002",
"number": 102,
"title": "Improve docs",
"state": "OPEN",
"isDraft": true,
"url": "https://github.com/OWNER/REPO/pull/102",
"body": "",
"createdAt": "%[1]s",
"updatedAt": "%[1]s",
"repository": {"nameWithOwner": "OWNER/REPO"}
},
{
"__typename": "User",
"login": "octocat",
"name": "Octocat",
"databaseId": 1
}
]
}
}`,
sampleDateString,
), func(q string, vars map[string]interface{}) {
// Expected encoded node IDs for resource IDs 3000,3001,3002 and user octocat
assert.Equal(t, []interface{}{"PR_kwDNA-jNC7g", "PR_kwDNA-jNC7k", "PR_kwDNA-jNC7o", "U_kgAB"}, vars["ids"])
}),
)
},
wantOut: []*Session{
{
ID: "sessA-new",
Name: "Build artifacts",
UserID: 1,
AgentID: 2,
Logs: "",
State: "completed",
OwnerID: 10,
RepoID: 1000,
ResourceType: "pull",
ResourceID: 3000,
CreatedAt: sampleDate,
PullRequest: &api.PullRequest{
ID: "PR_node3000",
FullDatabaseID: "3000",
Number: 100,
Title: "Improve docs",
State: "OPEN",
IsDraft: true,
URL: "https://github.com/OWNER/REPO/pull/100",
Body: "",
CreatedAt: sampleDate,
UpdatedAt: sampleDate,
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
User: &api.GitHubUser{Login: "octocat", Name: "Octocat", DatabaseID: 1},
},
{
ID: "sessB-new",
Name: "Build artifacts",
UserID: 1,
AgentID: 2,
Logs: "",
State: "completed",
OwnerID: 10,
RepoID: 1000,
ResourceType: "pull",
ResourceID: 3001,
CreatedAt: sampleDate,
PullRequest: &api.PullRequest{
ID: "PR_node3001",
FullDatabaseID: "3001",
Number: 101,
Title: "Improve docs",
State: "OPEN",
IsDraft: true,
URL: "https://github.com/OWNER/REPO/pull/101",
Body: "",
CreatedAt: sampleDate,
UpdatedAt: sampleDate,
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
User: &api.GitHubUser{Login: "octocat", Name: "Octocat", DatabaseID: 1},
},
{
ID: "sessC-new",
Name: "Build artifacts",
UserID: 1,
AgentID: 2,
Logs: "",
State: "completed",
OwnerID: 10,
RepoID: 1000,
ResourceType: "pull",
ResourceID: 3002,
CreatedAt: sampleDate,
PullRequest: &api.PullRequest{
ID: "PR_node3002",
FullDatabaseID: "3002",
Number: 102,
Title: "Improve docs",
State: "OPEN",
IsDraft: true,
URL: "https://github.com/OWNER/REPO/pull/102",
Body: "",
CreatedAt: sampleDate,
UpdatedAt: sampleDate,
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
User: &api.GitHubUser{Login: "octocat", Name: "Octocat", DatabaseID: 1},
},
},
},
{
name: "multiple pages with zero resource IDs all kept",
perPage: 2,
limit: 3,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
// Page 1 returns newest sessions, one with a zero resource ID
reg.Register(
httpmock.WithHost(
httpmock.QueryMatcher("GET", "agents/sessions", url.Values{
"page_number": {"1"},
"page_size": {"2"},
"sort": {"last_updated_at,desc"},
}),
"api.githubcopilot.com",
),
httpmock.StringResponse(heredoc.Docf(`
{
"sessions": [
{
"id": "sessA-new",
"name": "Build artifacts",
"user_id": 1,
"agent_id": 2,
"logs": "",
"state": "completed",
"owner_id": 10,
"repo_id": 1000,
"resource_type": "pull",
"resource_id": 3000,
"created_at": "%[1]s"
},
{
"id": "sessB-new",
"name": "Build artifacts",
"user_id": 1,
"agent_id": 2,
"logs": "",
"state": "queued",
"owner_id": 10,
"repo_id": 1000,
"resource_type": "",
"resource_id": 0,
"created_at": "%[1]s"
}
]
}`,
sampleDateString,
)),
)
// Page 2 returns older duplicate sessions for 3000, plus another new session with zero resource ID
reg.Register(
httpmock.WithHost(
httpmock.QueryMatcher("GET", "agents/sessions", url.Values{
"page_number": {"2"},
"page_size": {"2"},
"sort": {"last_updated_at,desc"},
}),
"api.githubcopilot.com",
),
httpmock.StringResponse(heredoc.Docf(`
{
"sessions": [
{
"id": "sessA-old",
"name": "Build artifacts",
"user_id": 1,
"agent_id": 2,
"logs": "",
"state": "completed",
"owner_id": 10,
"repo_id": 1000,
"resource_type": "pull",
"resource_id": 3000,
"created_at": "%[1]s"
},
{
"id": "sessC-new",
"name": "Build artifacts",
"user_id": 1,
"agent_id": 2,
"logs": "",
"state": "queued",
"owner_id": 10,
"repo_id": 1000,
"resource_type": "",
"resource_id": 0,
"created_at": "%[1]s"
}
]
}`,
sampleDateString,
)),
)
// GraphQL hydration for PRs 3000 and user 1
reg.Register(
httpmock.GraphQL(`query FetchPRsAndUsersForAgentTaskSessions\b`),
httpmock.GraphQLQuery(heredoc.Docf(`
{
"data": {
"nodes": [
{
"__typename": "PullRequest",
"id": "PR_node3000",
"fullDatabaseId": "3000",
"number": 100,
"title": "Improve docs",
"state": "OPEN",
"isDraft": true,
"url": "https://github.com/OWNER/REPO/pull/100",
"body": "",
"createdAt": "%[1]s",
"updatedAt": "%[1]s",
"repository": {"nameWithOwner": "OWNER/REPO"}
},
{
"__typename": "User",
"login": "octocat",
"name": "Octocat",
"databaseId": 1
}
]
}
}`,
sampleDateString,
), func(q string, vars map[string]interface{}) {
// Expected encoded node IDs for resource IDs 3000 and user octocat
assert.Equal(t, []interface{}{"PR_kwDNA-jNC7g", "U_kgAB"}, vars["ids"])
}),
)
},
wantOut: []*Session{
{
ID: "sessA-new",
Name: "Build artifacts",
UserID: 1,
AgentID: 2,
Logs: "",
State: "completed",
OwnerID: 10,
RepoID: 1000,
ResourceType: "pull",
ResourceID: 3000,
CreatedAt: sampleDate,
PullRequest: &api.PullRequest{
ID: "PR_node3000",
FullDatabaseID: "3000",
Number: 100,
Title: "Improve docs",
State: "OPEN",
IsDraft: true,
URL: "https://github.com/OWNER/REPO/pull/100",
Body: "",
CreatedAt: sampleDate,
UpdatedAt: sampleDate,
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
User: &api.GitHubUser{Login: "octocat", Name: "Octocat", DatabaseID: 1},
},
{
ID: "sessB-new",
Name: "Build artifacts",
UserID: 1,
AgentID: 2,
Logs: "",
State: "queued",
OwnerID: 10,
RepoID: 1000,
ResourceType: "",
ResourceID: 0,
CreatedAt: sampleDate,
User: &api.GitHubUser{Login: "octocat", Name: "Octocat", DatabaseID: 1},
},
{
ID: "sessC-new",
Name: "Build artifacts",
UserID: 1,
AgentID: 2,
Logs: "",
State: "queued",
OwnerID: 10,
RepoID: 1000,
ResourceType: "",
ResourceID: 0,
CreatedAt: sampleDate,
User: &api.GitHubUser{Login: "octocat", Name: "Octocat", DatabaseID: 1},
},
},
},
{
name: "session error is included",
limit: 10,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.WithHost(
httpmock.QueryMatcher("GET", "agents/sessions", url.Values{
"page_number": {"1"},
"page_size": {"50"},
"sort": {"last_updated_at,desc"},
}),
"api.githubcopilot.com",
),
httpmock.StringResponse(heredoc.Docf(`
{
"sessions": [
{
"id": "sessA",
"name": "Build artifacts",
"user_id": 1,
"agent_id": 2,
"logs": "",
"state": "failed",
"owner_id": 10,
"repo_id": 1000,
"resource_type": "pull",
"resource_id": 3000,
"created_at": "%[1]s",
"error": {
"code": "some-error-code",
"message": "some-error-message"
}
}
]
}`,
sampleDateString,
)),
)
// GraphQL hydration
reg.Register(
httpmock.GraphQL(`query FetchPRsAndUsersForAgentTaskSessions\b`),
httpmock.GraphQLQuery(heredoc.Docf(`
{
"data": {
"nodes": [
{
"__typename": "PullRequest",
"id": "PR_node3000",
"fullDatabaseId": "3000",
"number": 100,
"title": "Improve docs",
"state": "OPEN",
"isDraft": true,
"url": "https://github.com/OWNER/REPO/pull/100",
"body": "",
"createdAt": "%[1]s",
"updatedAt": "%[1]s",
"repository": {"nameWithOwner": "OWNER/REPO"}
},
{
"__typename": "User",
"login": "octocat",
"name": "Octocat",
"databaseId": 1
}
]
}
}`,
sampleDateString,
), func(q string, vars map[string]interface{}) {
// Expected encoded node IDs for resource IDs 3000 and user octocat
assert.Equal(t, []interface{}{"PR_kwDNA-jNC7g", "U_kgAB"}, vars["ids"])
}),
)
},
wantOut: []*Session{
{
ID: "sessA",
Name: "Build artifacts",
UserID: 1,
AgentID: 2,
Logs: "",
State: "failed",
OwnerID: 10,
RepoID: 1000,
ResourceType: "pull",
ResourceID: 3000,
CreatedAt: sampleDate,
Error: &SessionError{
Code: "some-error-code",
Message: "some-error-message",
},
PullRequest: &api.PullRequest{
ID: "PR_node3000",
FullDatabaseID: "3000",
Number: 100,
Title: "Improve docs",
State: "OPEN",
IsDraft: true,
URL: "https://github.com/OWNER/REPO/pull/100",
Body: "",
CreatedAt: sampleDate,
UpdatedAt: sampleDate,
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
User: &api.GitHubUser{Login: "octocat", Name: "Octocat", DatabaseID: 1},
},
},
},
{
name: "workflow run id is included",
limit: 10,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.WithHost(
httpmock.QueryMatcher("GET", "agents/sessions", url.Values{
"page_number": {"1"},
"page_size": {"50"},
"sort": {"last_updated_at,desc"},
}),
"api.githubcopilot.com",
),
httpmock.StringResponse(heredoc.Docf(`
{
"sessions": [
{
"id": "sessA",
"name": "Build artifacts",
"user_id": 1,
"agent_id": 2,
"logs": "",
"state": "failed",
"owner_id": 10,
"repo_id": 1000,
"resource_type": "pull",
"resource_id": 3000,
"created_at": "%[1]s",
"workflow_run_id": 9999
}
]
}`,
sampleDateString,
)),
)
// GraphQL hydration
reg.Register(
httpmock.GraphQL(`query FetchPRsAndUsersForAgentTaskSessions\b`),
httpmock.GraphQLQuery(heredoc.Docf(`
{
"data": {
"nodes": [
{
"__typename": "PullRequest",
"id": "PR_node3000",
"fullDatabaseId": "3000",
"number": 100,
"title": "Improve docs",
"state": "OPEN",
"isDraft": true,
"url": "https://github.com/OWNER/REPO/pull/100",
"body": "",
"createdAt": "%[1]s",
"updatedAt": "%[1]s",
"repository": {"nameWithOwner": "OWNER/REPO"}
},
{
"__typename": "User",
"login": "octocat",
"name": "Octocat",
"databaseId": 1
}
]
}
}`,
sampleDateString,
), func(q string, vars map[string]interface{}) {
// Expected encoded node IDs for resource IDs 3000 and user octocat
assert.Equal(t, []interface{}{"PR_kwDNA-jNC7g", "U_kgAB"}, vars["ids"])
}),
)
},
wantOut: []*Session{
{
ID: "sessA",
Name: "Build artifacts",
UserID: 1,
AgentID: 2,
Logs: "",
State: "failed",
OwnerID: 10,
RepoID: 1000,
ResourceType: "pull",
ResourceID: 3000,
CreatedAt: sampleDate,
WorkflowRunID: 9999,
PullRequest: &api.PullRequest{
ID: "PR_node3000",
FullDatabaseID: "3000",
Number: 100,
Title: "Improve docs",
State: "OPEN",
IsDraft: true,
URL: "https://github.com/OWNER/REPO/pull/100",
Body: "",
CreatedAt: sampleDate,
UpdatedAt: sampleDate,
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
User: &api.GitHubUser{Login: "octocat", Name: "Octocat", DatabaseID: 1},
},
},
},
{
name: "API error",
limit: 10,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.WithHost(
httpmock.QueryMatcher("GET", "agents/sessions", url.Values{
"page_number": {"1"},
"page_size": {"50"},
}),
"api.githubcopilot.com",
),
httpmock.StatusStringResponse(500, "{}"),
)
},
wantErr: "failed to list sessions:",
}, {
name: "API error at hydration",
limit: 10,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.WithHost(
httpmock.QueryMatcher("GET", "agents/sessions", url.Values{
"page_number": {"1"},
"page_size": {"50"},
}),
"api.githubcopilot.com",
),
httpmock.StringResponse(heredoc.Docf(`
{
"sessions": [
{
"id": "sess1",
"name": "Build artifacts",
"user_id": 1,
"agent_id": 2,
"logs": "",
"state": "completed",
"owner_id": 10,
"repo_id": 1000,
"resource_type": "pull",
"resource_id": 2000,
"created_at": "%[1]s",
"premium_requests": 0.1
}
]
}`,
sampleDateString,
)),
)
// GraphQL hydration
reg.Register(
httpmock.GraphQL(`query FetchPRsAndUsersForAgentTaskSessions\b`),
httpmock.StatusStringResponse(500, `{}`),
)
},
wantErr: `failed to fetch session resources: non-200 OK status code:`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
if tt.httpStubs != nil {
tt.httpStubs(t, reg)
}
defer reg.Verify(t)
httpClient := &http.Client{Transport: reg}
capiClient := NewCAPIClient(httpClient, "", "github.com")
if tt.perPage != 0 {
last := defaultSessionsPerPage
defaultSessionsPerPage = tt.perPage
defer func() {
defaultSessionsPerPage = last
}()
}
sessions, err := capiClient.ListLatestSessionsForViewer(context.Background(), tt.limit)
if tt.wantErr != "" {
require.ErrorContains(t, err, tt.wantErr)
require.Nil(t, sessions)
return
}
require.NoError(t, err)
require.Equal(t, tt.wantOut, sessions)
})
}
}
func TestListSessionsByResourceIDRequiresResource(t *testing.T) {
client := &CAPIClient{}
_, err := client.ListSessionsByResourceID(context.Background(), "", 999, 0)
assert.EqualError(t, err, "missing resource type/ID")
_, err = client.ListSessionsByResourceID(context.Background(), "only-resource-type", 0, 0)
assert.EqualError(t, err, "missing resource type/ID")
_, err = client.ListSessionsByResourceID(context.Background(), "", 0, 0)
assert.EqualError(t, err, "missing resource type/ID")
}
func TestListSessionsByResourceID(t *testing.T) {
sampleDateString := "2025-08-29T07:00:00Z"
sampleDate, err := time.Parse(time.RFC3339, sampleDateString)
require.NoError(t, err)
sampleDateTimestamp := sampleDate.Unix()
resourceID := int64(999)
resourceType := "pull"
tests := []struct {
name string
perPage int
limit int
httpStubs func(*testing.T, *httpmock.Registry)
wantErr string
wantOut []*Session
}{
{
name: "zero limit",
limit: 0,
wantOut: nil,
},
{
// If the given pull request does not exist or the pull request has no sessions,
// the API endpoint returns 404 with different messages. We should treat them
// the same though.
name: "no sessions or no pull request",
limit: 10,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.WithHost(httpmock.REST("GET", "agents/resource/pull/999"), "api.githubcopilot.com"),
httpmock.StatusStringResponse(404, "{}"),
)
},
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | true |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/agent-task/capi/sessions.go | pkg/cmd/agent-task/capi/sessions.go | package capi
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"net/http"
"net/url"
"slices"
"strconv"
"time"
"github.com/cli/cli/v2/api"
"github.com/shurcooL/githubv4"
"github.com/vmihailenco/msgpack/v5"
)
const AgentsHomeURL = "https://github.com/copilot/agents"
var defaultSessionsPerPage = 50
var ErrSessionNotFound = errors.New("not found")
// session is an in-flight agent task
type session struct {
ID string `json:"id"`
Name string `json:"name"`
UserID int64 `json:"user_id"`
AgentID int64 `json:"agent_id"`
Logs string `json:"logs"`
State string `json:"state"`
OwnerID uint64 `json:"owner_id"`
RepoID uint64 `json:"repo_id"`
ResourceType string `json:"resource_type"`
ResourceID int64 `json:"resource_id"`
ResourceGlobalID string `json:"resource_global_id"`
LastUpdatedAt time.Time `json:"last_updated_at,omitempty"`
CreatedAt time.Time `json:"created_at,omitempty"`
CompletedAt time.Time `json:"completed_at,omitempty"`
EventURL string `json:"event_url"`
EventType string `json:"event_type"`
PremiumRequests float64 `json:"premium_requests"`
WorkflowRunID uint64 `json:"workflow_run_id,omitempty"`
Error *struct {
Code string `json:"code"`
Message string `json:"message"`
} `json:"error,omitempty"`
}
// A shim of a full pull request because looking up by node ID
// using the full api.PullRequest type fails on unions (actors)
type sessionPullRequest struct {
ID string
FullDatabaseID string
Number int
Title string
State string
URL string
Body string
IsDraft bool
CreatedAt time.Time
UpdatedAt time.Time
ClosedAt *time.Time
MergedAt *time.Time
Repository *api.PRRepository
}
// Session is a hydrated in-flight agent task
type Session struct {
ID string
Name string
UserID int64
AgentID int64
Logs string
State string
OwnerID uint64
RepoID uint64
ResourceType string
ResourceID int64
LastUpdatedAt time.Time
CreatedAt time.Time
CompletedAt time.Time
EventURL string
EventType string
PremiumRequests float64
WorkflowRunID uint64
Error *SessionError
PullRequest *api.PullRequest
User *api.GitHubUser
}
type SessionError struct {
Code string
Message string
}
type resource struct {
ID string `json:"id"`
UserID uint64 `json:"user_id"`
ResourceType string `json:"resource_type"`
ResourceID int64 `json:"resource_id"`
ResourceGlobalID string `json:"resource_global_id"`
SessionCount int `json:"session_count"`
SessionLastUpdatedAt int64 `json:"last_updated_at"`
SessionState string `json:"state,omitempty"`
ResourceState string `json:"resource_state"`
Sessions []resourceSession `json:"sessions"`
}
type resourceSession struct {
SessionID string `json:"id"`
Name string `json:"name"`
SessionState string `json:"state,omitempty"`
SessionLastUpdatedAt int64 `json:"last_updated_at"`
}
// ListLatestSessionsForViewer lists all agent sessions for the
// authenticated user up to limit.
func (c *CAPIClient) ListLatestSessionsForViewer(ctx context.Context, limit int) ([]*Session, error) {
if limit == 0 {
return nil, nil
}
url := baseCAPIURL + "/agents/sessions"
pageSize := defaultSessionsPerPage
seenResources := make(map[int64]struct{})
latestSessions := make([]session, 0, limit)
for page := 1; ; page++ {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody)
if err != nil {
return nil, err
}
q := req.URL.Query()
q.Set("page_size", strconv.Itoa(pageSize))
q.Set("page_number", strconv.Itoa(page))
q.Set("sort", "last_updated_at,desc")
req.URL.RawQuery = q.Encode()
res, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to list sessions: %s", res.Status)
}
var response struct {
Sessions []session `json:"sessions"`
}
if err := json.NewDecoder(res.Body).Decode(&response); err != nil {
return nil, fmt.Errorf("failed to decode sessions response: %w", err)
}
// Process only the newly fetched page worth of sessions.
pageSessions := response.Sessions
// De-duplicate sessions by resource ID.
// Because the API returns newest first, once we've seen
// a resource ID we can ignore any older sessions for it.
for _, s := range pageSessions {
if _, exists := seenResources[s.ResourceID]; exists {
continue
}
// A zero resource ID is a temporary situation before a PR/resource
// is associated with the session. We should not mark such case as seen.
if s.ResourceID != 0 {
seenResources[s.ResourceID] = struct{}{}
}
latestSessions = append(latestSessions, s)
if len(latestSessions) >= limit {
break
}
}
if len(response.Sessions) < pageSize || len(latestSessions) >= limit {
break
}
}
// Drop any above the limit
if len(latestSessions) > limit {
latestSessions = latestSessions[:limit]
}
result, err := c.hydrateSessionPullRequestsAndUsers(latestSessions)
if err != nil {
return nil, fmt.Errorf("failed to fetch session resources: %w", err)
}
return result, nil
}
// GetSession retrieves a specific agent session by ID.
func (c *CAPIClient) GetSession(ctx context.Context, id string) (*Session, error) {
if id == "" {
return nil, fmt.Errorf("missing session ID")
}
url := fmt.Sprintf("%s/agents/sessions/%s", baseCAPIURL, url.PathEscape(id))
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody)
if err != nil {
return nil, err
}
res, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
if res.StatusCode == http.StatusNotFound {
return nil, ErrSessionNotFound
}
return nil, fmt.Errorf("failed to get session: %s", res.Status)
}
var rawSession session
if err := json.NewDecoder(res.Body).Decode(&rawSession); err != nil {
return nil, fmt.Errorf("failed to decode session response: %w", err)
}
sessions, err := c.hydrateSessionPullRequestsAndUsers([]session{rawSession})
if err != nil {
return nil, fmt.Errorf("failed to fetch session resources: %w", err)
}
return sessions[0], nil
}
// GetSessionLogs retrieves logs of an agent session identified by ID.
func (c *CAPIClient) GetSessionLogs(ctx context.Context, id string) ([]byte, error) {
if id == "" {
return nil, fmt.Errorf("missing session ID")
}
url := fmt.Sprintf("%s/agents/sessions/%s/logs", baseCAPIURL, url.PathEscape(id))
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody)
if err != nil {
return nil, err
}
res, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
if res.StatusCode == http.StatusNotFound {
return nil, ErrSessionNotFound
}
return nil, fmt.Errorf("failed to get session: %s", res.Status)
}
return io.ReadAll(res.Body)
}
// ListSessionsByResourceID retrieves sessions associated with the given resource type and ID.
func (c *CAPIClient) ListSessionsByResourceID(ctx context.Context, resourceType string, resourceID int64, limit int) ([]*Session, error) {
if resourceType == "" || resourceID == 0 {
return nil, fmt.Errorf("missing resource type/ID")
}
if limit == 0 {
return nil, nil
}
url := fmt.Sprintf("%s/agents/resource/%s/%d", baseCAPIURL, url.PathEscape(resourceType), resourceID)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody)
if err != nil {
return nil, err
}
res, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to list sessions: %s", res.Status)
}
var response resource
if err := json.NewDecoder(res.Body).Decode(&response); err != nil {
return nil, fmt.Errorf("failed to decode sessions response: %w", err)
}
sessions := make([]session, 0, len(response.Sessions))
for _, s := range response.Sessions {
session := session{
ID: s.SessionID,
Name: s.Name,
UserID: int64(response.UserID),
ResourceType: response.ResourceType,
ResourceID: response.ResourceID,
ResourceGlobalID: response.ResourceGlobalID,
State: s.SessionState,
}
if s.SessionLastUpdatedAt != 0 {
session.LastUpdatedAt = time.Unix(s.SessionLastUpdatedAt, 0).UTC()
}
sessions = append(sessions, session)
}
result, err := c.hydrateSessionPullRequestsAndUsers(sessions)
if err != nil {
return nil, fmt.Errorf("failed to fetch session resources: %w", err)
}
return result, nil
}
// hydrateSessionPullRequestsAndUsers hydrates pull request and user information in sessions
func (c *CAPIClient) hydrateSessionPullRequestsAndUsers(sessions []session) ([]*Session, error) {
if len(sessions) == 0 {
return nil, nil
}
prNodeIds := make([]string, 0, len(sessions))
userNodeIds := make([]string, 0, len(sessions))
for _, session := range sessions {
if session.ResourceType == "pull" {
prNodeID := session.ResourceGlobalID
// TODO: probably this can be dropped since the API should always
// keep returning the resource global ID.
if session.ResourceGlobalID == "" {
prNodeID = generatePullRequestNodeID(int64(session.RepoID), session.ResourceID)
}
if !slices.Contains(prNodeIds, prNodeID) {
prNodeIds = append(prNodeIds, prNodeID)
}
}
userNodeId := generateUserNodeID(session.UserID)
if !slices.Contains(userNodeIds, userNodeId) {
userNodeIds = append(userNodeIds, userNodeId)
}
}
apiClient := api.NewClientFromHTTP(c.httpClient)
var resp struct {
Nodes []struct {
TypeName string `graphql:"__typename"`
PullRequest sessionPullRequest `graphql:"... on PullRequest"`
User api.GitHubUser `graphql:"... on User"`
} `graphql:"nodes(ids: $ids)"`
}
ids := make([]string, 0, len(prNodeIds)+len(userNodeIds))
ids = append(ids, prNodeIds...)
ids = append(ids, userNodeIds...)
// TODO handle pagination
err := apiClient.Query(c.host, "FetchPRsAndUsersForAgentTaskSessions", &resp, map[string]any{
"ids": ids,
})
if err != nil {
return nil, err
}
prMap := make(map[string]*api.PullRequest, len(prNodeIds))
userMap := make(map[int64]*api.GitHubUser, len(userNodeIds))
for _, node := range resp.Nodes {
switch node.TypeName {
case "User":
userMap[node.User.DatabaseID] = &node.User
case "PullRequest":
prMap[node.PullRequest.FullDatabaseID] = &api.PullRequest{
ID: node.PullRequest.ID,
FullDatabaseID: node.PullRequest.FullDatabaseID,
Number: node.PullRequest.Number,
Title: node.PullRequest.Title,
State: node.PullRequest.State,
IsDraft: node.PullRequest.IsDraft,
URL: node.PullRequest.URL,
Body: node.PullRequest.Body,
CreatedAt: node.PullRequest.CreatedAt,
UpdatedAt: node.PullRequest.UpdatedAt,
ClosedAt: node.PullRequest.ClosedAt,
MergedAt: node.PullRequest.MergedAt,
Repository: node.PullRequest.Repository,
}
}
}
newSessions := make([]*Session, 0, len(sessions))
for _, s := range sessions {
newSession := fromAPISession(s)
newSession.PullRequest = prMap[strconv.FormatInt(s.ResourceID, 10)]
newSession.User = userMap[s.UserID]
newSessions = append(newSessions, newSession)
}
return newSessions, nil
}
// GetPullRequestDatabaseID retrieves the database ID and URL of a pull request given its number in a repository.
func (c *CAPIClient) GetPullRequestDatabaseID(ctx context.Context, hostname string, owner string, repo string, number int) (int64, string, error) {
// TODO: better int handling so we don't need to do bounds checks
// to both ensure a panic is impossible and that we do not trigger
// CodeQL alerts.
if number <= 0 || number > math.MaxInt32 {
return 0, "", fmt.Errorf("pull request number %d out of bounds", number)
}
var resp struct {
Repository struct {
PullRequest struct {
FullDatabaseID string `graphql:"fullDatabaseId"`
URL string `graphql:"url"`
} `graphql:"pullRequest(number: $number)"`
} `graphql:"repository(owner: $owner, name: $repo)"`
}
variables := map[string]interface{}{
"owner": githubv4.String(owner),
"repo": githubv4.String(repo),
"number": githubv4.Int(number),
}
apiClient := api.NewClientFromHTTP(c.httpClient)
if err := apiClient.Query(hostname, "GetPullRequestFullDatabaseID", &resp, variables); err != nil {
return 0, "", err
}
databaseID, err := strconv.ParseInt(resp.Repository.PullRequest.FullDatabaseID, 10, 64)
if err != nil {
return 0, "", err
}
return databaseID, resp.Repository.PullRequest.URL, nil
}
// generatePullRequestNodeID converts an int64 databaseID and repoID to a GraphQL Node ID format
// with the "PR_" prefix for pull requests
func generatePullRequestNodeID(repoID, pullRequestID int64) string {
buf := bytes.Buffer{}
parts := []int64{0, repoID, pullRequestID}
encoder := msgpack.NewEncoder(&buf)
encoder.UseCompactInts(true)
if err := encoder.Encode(parts); err != nil {
panic(err)
}
encoded := base64.RawURLEncoding.EncodeToString(buf.Bytes())
return "PR_" + encoded
}
func generateUserNodeID(userID int64) string {
buf := bytes.Buffer{}
parts := []int64{0, userID}
encoder := msgpack.NewEncoder(&buf)
encoder.UseCompactInts(true)
if err := encoder.Encode(parts); err != nil {
panic(err)
}
encoded := base64.RawURLEncoding.EncodeToString(buf.Bytes())
return "U_" + encoded
}
func fromAPISession(s session) *Session {
result := Session{
ID: s.ID,
Name: s.Name,
UserID: s.UserID,
AgentID: s.AgentID,
Logs: s.Logs,
State: s.State,
OwnerID: s.OwnerID,
RepoID: s.RepoID,
ResourceType: s.ResourceType,
ResourceID: s.ResourceID,
LastUpdatedAt: s.LastUpdatedAt,
CreatedAt: s.CreatedAt,
CompletedAt: s.CompletedAt,
EventURL: s.EventURL,
EventType: s.EventType,
PremiumRequests: s.PremiumRequests,
WorkflowRunID: s.WorkflowRunID,
}
if s.Error != nil {
result.Error = &SessionError{
Code: s.Error.Code,
Message: s.Error.Message,
}
}
return &result
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/agent-task/list/list_test.go | pkg/cmd/agent-task/list/list_test.go | package list
import (
"bytes"
"context"
"io"
"testing"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/browser"
"github.com/cli/cli/v2/pkg/cmd/agent-task/capi"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewCmdList(t *testing.T) {
tests := []struct {
name string
args string
wantOpts ListOptions
wantErr string
}{
{
name: "no arguments",
wantOpts: ListOptions{
Limit: defaultLimit,
},
},
{
name: "custom limit",
args: "--limit 15",
wantOpts: ListOptions{
Limit: 15,
},
},
{
name: "invalid limit",
args: "--limit 0",
wantErr: "invalid limit: 0",
},
{
name: "negative limit",
args: "--limit -5",
wantErr: "invalid limit: -5",
},
{
name: "web flag",
args: "--web",
wantOpts: ListOptions{
Limit: defaultLimit,
Web: true,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
f := &cmdutil.Factory{
IOStreams: ios,
}
var gotOpts *ListOptions
cmd := NewCmdList(f, func(opts *ListOptions) error { gotOpts = opts; return nil })
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.Error(t, err)
assert.Contains(t, err.Error(), tt.wantErr)
return
}
require.NoError(t, err)
assert.Equal(t, tt.wantOpts.Limit, gotOpts.Limit)
assert.Equal(t, tt.wantOpts.Web, gotOpts.Web)
})
}
}
func Test_listRun(t *testing.T) {
sampleDate := time.Now().Add(-6 * time.Hour) // 6h ago
sampleDateString := sampleDate.Format(time.RFC3339)
tests := []struct {
name string
tty bool
capiStubs func(*testing.T, *capi.CapiClientMock)
limit int
web bool
wantOut string
wantErr error
wantStderr string
wantBrowserURL string
}{
{
name: "viewer-scoped no sessions",
tty: true,
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.ListLatestSessionsForViewerFunc = func(ctx context.Context, limit int) ([]*capi.Session, error) {
return nil, nil
}
},
wantErr: cmdutil.NewNoResultsError("no agent tasks found"),
},
{
name: "viewer-scoped respects --limit",
tty: true,
limit: 999,
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.ListLatestSessionsForViewerFunc = func(ctx context.Context, limit int) ([]*capi.Session, error) {
assert.Equal(t, 999, limit)
return nil, nil
}
},
wantErr: cmdutil.NewNoResultsError("no agent tasks found"), // not important
},
{
name: "viewer-scoped single session (tty)",
tty: true,
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.ListLatestSessionsForViewerFunc = func(ctx context.Context, limit int) ([]*capi.Session, error) {
return []*capi.Session{
{
ID: "id1",
Name: "s1",
State: "completed",
CreatedAt: sampleDate,
ResourceType: "pull",
PullRequest: &api.PullRequest{
Number: 101,
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
},
}, nil
}
},
wantOut: heredoc.Doc(`
Showing 1 session
SESSION NAME PULL REQUEST REPO SESSION STATE CREATED
s1 #101 OWNER/REPO Ready for review about 6 hours ago
`),
},
{
name: "viewer-scoped single session (nontty)",
tty: false,
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.ListLatestSessionsForViewerFunc = func(ctx context.Context, limit int) ([]*capi.Session, error) {
return []*capi.Session{
{
ID: "id1",
Name: "s1",
State: "completed",
ResourceType: "pull",
CreatedAt: sampleDate,
PullRequest: &api.PullRequest{
Number: 101,
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
},
}, nil
}
},
wantOut: "s1\t#101\tOWNER/REPO\tReady for review\t" + sampleDateString + "\n", // header omitted for non-tty
},
{
name: "viewer-scoped many sessions (tty)",
tty: true,
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.ListLatestSessionsForViewerFunc = func(ctx context.Context, limit int) ([]*capi.Session, error) {
return []*capi.Session{
{
ID: "id1",
Name: "s1",
State: "completed",
CreatedAt: sampleDate,
ResourceType: "pull",
PullRequest: &api.PullRequest{
Number: 101,
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
},
{
ID: "id2",
Name: "s2",
State: "failed",
CreatedAt: sampleDate,
ResourceType: "pull",
PullRequest: &api.PullRequest{
Number: 102,
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
},
{
ID: "id3",
Name: "s3",
State: "in_progress",
CreatedAt: sampleDate,
ResourceType: "pull",
PullRequest: &api.PullRequest{
Number: 103,
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
},
{
ID: "id4",
Name: "s4",
State: "queued",
CreatedAt: sampleDate,
ResourceType: "pull",
PullRequest: &api.PullRequest{
Number: 104,
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
},
{
ID: "id5",
Name: "s5",
State: "cancelled",
CreatedAt: sampleDate,
ResourceType: "pull",
PullRequest: &api.PullRequest{
Number: 105,
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
},
{
ID: "id6",
Name: "s6",
State: "mystery",
CreatedAt: sampleDate,
ResourceType: "pull",
PullRequest: &api.PullRequest{
Number: 106,
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
},
}, nil
}
},
wantOut: heredoc.Doc(`
Showing 6 sessions
SESSION NAME PULL REQUEST REPO SESSION STATE CREATED
s1 #101 OWNER/REPO Ready for review about 6 hours ago
s2 #102 OWNER/REPO Failed about 6 hours ago
s3 #103 OWNER/REPO In progress about 6 hours ago
s4 #104 OWNER/REPO Queued about 6 hours ago
s5 #105 OWNER/REPO Cancelled about 6 hours ago
s6 #106 OWNER/REPO mystery about 6 hours ago
`),
},
{
name: "web mode",
tty: true,
web: true,
wantOut: "",
wantStderr: "Opening https://github.com/copilot/agents in your browser.\n",
wantBrowserURL: "https://github.com/copilot/agents",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
capiClientMock := &capi.CapiClientMock{}
if tt.capiStubs != nil {
tt.capiStubs(t, capiClientMock)
}
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdoutTTY(tt.tty)
var br *browser.Stub
if tt.web {
br = &browser.Stub{}
}
opts := &ListOptions{
IO: ios,
Limit: tt.limit,
Web: tt.web,
Browser: br,
CapiClient: func() (capi.CapiClient, error) {
if tt.web {
require.FailNow(t, "CapiClient was called with --web")
}
return capiClientMock, nil
},
}
err := listRun(opts)
if tt.wantErr != nil {
assert.Error(t, err)
require.EqualError(t, err, tt.wantErr.Error())
} else {
require.NoError(t, err)
}
got := stdout.String()
require.Equal(t, tt.wantOut, got)
require.Equal(t, tt.wantStderr, stderr.String())
if tt.web {
br.Verify(t, tt.wantBrowserURL)
}
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/agent-task/list/list.go | pkg/cmd/agent-task/list/list.go | package list
import (
"context"
"fmt"
"time"
"github.com/cli/cli/v2/internal/browser"
"github.com/cli/cli/v2/internal/tableprinter"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/cmd/agent-task/capi"
"github.com/cli/cli/v2/pkg/cmd/agent-task/shared"
prShared "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 defaultLimit = 30
// ListOptions are the options for the list command
type ListOptions struct {
IO *iostreams.IOStreams
Limit int
CapiClient func() (capi.CapiClient, error)
Web bool
Browser browser.Browser
}
// NewCmdList creates the list command
func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Command {
opts := &ListOptions{
IO: f.IOStreams,
CapiClient: shared.CapiClientFunc(f),
Limit: defaultLimit,
Browser: f.Browser,
}
cmd := &cobra.Command{
Use: "list",
Short: "List agent tasks (preview)",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
if opts.Limit < 1 {
return cmdutil.FlagErrorf("invalid limit: %v", opts.Limit)
}
if runF != nil {
return runF(opts)
}
return listRun(opts)
},
}
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", defaultLimit, "Maximum number of agent tasks to fetch")
cmd.Flags().BoolVarP(&opts.Web, "web", "w", false, "Open agent tasks in the browser")
return cmd
}
func listRun(opts *ListOptions) error {
if opts.Web {
webURL := capi.AgentsHomeURL
if opts.IO.IsStdoutTTY() {
fmt.Fprintf(opts.IO.ErrOut, "Opening %s in your browser.\n", text.DisplayURL(webURL))
}
return opts.Browser.Browse(webURL)
}
if opts.Limit <= 0 {
opts.Limit = defaultLimit
}
capiClient, err := opts.CapiClient()
if err != nil {
return err
}
opts.IO.StartProgressIndicatorWithLabel("Fetching agent tasks...")
defer opts.IO.StopProgressIndicator()
var sessions []*capi.Session
ctx := context.Background()
sessions, err = capiClient.ListLatestSessionsForViewer(ctx, opts.Limit)
if err != nil {
return err
}
opts.IO.StopProgressIndicator()
if len(sessions) == 0 {
return cmdutil.NewNoResultsError("no agent tasks found")
}
if err := opts.IO.StartPager(); err == nil {
defer opts.IO.StopPager()
} else {
fmt.Fprintf(opts.IO.ErrOut, "error starting pager: %v\n", err)
}
if opts.IO.IsStdoutTTY() {
count := len(sessions)
header := fmt.Sprintf("Showing %s", text.Pluralize(count, "session"))
fmt.Fprintf(opts.IO.Out, "%s\n\n", header)
}
cs := opts.IO.ColorScheme()
tp := tableprinter.New(opts.IO, tableprinter.WithHeader("Session Name", "Pull Request", "Repo", "Session State", "Created"))
for _, s := range sessions {
if s.ResourceType != "pull" || s.PullRequest == nil || s.PullRequest.Repository == nil {
// Skip these sessions in case they happen, for now.
continue
}
pr := fmt.Sprintf("#%d", s.PullRequest.Number)
repo := s.PullRequest.Repository.NameWithOwner
// Name
tp.AddField(s.Name)
if tp.IsTTY() {
tp.AddField(pr, tableprinter.WithColor(cs.ColorFromString(prShared.ColorForPRState(*s.PullRequest))))
} else {
tp.AddField(pr)
}
// Repo
tp.AddField(repo, tableprinter.WithColor(cs.Muted))
// State
if tp.IsTTY() {
tp.AddField(shared.SessionStateString(s.State), tableprinter.WithColor(shared.ColorFuncForSessionState(*s, cs)))
} else {
tp.AddField(shared.SessionStateString(s.State))
}
// Created
if tp.IsTTY() {
tp.AddTimeField(time.Now(), s.CreatedAt, cs.Muted)
} else {
tp.AddField(s.CreatedAt.Format(time.RFC3339))
}
tp.EndRow()
}
if err := tp.Render(); 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/agent-task/view/view.go | pkg/cmd/agent-task/view/view.go | package view
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/browser"
"github.com/cli/cli/v2/internal/ghinstance"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/prompter"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/cmd/agent-task/capi"
"github.com/cli/cli/v2/pkg/cmd/agent-task/shared"
prShared "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 (
defaultLimit = 40
defaultLogPollInterval = 5 * time.Second
)
type ViewOptions struct {
IO *iostreams.IOStreams
BaseRepo func() (ghrepo.Interface, error)
CapiClient func() (capi.CapiClient, error)
HttpClient func() (*http.Client, error)
Finder prShared.PRFinder
Prompter prompter.Prompter
Browser browser.Browser
LogRenderer func() shared.LogRenderer
Sleep func(d time.Duration)
SelectorArg string
PRNumber int
SessionID string
Web bool
Log bool
Follow bool
}
func defaultLogRenderer() shared.LogRenderer {
return shared.NewLogRenderer()
}
func NewCmdView(f *cmdutil.Factory, runF func(*ViewOptions) error) *cobra.Command {
opts := &ViewOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
CapiClient: shared.CapiClientFunc(f),
Prompter: f.Prompter,
Browser: f.Browser,
LogRenderer: defaultLogRenderer,
Sleep: time.Sleep,
}
cmd := &cobra.Command{
Use: "view [<session-id> | <pr-number> | <pr-url> | <pr-branch>]",
Short: "View an agent task session (preview)",
Long: heredoc.Doc(`
View an agent task session.
`),
Example: heredoc.Doc(`
# View an agent task by session ID
$ gh agent-task view e2fa49d2-f164-4a56-ab99-498090b8fcdf
# View an agent task by pull request number in current repo
$ gh agent-task view 12345
# View an agent task by pull request number
$ gh agent-task view --repo OWNER/REPO 12345
# View an agent task by pull request reference
$ gh agent-task view OWNER/REPO#12345
# View a pull request agents tasks in the browser
$ gh agent-task view 12345 --web
`),
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
// Support -R/--repo override
opts.BaseRepo = f.BaseRepo
if len(args) > 0 {
opts.SelectorArg = args[0]
if shared.IsSessionID(opts.SelectorArg) {
opts.SessionID = opts.SelectorArg
} else if sessionID, err := shared.ParseSessionIDFromURL(opts.SelectorArg); err == nil {
opts.SessionID = sessionID
}
}
if opts.SessionID == "" && !opts.IO.CanPrompt() {
return fmt.Errorf("session ID is required when not running interactively")
}
if opts.Follow && !opts.Log {
return cmdutil.FlagErrorf("--log is required when providing --follow")
}
if opts.Finder == nil {
opts.Finder = prShared.NewFinder(f)
}
if runF != nil {
return runF(opts)
}
return viewRun(opts)
},
}
cmdutil.EnableRepoOverride(cmd, f)
cmd.Flags().BoolVarP(&opts.Web, "web", "w", false, "Open agent task in the browser")
cmd.Flags().BoolVar(&opts.Log, "log", false, "Show agent session logs")
cmd.Flags().BoolVar(&opts.Follow, "follow", false, "Follow agent session logs")
return cmd
}
func viewRun(opts *ViewOptions) error {
capiClient, err := opts.CapiClient()
if err != nil {
return err
}
ctx := context.Background()
cs := opts.IO.ColorScheme()
opts.IO.StartProgressIndicatorWithLabel("Fetching agent session...")
defer opts.IO.StopProgressIndicator()
var session *capi.Session
if opts.SessionID != "" {
sess, err := capiClient.GetSession(ctx, opts.SessionID)
if err != nil {
if errors.Is(err, capi.ErrSessionNotFound) {
fmt.Fprintln(opts.IO.ErrOut, "session not found")
return cmdutil.SilentError
}
return err
}
opts.IO.StopProgressIndicator()
if opts.Web {
var webURL string
if sess.PullRequest != nil {
webURL = fmt.Sprintf("%s/agent-sessions/%s", sess.PullRequest.URL, url.PathEscape(sess.ID))
} else {
// Currently the web Copilot Agents home GUI does not support focusing
// on a given session, so we should just navigate to the home page.
webURL = capi.AgentsHomeURL
}
if opts.IO.IsStdoutTTY() {
fmt.Fprintf(opts.IO.ErrOut, "Opening %s in your browser.\n", text.DisplayURL(webURL))
}
return opts.Browser.Browse(webURL)
}
session = sess
} else {
var prID int64
var prURL string
if opts.SelectorArg != "" {
// Finder does not support the PR/issue reference format (e.g. owner/repo#123)
// so we need to check if the selector arg is a reference and fetch the PR
// directly.
if repo, num, err := prShared.ParseFullReference(opts.SelectorArg); err == nil {
// Since the selector was a reference (i.e. without hostname data), we need to
// check the base repo to get the hostname.
baseRepo, err := opts.BaseRepo()
if err != nil {
return err
}
hostname := baseRepo.RepoHost()
if hostname != ghinstance.Default() {
return fmt.Errorf("agent tasks are not supported on this host: %s", hostname)
}
prID, prURL, err = capiClient.GetPullRequestDatabaseID(ctx, hostname, repo.RepoOwner(), repo.RepoName(), num)
if err != nil {
return fmt.Errorf("failed to fetch pull request: %w", err)
}
}
}
if prID == 0 {
findOptions := prShared.FindOptions{
Selector: opts.SelectorArg,
Fields: []string{"id", "url", "fullDatabaseId"},
DisableProgress: true,
}
pr, repo, err := opts.Finder.Find(findOptions)
if err != nil {
return err
}
if repo.RepoHost() != ghinstance.Default() {
return fmt.Errorf("agent tasks are not supported on this host: %s", repo.RepoHost())
}
databaseID, err := strconv.ParseInt(pr.FullDatabaseID, 10, 64)
if err != nil {
return fmt.Errorf("failed to parse pull request: %w", err)
}
prID = databaseID
prURL = pr.URL
}
sessions, err := capiClient.ListSessionsByResourceID(ctx, "pull", prID, defaultLimit)
if err != nil {
return fmt.Errorf("failed to list sessions for pull request: %w", err)
}
if len(sessions) == 0 {
fmt.Fprintln(opts.IO.ErrOut, "no session found for pull request")
return cmdutil.SilentError
}
opts.IO.StopProgressIndicator()
if opts.Web {
// Note that, we needed to make sure the PR exists and it has at least one session
// associated with it, other wise the `/agent-sessions` page would display the 404
// error.
// We don't need to navigate to a specific session; if there's only one session
// then the GUI will automatically show it, otherwise the user can select from the
// list. This is to avoid unnecessary prompting.
webURL := prURL + "/agent-sessions"
if opts.IO.IsStdoutTTY() {
fmt.Fprintf(opts.IO.ErrOut, "Opening %s in your browser.\n", text.DisplayURL(webURL))
}
return opts.Browser.Browse(webURL)
}
selectedSession := sessions[0]
if len(sessions) > 1 {
now := time.Now()
options := make([]string, 0, len(sessions))
for _, session := range sessions {
options = append(options, fmt.Sprintf(
"%s %s • updated %s",
shared.SessionSymbol(cs, session.State),
session.Name,
text.FuzzyAgo(now, session.LastUpdatedAt),
))
}
selected, err := opts.Prompter.Select("Select a session", "", options)
if err != nil {
return err
}
selectedSession = sessions[selected]
}
opts.IO.StartProgressIndicatorWithLabel("Fetching agent session...")
defer opts.IO.StopProgressIndicator()
// Sessions returned by ListSessionsByResourceID do not have all fields populated.
// So, we need to fetch the individual session to get all the details.
session, err = capiClient.GetSession(ctx, selectedSession.ID)
if err != nil {
return err
}
opts.IO.StopProgressIndicator()
}
if opts.Log {
return printLogs(opts, capiClient, session.ID)
}
printSession(opts, session)
return nil
}
func printSession(opts *ViewOptions, session *capi.Session) {
cs := opts.IO.ColorScheme()
fmt.Fprintf(opts.IO.Out, "%s • %s\n",
shared.ColorFuncForSessionState(*session, cs)(shared.SessionStateString(session.State)),
cs.Bold(session.Name),
)
if session.User != nil {
fmt.Fprintf(opts.IO.Out, "Started on behalf of %s %s\n", session.User.Login, text.FuzzyAgo(time.Now(), session.CreatedAt))
} else {
// Should never happen, but we need to cover the path
fmt.Fprintf(opts.IO.Out, "Started %s\n", text.FuzzyAgo(time.Now(), session.CreatedAt))
}
usedPremiumRequests := strings.TrimSuffix(fmt.Sprintf("%.1f", session.PremiumRequests), ".0")
usedPremiumRequestsNote := fmt.Sprintf("Used %s premium request(s)", usedPremiumRequests)
var durationNote string
if session.CompletedAt.After(session.CreatedAt) {
durationNote = fmt.Sprintf(" • Duration %s", session.CompletedAt.Sub(session.CreatedAt).Round(time.Second).String())
}
fmt.Fprintf(opts.IO.Out, "%s%s\n", cs.Muted(usedPremiumRequestsNote), cs.Muted(durationNote))
// Note that when the session is just created, a PR is not yet available for it.
if session.PullRequest != nil {
fmt.Fprintf(opts.IO.Out, "\n%s%s • %s\n",
session.PullRequest.Repository.NameWithOwner,
cs.ColorFromString(prShared.ColorForPRState(*session.PullRequest))(fmt.Sprintf("#%d", session.PullRequest.Number)),
cs.Bold(session.PullRequest.Title),
)
}
if session.Error != nil {
var workflowRunURL string
if session.WorkflowRunID != 0 && session.PullRequest != nil {
if u, err := url.Parse(session.PullRequest.URL); err == nil {
workflowRunURL = fmt.Sprintf("%s://%s/%s/actions/runs/%d", u.Scheme, u.Host, session.PullRequest.Repository.NameWithOwner, session.WorkflowRunID)
}
}
message := session.Error.Message
if message == "" {
message = "An error occurred"
}
fmt.Fprintf(opts.IO.Out, "\n%s %s\n", cs.FailureIconWithColor(cs.Red), message)
if workflowRunURL != "" {
// We don't need to prefix the link with any text (e.g. "checkout the logs here")
// because the error message already contains all the information.
fmt.Fprintf(opts.IO.Out, "%s\n", workflowRunURL)
}
}
if !opts.Log {
fmt.Fprint(opts.IO.Out, cs.Mutedf("\nFor detailed session logs, try:\ngh agent-task view '%s' --log\n", session.ID))
} else if !opts.Follow {
fmt.Fprint(opts.IO.Out, cs.Mutedf("\nTo follow session logs, try:\ngh agent-task view '%s' --log --follow\n", session.ID))
}
if session.PullRequest != nil {
fmt.Fprintln(opts.IO.Out, cs.Muted("\nView this session on GitHub:"))
fmt.Fprintln(opts.IO.Out, cs.Muted(fmt.Sprintf("%s/agent-sessions/%s", session.PullRequest.URL, url.PathEscape(session.ID))))
}
}
func printLogs(opts *ViewOptions, capiClient capi.CapiClient, sessionID string) error {
ctx := context.Background()
renderer := opts.LogRenderer()
if err := opts.IO.StartPager(); err == nil {
defer opts.IO.StopPager()
} else {
fmt.Fprintf(opts.IO.ErrOut, "error starting pager: %v\n", err)
}
if opts.Follow {
var called bool
fetcher := func() ([]byte, error) {
if called {
opts.Sleep(defaultLogPollInterval)
}
called = true
raw, err := capiClient.GetSessionLogs(ctx, sessionID)
if err != nil {
return nil, err
}
return raw, nil
}
return renderer.Follow(fetcher, opts.IO.Out, opts.IO)
}
raw, err := capiClient.GetSessionLogs(ctx, sessionID)
if err != nil {
return fmt.Errorf("failed to fetch session logs: %w", err)
}
_, err = renderer.Render(raw, opts.IO.Out, opts.IO)
return err
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/agent-task/view/view_test.go | pkg/cmd/agent-task/view/view_test.go | package view
import (
"bytes"
"context"
"errors"
"io"
"testing"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/browser"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/prompter"
"github.com/cli/cli/v2/pkg/cmd/agent-task/capi"
"github.com/cli/cli/v2/pkg/cmd/agent-task/shared"
prShared "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/google/shlex"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewCmdList(t *testing.T) {
tests := []struct {
name string
tty bool
args string
wantOpts ViewOptions
wantBaseRepo ghrepo.Interface
wantErr string
}{
{
name: "no arg tty",
tty: true,
args: "",
wantOpts: ViewOptions{},
},
{
name: "session ID arg tty",
tty: true,
args: "00000000-0000-0000-0000-000000000000",
wantOpts: ViewOptions{
SelectorArg: "00000000-0000-0000-0000-000000000000",
SessionID: "00000000-0000-0000-0000-000000000000",
},
},
{
name: "PR agent-session URL arg tty",
tty: true,
args: "https://github.com/OWNER/REPO/pull/101/agent-sessions/00000000-0000-0000-0000-000000000000",
wantOpts: ViewOptions{
SelectorArg: "https://github.com/OWNER/REPO/pull/101/agent-sessions/00000000-0000-0000-0000-000000000000",
SessionID: "00000000-0000-0000-0000-000000000000",
},
},
{
name: "non-session ID arg tty",
tty: true,
args: "some-arg",
wantOpts: ViewOptions{
SelectorArg: "some-arg",
},
},
{
name: "session ID required if non-tty",
tty: false,
args: "some-arg",
wantErr: "session ID is required when not running interactively",
},
{
name: "repo override",
tty: true,
args: "some-arg -R OWNER/REPO",
wantBaseRepo: ghrepo.New("OWNER", "REPO"),
wantOpts: ViewOptions{
SelectorArg: "some-arg",
},
},
{
name: "with --log",
tty: true,
args: "some-arg --log",
wantOpts: ViewOptions{
SelectorArg: "some-arg",
Log: true,
},
},
{
name: "with --log and --follow",
tty: true,
args: "some-arg --log --follow",
wantOpts: ViewOptions{
SelectorArg: "some-arg",
Log: true,
Follow: true,
},
},
{
name: "--follow requires --log",
tty: true,
args: "some-arg --follow",
wantErr: "--log is required when providing --follow",
},
{
name: "web mode",
tty: true,
args: "some-arg -w",
wantOpts: ViewOptions{
SelectorArg: "some-arg",
Web: true,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
ios.SetStdinTTY(tt.tty)
ios.SetStdoutTTY(tt.tty)
ios.SetStderrTTY(tt.tty)
f := &cmdutil.Factory{
IOStreams: ios,
}
var gotOpts *ViewOptions
cmd := NewCmdView(f, func(opts *ViewOptions) error { gotOpts = opts; return nil })
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.Error(t, err)
assert.Contains(t, err.Error(), tt.wantErr)
return
}
require.NoError(t, err)
assert.Equal(t, tt.wantOpts.SelectorArg, gotOpts.SelectorArg)
assert.Equal(t, tt.wantOpts.SessionID, gotOpts.SessionID)
if tt.wantBaseRepo != nil {
baseRepo, err := gotOpts.BaseRepo()
require.NoError(t, err)
assert.True(t, ghrepo.IsSame(tt.wantBaseRepo, baseRepo))
}
})
}
}
func Test_viewRun(t *testing.T) {
sampleDate := time.Now().Add(-6 * time.Hour) // 6h ago
sampleCompletedAt := sampleDate.Add(5 * time.Minute)
tests := []struct {
name string
tty bool
opts ViewOptions
promptStubs func(*testing.T, *prompter.MockPrompter)
capiStubs func(*testing.T, *capi.CapiClientMock)
logRendererStubs func(*testing.T, *shared.LogRendererMock)
wantOut string
wantErr error
wantStderr string
wantBrowserURL string
}{
{
name: "with session id, not found (tty)",
tty: true,
opts: ViewOptions{
SelectorArg: "some-session-id",
SessionID: "some-session-id",
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.GetSessionFunc = func(_ context.Context, _ string) (*capi.Session, error) {
return nil, capi.ErrSessionNotFound
}
},
wantStderr: "session not found\n",
wantErr: cmdutil.SilentError,
},
{
name: "with session id, api error (tty)",
tty: true,
opts: ViewOptions{
SelectorArg: "some-session-id",
SessionID: "some-session-id",
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.GetSessionFunc = func(_ context.Context, _ string) (*capi.Session, error) {
return nil, errors.New("some error")
}
},
wantErr: errors.New("some error"),
},
{
name: "with session id, success, with pr and user data (tty)",
tty: true,
opts: ViewOptions{
SelectorArg: "some-session-id",
SessionID: "some-session-id",
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.GetSessionFunc = func(_ context.Context, id string) (*capi.Session, error) {
assert.Equal(t, "some-session-id", id)
return &capi.Session{
ID: "some-session-id",
State: "completed",
Name: "session one",
CreatedAt: sampleDate,
CompletedAt: sampleCompletedAt,
PremiumRequests: 1.5,
PullRequest: &api.PullRequest{
Title: "fix something",
Number: 101,
URL: "https://github.com/OWNER/REPO/pull/101",
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
User: &api.GitHubUser{
Login: "octocat",
},
}, nil
}
},
wantOut: heredoc.Doc(`
Ready for review • session one
Started on behalf of octocat about 6 hours ago
Used 1.5 premium request(s) • Duration 5m0s
OWNER/REPO#101 • fix something
For detailed session logs, try:
gh agent-task view 'some-session-id' --log
View this session on GitHub:
https://github.com/OWNER/REPO/pull/101/agent-sessions/some-session-id
`),
},
{
// The user data should always be there, but we need to cover the code path.
name: "with session id, success, without user data (tty)",
tty: true,
opts: ViewOptions{
SelectorArg: "some-session-id",
SessionID: "some-session-id",
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.GetSessionFunc = func(_ context.Context, id string) (*capi.Session, error) {
assert.Equal(t, "some-session-id", id)
return &capi.Session{
ID: "some-session-id",
State: "completed",
Name: "session one",
CreatedAt: sampleDate,
CompletedAt: sampleCompletedAt,
PremiumRequests: 1.5,
PullRequest: &api.PullRequest{
Title: "fix something",
Number: 101,
URL: "https://github.com/OWNER/REPO/pull/101",
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
}, nil
}
},
wantOut: heredoc.Doc(`
Ready for review • session one
Started about 6 hours ago
Used 1.5 premium request(s) • Duration 5m0s
OWNER/REPO#101 • fix something
For detailed session logs, try:
gh agent-task view 'some-session-id' --log
View this session on GitHub:
https://github.com/OWNER/REPO/pull/101/agent-sessions/some-session-id
`),
},
{
// This can happen when the session is just created and a PR is not yet available for it.
name: "with session id, success, without pr data (tty)",
tty: true,
opts: ViewOptions{
SelectorArg: "some-session-id",
SessionID: "some-session-id",
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.GetSessionFunc = func(_ context.Context, id string) (*capi.Session, error) {
assert.Equal(t, "some-session-id", id)
return &capi.Session{
ID: "some-session-id",
State: "completed",
Name: "session one",
CreatedAt: sampleDate,
CompletedAt: sampleCompletedAt,
PremiumRequests: 1.5,
User: &api.GitHubUser{
Login: "octocat",
},
}, nil
}
},
wantOut: heredoc.Doc(`
Ready for review • session one
Started on behalf of octocat about 6 hours ago
Used 1.5 premium request(s) • Duration 5m0s
For detailed session logs, try:
gh agent-task view 'some-session-id' --log
`),
},
{
// The user data should always be there, but we need to cover the code path.
name: "with session id, success, without pr nor user data (tty)",
tty: true,
opts: ViewOptions{
SelectorArg: "some-session-id",
SessionID: "some-session-id",
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.GetSessionFunc = func(_ context.Context, id string) (*capi.Session, error) {
assert.Equal(t, "some-session-id", id)
return &capi.Session{
ID: "some-session-id",
State: "completed",
Name: "session one",
CreatedAt: sampleDate,
CompletedAt: sampleCompletedAt,
PremiumRequests: 1.5,
}, nil
}
},
wantOut: heredoc.Doc(`
Ready for review • session one
Started about 6 hours ago
Used 1.5 premium request(s) • Duration 5m0s
For detailed session logs, try:
gh agent-task view 'some-session-id' --log
`),
},
{
name: "with session id, success, with zero premium requests (tty)",
tty: true,
opts: ViewOptions{
SelectorArg: "some-session-id",
SessionID: "some-session-id",
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.GetSessionFunc = func(_ context.Context, id string) (*capi.Session, error) {
assert.Equal(t, "some-session-id", id)
return &capi.Session{
ID: "some-session-id",
State: "completed",
Name: "session one",
CreatedAt: sampleDate,
CompletedAt: sampleCompletedAt,
PremiumRequests: 0,
PullRequest: &api.PullRequest{
Title: "fix something",
Number: 101,
URL: "https://github.com/OWNER/REPO/pull/101",
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
User: &api.GitHubUser{
Login: "octocat",
},
}, nil
}
},
wantOut: heredoc.Doc(`
Ready for review • session one
Started on behalf of octocat about 6 hours ago
Used 0 premium request(s) • Duration 5m0s
OWNER/REPO#101 • fix something
For detailed session logs, try:
gh agent-task view 'some-session-id' --log
View this session on GitHub:
https://github.com/OWNER/REPO/pull/101/agent-sessions/some-session-id
`),
},
{
name: "with session id, success, duration not available (tty)",
tty: true,
opts: ViewOptions{
SelectorArg: "some-session-id",
SessionID: "some-session-id",
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.GetSessionFunc = func(_ context.Context, id string) (*capi.Session, error) {
assert.Equal(t, "some-session-id", id)
return &capi.Session{
ID: "some-session-id",
State: "in_progress",
Name: "session one",
CreatedAt: sampleDate,
PremiumRequests: 1.5,
PullRequest: &api.PullRequest{
Title: "fix something",
Number: 101,
URL: "https://github.com/OWNER/REPO/pull/101",
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
User: &api.GitHubUser{
Login: "octocat",
},
}, nil
}
},
wantOut: heredoc.Doc(`
In progress • session one
Started on behalf of octocat about 6 hours ago
Used 1.5 premium request(s)
OWNER/REPO#101 • fix something
For detailed session logs, try:
gh agent-task view 'some-session-id' --log
View this session on GitHub:
https://github.com/OWNER/REPO/pull/101/agent-sessions/some-session-id
`),
},
{
name: "with session id, success, session has error (tty)",
tty: true,
opts: ViewOptions{
SelectorArg: "some-session-id",
SessionID: "some-session-id",
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.GetSessionFunc = func(_ context.Context, id string) (*capi.Session, error) {
assert.Equal(t, "some-session-id", id)
return &capi.Session{
ID: "some-session-id",
State: "failed",
Name: "session one",
CreatedAt: sampleDate,
PremiumRequests: 1.5,
Error: &capi.SessionError{
Message: "blah blah",
},
PullRequest: &api.PullRequest{
Title: "fix something",
Number: 101,
URL: "https://github.com/OWNER/REPO/pull/101",
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
User: &api.GitHubUser{
Login: "octocat",
},
}, nil
}
},
wantOut: heredoc.Doc(`
Failed • session one
Started on behalf of octocat about 6 hours ago
Used 1.5 premium request(s)
OWNER/REPO#101 • fix something
X blah blah
For detailed session logs, try:
gh agent-task view 'some-session-id' --log
View this session on GitHub:
https://github.com/OWNER/REPO/pull/101/agent-sessions/some-session-id
`),
},
{
name: "with session id, success, session has error with workflow id (tty)",
tty: true,
opts: ViewOptions{
SelectorArg: "some-session-id",
SessionID: "some-session-id",
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.GetSessionFunc = func(_ context.Context, id string) (*capi.Session, error) {
assert.Equal(t, "some-session-id", id)
return &capi.Session{
ID: "some-session-id",
State: "failed",
Name: "session one",
CreatedAt: sampleDate,
PremiumRequests: 1.5,
WorkflowRunID: 9999,
Error: &capi.SessionError{
Message: "blah blah",
},
PullRequest: &api.PullRequest{
Title: "fix something",
Number: 101,
URL: "https://github.com/OWNER/REPO/pull/101",
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
User: &api.GitHubUser{
Login: "octocat",
},
}, nil
}
},
wantOut: heredoc.Doc(`
Failed • session one
Started on behalf of octocat about 6 hours ago
Used 1.5 premium request(s)
OWNER/REPO#101 • fix something
X blah blah
https://github.com/OWNER/REPO/actions/runs/9999
For detailed session logs, try:
gh agent-task view 'some-session-id' --log
View this session on GitHub:
https://github.com/OWNER/REPO/pull/101/agent-sessions/some-session-id
`),
},
{
name: "with session id, not found, web mode (tty)",
tty: true,
opts: ViewOptions{
SelectorArg: "some-session-id",
SessionID: "some-session-id",
Web: true,
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.GetSessionFunc = func(_ context.Context, _ string) (*capi.Session, error) {
return nil, capi.ErrSessionNotFound
}
},
wantStderr: "session not found\n",
wantErr: cmdutil.SilentError,
},
{
name: "with session id, without pr data, web mode (tty)",
tty: true,
opts: ViewOptions{
SelectorArg: "some-session-id",
SessionID: "some-session-id",
Web: true,
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.GetSessionFunc = func(_ context.Context, id string) (*capi.Session, error) {
assert.Equal(t, "some-session-id", id)
return &capi.Session{
ID: "some-session-id",
State: "completed",
Name: "session one",
CreatedAt: sampleDate,
CompletedAt: sampleCompletedAt,
PremiumRequests: 1.5,
// User data is irrelevant in this case
}, nil
}
},
wantBrowserURL: "https://github.com/copilot/agents",
wantStderr: "Opening https://github.com/copilot/agents in your browser.\n",
},
{
name: "with session id, with pr data, web mode (tty)",
tty: true,
opts: ViewOptions{
SelectorArg: "some-session-id",
SessionID: "some-session-id",
Web: true,
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.GetSessionFunc = func(_ context.Context, id string) (*capi.Session, error) {
assert.Equal(t, "some-session-id", id)
return &capi.Session{
ID: "some-session-id",
State: "completed",
Name: "session one",
CreatedAt: sampleDate,
CompletedAt: sampleCompletedAt,
PremiumRequests: 1.5,
PullRequest: &api.PullRequest{
Title: "fix something",
Number: 101,
URL: "https://github.com/OWNER/REPO/pull/101",
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
// User data is irrelevant in this case
}, nil
}
},
wantBrowserURL: "https://github.com/OWNER/REPO/pull/101/agent-sessions/some-session-id",
wantStderr: "Opening https://github.com/OWNER/REPO/pull/101/agent-sessions/some-session-id in your browser.\n",
},
{
name: "with pr number, api error (tty)",
tty: true,
opts: ViewOptions{
SelectorArg: "101",
Finder: prShared.NewMockFinder(
"101",
&api.PullRequest{
FullDatabaseID: "999999",
URL: "https://github.com/OWNER/REPO/pull/101",
},
ghrepo.New("OWNER", "REPO"),
),
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.ListSessionsByResourceIDFunc = func(_ context.Context, _ string, _ int64, _ int) ([]*capi.Session, error) {
return nil, errors.New("some error")
}
},
wantErr: errors.New("failed to list sessions for pull request: some error"),
},
{
name: "with pr reference, unsupported hostname (tty)",
tty: true,
opts: ViewOptions{
SelectorArg: "OWNER/REPO#101",
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.NewWithHost("OWNER", "REPO", "foo.com"), nil
},
},
wantErr: errors.New("agent tasks are not supported on this host: foo.com"),
},
{
name: "with pr reference, api error when fetching pr database ID (tty)",
tty: true,
opts: ViewOptions{
SelectorArg: "OWNER/REPO#101",
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.New("OWNER", "REPO"), nil
},
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.GetPullRequestDatabaseIDFunc = func(_ context.Context, _ string, _ string, _ string, _ int) (int64, string, error) {
return 0, "", errors.New("some error")
}
},
wantErr: errors.New("failed to fetch pull request: some error"),
},
{
name: "with pr reference, api error when fetching session (tty)",
tty: true,
opts: ViewOptions{
SelectorArg: "OWNER/REPO#101",
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.New("OWNER", "REPO"), nil
},
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.GetPullRequestDatabaseIDFunc = func(_ context.Context, _ string, _ string, _ string, _ int) (int64, string, error) {
return 999999, "some-url", nil
}
m.ListSessionsByResourceIDFunc = func(_ context.Context, _ string, _ int64, _ int) ([]*capi.Session, error) {
return nil, errors.New("some error")
}
},
wantErr: errors.New("failed to list sessions for pull request: some error"),
},
{
name: "with pr number, success, single session (tty)",
tty: true,
opts: ViewOptions{
SelectorArg: "101",
Finder: prShared.NewMockFinder(
"101",
&api.PullRequest{
FullDatabaseID: "999999",
URL: "https://github.com/OWNER/REPO/pull/101",
},
ghrepo.New("OWNER", "REPO"),
),
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.ListSessionsByResourceIDFunc = func(_ context.Context, resourceType string, resourceID int64, limit int) ([]*capi.Session, error) {
assert.Equal(t, "pull", resourceType)
assert.Equal(t, int64(999999), resourceID)
assert.Equal(t, defaultLimit, limit)
return []*capi.Session{
{
ID: "some-session-id",
Name: "session one",
State: "completed",
LastUpdatedAt: sampleCompletedAt,
// Rest of the fields are not not meant to be used or relied upon
},
}, nil
}
m.GetSessionFunc = func(_ context.Context, id string) (*capi.Session, error) {
assert.Equal(t, "some-session-id", id)
return &capi.Session{
ID: "some-session-id",
State: "completed",
Name: "session one",
CreatedAt: sampleDate,
CompletedAt: sampleCompletedAt,
PremiumRequests: 1.5,
PullRequest: &api.PullRequest{
Title: "fix something",
Number: 101,
URL: "https://github.com/OWNER/REPO/pull/101",
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
User: &api.GitHubUser{
Login: "octocat",
},
}, nil
}
},
wantOut: heredoc.Doc(`
Ready for review • session one
Started on behalf of octocat about 6 hours ago
Used 1.5 premium request(s) • Duration 5m0s
OWNER/REPO#101 • fix something
For detailed session logs, try:
gh agent-task view 'some-session-id' --log
View this session on GitHub:
https://github.com/OWNER/REPO/pull/101/agent-sessions/some-session-id
`),
},
{
name: "with pr number, success, multiple sessions (tty)",
tty: true,
opts: ViewOptions{
SelectorArg: "101",
Finder: prShared.NewMockFinder(
"101",
&api.PullRequest{
FullDatabaseID: "999999",
URL: "https://github.com/OWNER/REPO/pull/101",
},
ghrepo.New("OWNER", "REPO"),
),
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.ListSessionsByResourceIDFunc = func(_ context.Context, resourceType string, resourceID int64, limit int) ([]*capi.Session, error) {
assert.Equal(t, "pull", resourceType)
assert.Equal(t, int64(999999), resourceID)
assert.Equal(t, defaultLimit, limit)
return []*capi.Session{
{
ID: "some-session-id",
Name: "session one",
State: "completed",
LastUpdatedAt: sampleCompletedAt,
// Rest of the fields are not not meant to be used or relied upon
},
{
ID: "some-other-session-id",
Name: "session two",
State: "completed",
LastUpdatedAt: sampleCompletedAt,
// Rest of the fields are not not meant to be used or relied upon
},
}, nil
}
m.GetSessionFunc = func(_ context.Context, id string) (*capi.Session, error) {
assert.Equal(t, "some-session-id", id)
return &capi.Session{
ID: "some-session-id",
Name: "session one",
State: "completed",
CreatedAt: sampleDate,
LastUpdatedAt: sampleCompletedAt,
CompletedAt: sampleCompletedAt,
PremiumRequests: 1.5,
PullRequest: &api.PullRequest{
Title: "fix something",
Number: 101,
URL: "https://github.com/OWNER/REPO/pull/101",
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
User: &api.GitHubUser{
Login: "octocat",
},
}, nil
}
},
promptStubs: func(t *testing.T, pm *prompter.MockPrompter) {
pm.RegisterSelect(
"Select a session",
[]string{
"✓ session one • updated about 5 hours ago",
"✓ session two • updated about 5 hours ago",
},
func(_, _ string, opts []string) (int, error) {
return prompter.IndexFor(opts, "✓ session one • updated about 5 hours ago")
},
)
},
wantOut: heredoc.Doc(`
Ready for review • session one
Started on behalf of octocat about 6 hours ago
Used 1.5 premium request(s) • Duration 5m0s
OWNER/REPO#101 • fix something
For detailed session logs, try:
gh agent-task view 'some-session-id' --log
View this session on GitHub:
https://github.com/OWNER/REPO/pull/101/agent-sessions/some-session-id
`),
},
{
name: "with pr reference, success, multiple sessions (tty)",
tty: true,
opts: ViewOptions{
SelectorArg: "OWNER/REPO#101",
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.New("OWNER", "REPO"), nil
},
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.GetPullRequestDatabaseIDFunc = func(_ context.Context, hostname string, owner string, repo string, number int) (int64, string, error) {
assert.Equal(t, "github.com", hostname)
assert.Equal(t, "OWNER", owner)
assert.Equal(t, "REPO", repo)
assert.Equal(t, 101, number)
return 999999, "https://github.com/OWNER/REPO/pull/101", nil
}
m.ListSessionsByResourceIDFunc = func(_ context.Context, resourceType string, resourceID int64, limit int) ([]*capi.Session, error) {
assert.Equal(t, "pull", resourceType)
assert.Equal(t, int64(999999), resourceID)
assert.Equal(t, defaultLimit, limit)
return []*capi.Session{
{
ID: "some-session-id",
Name: "session one",
State: "completed",
LastUpdatedAt: sampleCompletedAt,
// Rest of the fields are not not meant to be used or relied upon
},
{
ID: "some-other-session-id",
Name: "session two",
State: "completed",
LastUpdatedAt: sampleCompletedAt,
// Rest of the fields are not not meant to be used or relied upon
},
}, nil
}
m.GetSessionFunc = func(_ context.Context, id string) (*capi.Session, error) {
assert.Equal(t, "some-session-id", id)
return &capi.Session{
ID: "some-session-id",
Name: "session one",
State: "completed",
CreatedAt: sampleDate,
CompletedAt: sampleCompletedAt,
LastUpdatedAt: sampleCompletedAt,
PremiumRequests: 1.5,
PullRequest: &api.PullRequest{
Title: "fix something",
Number: 101,
URL: "https://github.com/OWNER/REPO/pull/101",
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
User: &api.GitHubUser{
Login: "octocat",
},
}, nil
}
},
promptStubs: func(t *testing.T, pm *prompter.MockPrompter) {
pm.RegisterSelect(
"Select a session",
[]string{
"✓ session one • updated about 5 hours ago",
"✓ session two • updated about 5 hours ago",
},
func(_, _ string, opts []string) (int, error) {
return prompter.IndexFor(opts, "✓ session one • updated about 5 hours ago")
},
)
},
wantOut: heredoc.Doc(`
Ready for review • session one
Started on behalf of octocat about 6 hours ago
Used 1.5 premium request(s) • Duration 5m0s
OWNER/REPO#101 • fix something
For detailed session logs, try:
gh agent-task view 'some-session-id' --log
View this session on GitHub:
https://github.com/OWNER/REPO/pull/101/agent-sessions/some-session-id
`),
},
{
name: "with pr number, api error, web mode (tty)",
tty: true,
opts: ViewOptions{
SelectorArg: "101",
Finder: prShared.NewMockFinder(
"101",
&api.PullRequest{
FullDatabaseID: "999999",
URL: "https://github.com/OWNER/REPO/pull/101",
},
ghrepo.New("OWNER", "REPO"),
),
Web: true,
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.ListSessionsByResourceIDFunc = func(_ context.Context, _ string, _ int64, _ int) ([]*capi.Session, error) {
return nil, errors.New("some error")
}
},
wantErr: errors.New("failed to list sessions for pull request: some error"),
},
{
name: "with pr number, single session, web mode (tty)",
tty: true,
opts: ViewOptions{
SelectorArg: "101",
Finder: prShared.NewMockFinder(
"101",
&api.PullRequest{
FullDatabaseID: "999999",
URL: "https://github.com/OWNER/REPO/pull/101",
},
ghrepo.New("OWNER", "REPO"),
),
Web: true,
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.ListSessionsByResourceIDFunc = func(_ context.Context, resourceType string, resourceID int64, limit int) ([]*capi.Session, error) {
assert.Equal(t, "pull", resourceType)
assert.Equal(t, int64(999999), resourceID)
assert.Equal(t, defaultLimit, limit)
return []*capi.Session{
{
ID: "some-session-id",
State: "completed",
Name: "session one",
CreatedAt: sampleDate,
CompletedAt: sampleCompletedAt,
PremiumRequests: 1.5,
PullRequest: &api.PullRequest{
Title: "fix something",
Number: 101,
URL: "https://github.com/OWNER/REPO/pull/101",
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
// User data is irrelevant in this case
},
}, nil
}
},
wantBrowserURL: "https://github.com/OWNER/REPO/pull/101/agent-sessions",
wantStderr: "Opening https://github.com/OWNER/REPO/pull/101/agent-sessions in your browser.\n",
},
{
name: "with pr number, multiple sessions, web mode (tty)",
tty: true,
opts: ViewOptions{
SelectorArg: "101",
Finder: prShared.NewMockFinder(
"101",
&api.PullRequest{
FullDatabaseID: "999999",
URL: "https://github.com/OWNER/REPO/pull/101",
},
ghrepo.New("OWNER", "REPO"),
),
Web: true,
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.ListSessionsByResourceIDFunc = func(_ context.Context, resourceType string, resourceID int64, limit int) ([]*capi.Session, error) {
assert.Equal(t, "pull", resourceType)
assert.Equal(t, int64(999999), resourceID)
assert.Equal(t, defaultLimit, limit)
return []*capi.Session{
{
ID: "some-session-id",
Name: "session one",
State: "completed",
CreatedAt: sampleDate,
CompletedAt: sampleCompletedAt,
PremiumRequests: 1.5,
PullRequest: &api.PullRequest{
Title: "fix something",
Number: 101,
URL: "https://github.com/OWNER/REPO/pull/101",
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
// User data is irrelevant in this case
},
{
ID: "some-other-session-id",
Name: "session two",
State: "completed",
CreatedAt: sampleDate,
CompletedAt: sampleCompletedAt,
PremiumRequests: 1.5,
PullRequest: &api.PullRequest{
Title: "fix something",
Number: 101,
URL: "https://github.com/OWNER/REPO/pull/101",
Repository: &api.PRRepository{
NameWithOwner: "OWNER/REPO",
},
},
// User data is irrelevant in this case
},
}, nil
}
},
wantBrowserURL: "https://github.com/OWNER/REPO/pull/101/agent-sessions",
wantStderr: "Opening https://github.com/OWNER/REPO/pull/101/agent-sessions in your browser.\n",
},
{
name: "with pr reference, multiple sessions, web mode (tty)",
tty: true,
opts: ViewOptions{
SelectorArg: "OWNER/REPO#101",
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.New("OWNER", "REPO"), nil
},
Web: true,
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.GetPullRequestDatabaseIDFunc = func(_ context.Context, hostname string, owner string, repo string, number int) (int64, string, error) {
assert.Equal(t, "github.com", hostname)
assert.Equal(t, "OWNER", owner)
assert.Equal(t, "REPO", repo)
assert.Equal(t, 101, number)
return 999999, "https://github.com/OWNER/REPO/pull/101", nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | true |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/agent-task/create/create.go | pkg/cmd/agent-task/create/create.go | package create
import (
"context"
"errors"
"fmt"
"net/url"
"strings"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/MakeNowJust/heredoc"
"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/cmd/agent-task/capi"
"github.com/cli/cli/v2/pkg/cmd/agent-task/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
const defaultLogPollInterval = 5 * time.Second
// CreateOptions holds options for create command
type CreateOptions struct {
IO *iostreams.IOStreams
BaseRepo func() (ghrepo.Interface, error)
CapiClient func() (capi.CapiClient, error)
Config func() (gh.Config, error)
LogRenderer func() shared.LogRenderer
Sleep func(d time.Duration)
ProblemStatement string
CustomAgent string
BackOff backoff.BackOff
BaseBranch string
Prompter prompter.Prompter
ProblemStatementFile string
Follow bool
}
func defaultLogRenderer() shared.LogRenderer {
return shared.NewLogRenderer()
}
func NewCmdCreate(f *cmdutil.Factory, runF func(*CreateOptions) error) *cobra.Command {
opts := &CreateOptions{
IO: f.IOStreams,
CapiClient: shared.CapiClientFunc(f),
Config: f.Config,
Prompter: f.Prompter,
LogRenderer: defaultLogRenderer,
Sleep: time.Sleep,
}
cmd := &cobra.Command{
Use: "create [<task description>] [flags]",
Short: "Create an agent task (preview)",
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
// Support -R/--repo override
opts.BaseRepo = f.BaseRepo
if err := cmdutil.MutuallyExclusive("only one of -F or arg can be provided", len(args) > 0, opts.ProblemStatementFile != ""); err != nil {
return err
}
// Populate ProblemStatement from arg
if len(args) > 0 {
opts.ProblemStatement = args[0]
if strings.TrimSpace(opts.ProblemStatement) == "" {
return cmdutil.FlagErrorf("task description cannot be empty")
}
} else if opts.ProblemStatementFile == "" && !opts.IO.CanPrompt() {
return cmdutil.FlagErrorf("a task description or -F is required when running non-interactively")
}
if runF != nil {
return runF(opts)
}
return createRun(opts)
},
Example: heredoc.Doc(`
# Create a task from an inline description
$ gh agent-task create "build me a new app"
# Create a task from an inline description and follow logs
$ gh agent-task create "build me a new app" --follow
# Create a task from a file
$ gh agent-task create -F task-desc.md
# Create a task with problem statement from stdin
$ echo "build me a new app" | gh agent-task create -F -
# Create a task with an editor
$ gh agent-task create
# Create a task with an editor and a file as a template
$ gh agent-task create -F task-desc.md
# Select a different base branch for the PR
$ gh agent-task create "fix errors" --base branch
# Create a task using the custom agent defined in '.github/agents/my-agent.md'
$ gh agent-task create "build me a new app" --custom-agent my-agent
`),
}
cmdutil.EnableRepoOverride(cmd, f)
cmd.Flags().StringVarP(&opts.ProblemStatementFile, "from-file", "F", "", "Read task description from `file` (use \"-\" to read from standard input)")
cmd.Flags().StringVarP(&opts.BaseBranch, "base", "b", "", "Base branch for the pull request (use default branch if not provided)")
cmd.Flags().BoolVar(&opts.Follow, "follow", false, "Follow agent session logs")
cmd.Flags().StringVarP(&opts.CustomAgent, "custom-agent", "a", "", "Use a custom agent for the task. e.g., use 'my-agent' for the 'my-agent.md' agent")
return cmd
}
func createRun(opts *CreateOptions) error {
repo, err := opts.BaseRepo()
if err != nil || repo == nil {
// Not printing the error that came back from BaseRepo() here because we want
// something clear, human friendly, and actionable.
return fmt.Errorf("a repository is required; re-run in a repository or supply one with --repo owner/name")
}
if opts.ProblemStatement == "" {
if opts.ProblemStatementFile != "" {
fileContent, err := cmdutil.ReadFile(opts.ProblemStatementFile, opts.IO.In)
if err != nil {
return fmt.Errorf("could not read task description file: %w", err)
}
trimmed := strings.TrimSpace(string(fileContent))
if trimmed == "" {
return errors.New("task description file cannot be empty")
}
opts.ProblemStatement = trimmed
} else {
desc, err := opts.Prompter.MarkdownEditor("Enter the task description", opts.ProblemStatement, false)
if err != nil {
return err
}
trimmed := strings.TrimSpace(string(desc))
if trimmed == "" {
return errors.New("a task description is required")
}
opts.ProblemStatement = trimmed
}
}
client, err := opts.CapiClient()
if err != nil {
return err
}
ctx := context.Background()
opts.IO.StartProgressIndicatorWithLabel(fmt.Sprintf("Creating agent task in %s/%s...", repo.RepoOwner(), repo.RepoName()))
defer opts.IO.StopProgressIndicator()
job, err := client.CreateJob(ctx, repo.RepoOwner(), repo.RepoName(), opts.ProblemStatement, opts.BaseBranch, opts.CustomAgent)
if err != nil {
return err
}
if opts.Follow {
opts.IO.StopProgressIndicator()
fmt.Fprintf(opts.IO.Out, "Displaying session logs for job %s. Press Ctrl+C to stop.\n", job.ID)
return followLogs(opts, client, job.SessionID)
}
sessionURL, err := fetchJobSessionURL(ctx, client, repo, job, opts.BackOff)
opts.IO.StopProgressIndicator()
if sessionURL != "" {
fmt.Fprintln(opts.IO.Out, sessionURL)
} else {
if err != nil {
// If this does happen ever, we still want the user to get the fallback
// message and URL. So, we don't return with this error, but we do still
// want to print it.
fmt.Fprintf(opts.IO.ErrOut, "%v\n", err)
}
fmt.Fprintf(opts.IO.Out, "job %s queued. View progress: %s\n", job.ID, capi.AgentsHomeURL)
}
return nil
}
func agentSessionWebURL(repo ghrepo.Interface, j *capi.Job) string {
if j.PullRequest == nil {
return ""
}
if j.SessionID == "" {
return fmt.Sprintf("https://github.com/%s/%s/pull/%d", url.PathEscape(repo.RepoOwner()), url.PathEscape(repo.RepoName()), j.PullRequest.Number)
}
return fmt.Sprintf("https://github.com/%s/%s/pull/%d/agent-sessions/%s", url.PathEscape(repo.RepoOwner()), url.PathEscape(repo.RepoName()), j.PullRequest.Number, url.PathEscape(j.SessionID))
}
// fetchJobSessionURL tries to return the agent session URL for a job. If the pull
// request is not yet available, ("", nil) is returned.
func fetchJobSessionURL(ctx context.Context, client capi.CapiClient, repo ghrepo.Interface, job *capi.Job, bo backoff.BackOff) (string, error) {
if job.PullRequest != nil && job.PullRequest.Number > 0 {
// Return the agent session URL if we happen to get it.
// Right now, this never happens.
return agentSessionWebURL(repo, job), nil
}
if bo == nil {
bo = backoff.NewExponentialBackOff(
backoff.WithMaxElapsedTime(10*time.Second),
backoff.WithInitialInterval(300*time.Millisecond),
backoff.WithMaxInterval(10*time.Second),
backoff.WithMultiplier(1.5),
)
}
jobWithPR, err := fetchJobWithBackoff(ctx, client, repo, job.ID, bo)
if jobWithPR != nil {
return agentSessionWebURL(repo, jobWithPR), nil
}
return "", err
}
// fetchJobWithBackoff polls the job resource until a PR number is present or the overall
// timeout elapses. It returns the updated Job on success, (nil, nil) on timeout,
// and (nil, error) only for non-retryable failures.
func fetchJobWithBackoff(ctx context.Context, client capi.CapiClient, repo ghrepo.Interface, jobID string, bo backoff.BackOff) (*capi.Job, error) {
// sentinel error to signal timeout
var errPRNotReady = errors.New("job not ready")
var result *capi.Job
retryErr := backoff.Retry(func() error {
j, err := client.GetJob(ctx, repo.RepoOwner(), repo.RepoName(), jobID)
if err != nil {
// Do not retry on GetJob errors; surface immediately.
return backoff.Permanent(err)
}
if j.PullRequest != nil && j.PullRequest.Number > 0 {
result = j
return nil
}
return errPRNotReady
}, backoff.WithContext(bo, ctx))
if retryErr != nil {
if errors.Is(retryErr, errPRNotReady) {
// Timed out
return nil, nil
}
return nil, retryErr
}
return result, nil
}
func followLogs(opts *CreateOptions, capiClient capi.CapiClient, sessionID string) error {
if err := opts.IO.StartPager(); err == nil {
defer opts.IO.StopPager()
} else {
fmt.Fprintf(opts.IO.ErrOut, "error starting pager: %v\n", err)
}
ctx := context.Background()
renderer := opts.LogRenderer()
var called bool
fetcher := func() ([]byte, error) {
if called {
opts.Sleep(defaultLogPollInterval)
}
called = true
raw, err := capiClient.GetSessionLogs(ctx, sessionID)
if err != nil {
return nil, err
}
return raw, nil
}
return renderer.Follow(fetcher, opts.IO.Out, opts.IO)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/agent-task/create/create_test.go | pkg/cmd/agent-task/create/create_test.go | package create
import (
"context"
"errors"
"io"
"os"
"path/filepath"
"testing"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/cenkalti/backoff/v4"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/prompter"
"github.com/cli/cli/v2/pkg/cmd/agent-task/capi"
"github.com/cli/cli/v2/pkg/cmd/agent-task/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewCmdCreate(t *testing.T) {
tests := []struct {
name string
args string
tty bool
wantOpts *CreateOptions
wantErr string
}{
{
name: "no args nor file returns no error (prompting path)",
tty: true,
wantOpts: &CreateOptions{
ProblemStatement: "",
ProblemStatementFile: "",
},
},
{
name: "arg only success",
args: "'task description from args'",
wantOpts: &CreateOptions{
ProblemStatement: "task description from args",
ProblemStatementFile: "",
},
},
{
name: "empty arg",
args: "''",
wantErr: "task description cannot be empty",
},
{
name: "whitespace arg",
args: "' '",
wantErr: "task description cannot be empty",
},
{
name: "whitespace and newline arg",
args: "'\n'",
wantErr: "task description cannot be empty",
},
{
name: "mutually exclusive arg and file",
args: "'some task inline' -F foo.md",
wantErr: "only one of -F or arg can be provided",
},
{
name: "base branch sets baseBranch field",
args: "'task description' -b feature",
wantOpts: &CreateOptions{
ProblemStatement: "task description",
ProblemStatementFile: "",
BaseBranch: "feature",
},
},
{
name: "with --follow",
args: "'task description from args' --follow",
wantOpts: &CreateOptions{
ProblemStatement: "task description from args",
ProblemStatementFile: "",
Follow: true,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, stdin, _, _ := iostreams.Test()
if tt.tty {
ios.SetStdinTTY(true)
ios.SetStdoutTTY(true)
ios.SetStderrTTY(true)
}
f := &cmdutil.Factory{IOStreams: ios}
var gotOpts *CreateOptions
cmd := NewCmdCreate(f, func(o *CreateOptions) error {
gotOpts = o
return nil
})
argv, err := shlex.Split(tt.args)
require.NoError(t, err)
cmd.SetArgs(argv)
cmd.SetIn(stdin)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
_, err = cmd.ExecuteC()
if tt.wantErr != "" {
require.EqualError(t, err, tt.wantErr)
} else {
require.NoError(t, err)
}
if tt.wantOpts != nil {
require.Equal(t, tt.wantOpts.ProblemStatement, gotOpts.ProblemStatement)
require.Equal(t, tt.wantOpts.ProblemStatementFile, gotOpts.ProblemStatementFile)
require.Equal(t, tt.wantOpts.BaseBranch, gotOpts.BaseBranch)
}
})
}
}
func Test_createRun(t *testing.T) {
tmpDir := t.TempDir()
taskDescFile := filepath.Join(tmpDir, "task-description.md")
emptyTaskDescFile := filepath.Join(tmpDir, "empty-task-description.md")
require.NoError(t, os.WriteFile(taskDescFile, []byte("task description from file"), 0600))
require.NoError(t, os.WriteFile(emptyTaskDescFile, []byte(" \n\n"), 0600))
sampleDateString := "2025-08-29T00:00:00Z"
sampleDate, err := time.Parse(time.RFC3339, sampleDateString)
require.NoError(t, err)
createdJobSuccess := capi.Job{
ID: "job123",
SessionID: "sess1",
Actor: &capi.JobActor{
ID: 1,
Login: "octocat",
},
CreatedAt: sampleDate,
UpdatedAt: sampleDate,
}
createdJobSuccessWithPR := capi.Job{
ID: "job123",
SessionID: "sess1",
Actor: &capi.JobActor{
ID: 1,
Login: "octocat",
},
CreatedAt: sampleDate,
UpdatedAt: sampleDate,
PullRequest: &capi.JobPullRequest{
ID: 101,
Number: 42,
},
}
tests := []struct {
name string
isTTY bool
opts *CreateOptions // input options (IO & BackOff set later)
capiStubs func(*testing.T, *capi.CapiClientMock)
logRendererStubs func(*testing.T, *shared.LogRendererMock)
wantStdout string
wantStdErr string
wantErr string
wantErrIs error
}{
{
name: "interactive, problem statement from arg",
isTTY: true,
opts: &CreateOptions{
BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil },
ProblemStatement: "task description from arg",
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.CreateJobFunc = func(ctx context.Context, owner, repo, problemStatement, baseBranch, customAgent string) (*capi.Job, error) {
require.Equal(t, "OWNER", owner)
require.Equal(t, "REPO", repo)
require.Equal(t, "task description from arg", problemStatement)
return &createdJobSuccessWithPR, nil
}
},
wantStdout: "https://github.com/OWNER/REPO/pull/42/agent-sessions/sess1\n",
},
{
name: "non-interactive, problem statement from arg",
opts: &CreateOptions{
BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil },
ProblemStatement: "task description from arg",
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.CreateJobFunc = func(ctx context.Context, owner, repo, problemStatement, baseBranch, customAgent string) (*capi.Job, error) {
require.Equal(t, "OWNER", owner)
require.Equal(t, "REPO", repo)
require.Equal(t, "task description from arg", problemStatement)
return &createdJobSuccessWithPR, nil
}
},
wantStdout: "https://github.com/OWNER/REPO/pull/42/agent-sessions/sess1\n",
},
{
name: "interactive, problem statement from file",
isTTY: true,
opts: &CreateOptions{
BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil },
ProblemStatement: "",
ProblemStatementFile: taskDescFile,
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.CreateJobFunc = func(ctx context.Context, owner, repo, problemStatement, baseBranch, customAgent string) (*capi.Job, error) {
require.Equal(t, "OWNER", owner)
require.Equal(t, "REPO", repo)
require.Equal(t, "task description from file", problemStatement)
return &createdJobSuccessWithPR, nil
}
},
wantStdout: "https://github.com/OWNER/REPO/pull/42/agent-sessions/sess1\n",
},
{
name: "non-interactive, problem statement loaded from file",
opts: &CreateOptions{
BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil },
ProblemStatement: "",
ProblemStatementFile: taskDescFile,
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.CreateJobFunc = func(ctx context.Context, owner, repo, problemStatement, baseBranch, customAgent string) (*capi.Job, error) {
require.Equal(t, "OWNER", owner)
require.Equal(t, "REPO", repo)
require.Equal(t, "task description from file", problemStatement)
return &createdJobSuccessWithPR, nil
}
},
wantStdout: "https://github.com/OWNER/REPO/pull/42/agent-sessions/sess1\n",
},
{
name: "interactive, problem statement from prompt/editor",
isTTY: true,
opts: &CreateOptions{
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.New("OWNER", "REPO"), nil
},
Prompter: &prompter.PrompterMock{
MarkdownEditorFunc: func(prompt, defaultValue string, blankAllowed bool) (string, error) {
require.Equal(t, "Enter the task description", prompt)
return "From editor", nil
},
},
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.CreateJobFunc = func(ctx context.Context, owner, repo, problemStatement, baseBranch, customAgent string) (*capi.Job, error) {
require.Equal(t, "From editor", problemStatement)
return &createdJobSuccessWithPR, nil
}
},
wantStdout: "https://github.com/OWNER/REPO/pull/42/agent-sessions/sess1\n",
},
{
name: "interactive, empty task description from editor returns error",
isTTY: true,
opts: &CreateOptions{
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.New("OWNER", "REPO"), nil
},
Prompter: &prompter.PrompterMock{
MarkdownEditorFunc: func(prompt, defaultValue string, blankAllowed bool) (string, error) {
return " ", nil
},
},
},
wantErr: "a task description is required",
},
{
name: "missing repo returns error",
opts: &CreateOptions{
BaseRepo: func() (ghrepo.Interface, error) {
return nil, nil
}},
wantErr: "a repository is required; re-run in a repository or supply one with --repo owner/name",
},
{
name: "problem statement loaded from arg non-interactively doesn't prompt or return error",
opts: &CreateOptions{
BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil },
ProblemStatement: "task description",
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.CreateJobFunc = func(ctx context.Context, owner, repo, problemStatement, baseBranch, customAgent string) (*capi.Job, error) {
require.Equal(t, "OWNER", owner)
require.Equal(t, "REPO", repo)
require.Equal(t, "task description", problemStatement)
return &createdJobSuccessWithPR, nil
}
},
wantStdout: "https://github.com/OWNER/REPO/pull/42/agent-sessions/sess1\n",
},
{
name: "base branch included in create payload",
opts: &CreateOptions{
BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil },
ProblemStatement: "Do the thing",
BaseBranch: "feature",
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.CreateJobFunc = func(ctx context.Context, owner, repo, problemStatement, baseBranch, customAgent string) (*capi.Job, error) {
require.Equal(t, "OWNER", owner)
require.Equal(t, "REPO", repo)
require.Equal(t, "Do the thing", problemStatement)
require.Equal(t, "feature", baseBranch)
return &createdJobSuccess, nil
}
m.GetJobFunc = func(ctx context.Context, owner, repo, jobID string) (*capi.Job, error) {
require.Equal(t, "OWNER", owner)
require.Equal(t, "REPO", repo)
require.Equal(t, "job123", jobID)
return &createdJobSuccessWithPR, nil
}
},
wantStdout: "https://github.com/OWNER/REPO/pull/42/agent-sessions/sess1\n",
},
{
name: "create task API failure returns error",
opts: &CreateOptions{
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.New("OWNER", "REPO"), nil
},
ProblemStatement: "Do the thing",
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.CreateJobFunc = func(ctx context.Context, owner, repo, problemStatement, baseBranch, customAgent string) (*capi.Job, error) {
require.Equal(t, "OWNER", owner)
require.Equal(t, "REPO", repo)
require.Equal(t, "Do the thing", problemStatement)
require.Equal(t, "", baseBranch)
return nil, errors.New("some API error")
}
},
wantErr: "some API error",
},
{
name: "get job API failure surfaces error",
opts: &CreateOptions{
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.New("OWNER", "REPO"), nil
},
ProblemStatement: "Do the thing",
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.CreateJobFunc = func(ctx context.Context, owner, repo, problemStatement, baseBranch, customAgent string) (*capi.Job, error) {
require.Equal(t, "OWNER", owner)
require.Equal(t, "REPO", repo)
require.Equal(t, "Do the thing", problemStatement)
require.Equal(t, "", baseBranch)
return &createdJobSuccess, nil
}
m.GetJobFunc = func(ctx context.Context, owner, repo, jobID string) (*capi.Job, error) {
return nil, errors.New("some error")
}
},
wantStdErr: "some error\n",
wantStdout: "job job123 queued. View progress: https://github.com/copilot/agents\n",
},
{
name: "success with immediate PR",
opts: &CreateOptions{
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.New("OWNER", "REPO"), nil
},
ProblemStatement: "Do the thing",
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.CreateJobFunc = func(ctx context.Context, owner, repo, problemStatement, baseBranch, customAgent string) (*capi.Job, error) {
require.Equal(t, "OWNER", owner)
require.Equal(t, "REPO", repo)
require.Equal(t, "Do the thing", problemStatement)
require.Equal(t, "", baseBranch)
return &createdJobSuccessWithPR, nil
}
},
wantStdout: "https://github.com/OWNER/REPO/pull/42/agent-sessions/sess1\n",
},
{
name: "success with delayed PR after polling",
opts: &CreateOptions{
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.New("OWNER", "REPO"), nil
},
ProblemStatement: "Do the thing",
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.CreateJobFunc = func(ctx context.Context, owner, repo, problemStatement, baseBranch, customAgent string) (*capi.Job, error) {
require.Equal(t, "OWNER", owner)
require.Equal(t, "REPO", repo)
require.Equal(t, "Do the thing", problemStatement)
require.Equal(t, "", baseBranch)
return &createdJobSuccess, nil
}
m.GetJobFunc = func(ctx context.Context, owner, repo, jobID string) (*capi.Job, error) {
require.Equal(t, "OWNER", owner)
require.Equal(t, "REPO", repo)
require.Equal(t, "job123", jobID)
return &createdJobSuccessWithPR, nil
}
},
wantStdout: "https://github.com/OWNER/REPO/pull/42/agent-sessions/sess1\n",
},
{
name: "fallback after polling timeout returns link to global agents page",
opts: &CreateOptions{
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.New("OWNER", "REPO"), nil
},
ProblemStatement: "Do the thing",
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.CreateJobFunc = func(ctx context.Context, owner, repo, problemStatement, baseBranch, customAgent string) (*capi.Job, error) {
require.Equal(t, "OWNER", owner)
require.Equal(t, "REPO", repo)
require.Equal(t, "Do the thing", problemStatement)
require.Equal(t, "", baseBranch)
return &createdJobSuccess, nil
}
count := 0
m.GetJobFunc = func(ctx context.Context, owner, repo, jobID string) (*capi.Job, error) {
if count++; count > 4 {
require.FailNow(t, "too many get calls")
}
return &createdJobSuccess, nil
}
},
wantStdout: "job job123 queued. View progress: https://github.com/copilot/agents\n",
},
{
name: "success with follow logs and delayed PR after polling",
opts: &CreateOptions{
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.New("OWNER", "REPO"), nil
},
ProblemStatement: "Do the thing",
Follow: true,
Sleep: func(d time.Duration) {},
},
capiStubs: func(t *testing.T, m *capi.CapiClientMock) {
m.CreateJobFunc = func(ctx context.Context, owner, repo, problemStatement, baseBranch, customAgent string) (*capi.Job, error) {
require.Equal(t, "OWNER", owner)
require.Equal(t, "REPO", repo)
require.Equal(t, "Do the thing", problemStatement)
require.Equal(t, "", baseBranch)
return &createdJobSuccess, nil
}
m.GetJobFunc = func(ctx context.Context, owner, repo, jobID string) (*capi.Job, error) {
require.Equal(t, "OWNER", owner)
require.Equal(t, "REPO", repo)
require.Equal(t, "job123", jobID)
return &createdJobSuccessWithPR, nil
}
var count int
m.GetSessionLogsFunc = func(_ context.Context, id string) ([]byte, error) {
assert.Equal(t, "sess1", id)
count++
require.Less(t, count, 3, "too many calls to fetch logs")
if count == 1 {
return []byte("<raw-logs-one>"), nil
}
return []byte("<raw-logs-two>"), nil
}
},
logRendererStubs: func(t *testing.T, m *shared.LogRendererMock) {
m.FollowFunc = func(fetcher func() ([]byte, error), w io.Writer, ios *iostreams.IOStreams) error {
raw, err := fetcher()
require.NoError(t, err)
w.Write([]byte("(rendered:) " + string(raw) + "\n"))
raw, err = fetcher()
require.NoError(t, err)
w.Write([]byte("(rendered:) " + string(raw) + "\n"))
return nil
}
},
wantStdout: heredoc.Doc(`
Displaying session logs for job job123. Press Ctrl+C to stop.
(rendered:) <raw-logs-one>
(rendered:) <raw-logs-two>
`),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
capiClientMock := &capi.CapiClientMock{}
if tt.capiStubs != nil {
tt.capiStubs(t, capiClientMock)
}
ios, _, stdout, stderr := iostreams.Test()
if tt.isTTY {
ios.SetStdinTTY(true)
ios.SetStderrTTY(true)
ios.SetStdoutTTY(true)
}
tt.opts.IO = ios
tt.opts.CapiClient = func() (capi.CapiClient, error) {
return capiClientMock, nil
}
// fast backoff
tt.opts.BackOff = backoff.WithMaxRetries(&backoff.ZeroBackOff{}, 3)
logRenderer := &shared.LogRendererMock{}
if tt.logRendererStubs != nil {
tt.logRendererStubs(t, logRenderer)
}
tt.opts.LogRenderer = func() shared.LogRenderer {
return logRenderer
}
err := createRun(tt.opts)
if tt.wantErrIs != nil {
require.ErrorIs(t, err, tt.wantErrIs)
}
if tt.wantErr != "" {
require.Error(t, err)
require.Equal(t, tt.wantErr, err.Error())
} else if tt.wantErrIs == nil {
require.NoError(t, err)
}
require.Equal(t, tt.wantStdout, stdout.String())
require.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/agent-task/shared/capi.go | pkg/cmd/agent-task/shared/capi.go | package shared
import (
"errors"
"fmt"
"regexp"
"github.com/cli/cli/v2/pkg/cmd/agent-task/capi"
prShared "github.com/cli/cli/v2/pkg/cmd/pr/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
)
const uuidPattern = `[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}`
var sessionIDRegexp = regexp.MustCompile(fmt.Sprintf("^%s$", uuidPattern))
var agentSessionURLRegexp = regexp.MustCompile(fmt.Sprintf("^/agent-sessions/(%s)$", uuidPattern))
func CapiClientFunc(f *cmdutil.Factory) func() (capi.CapiClient, error) {
return func() (capi.CapiClient, error) {
cfg, err := f.Config()
if err != nil {
return nil, err
}
httpClient, err := f.HttpClient()
if err != nil {
return nil, err
}
authCfg := cfg.Authentication()
host, _ := authCfg.DefaultHost()
token, _ := authCfg.ActiveToken(host)
return capi.NewCAPIClient(httpClient, token, host), nil
}
}
func IsSessionID(s string) bool {
return sessionIDRegexp.MatchString(s)
}
// ParseSessionIDFromURL parses session ID from a pull request's agent session
// URL, which is of the form:
//
// `https://github.com/OWNER/REPO/pull/NUMBER/agent-sessions/SESSION-ID`
func ParseSessionIDFromURL(u string) (string, error) {
_, _, rest, err := prShared.ParseURL(u)
if err != nil {
return "", err
}
match := agentSessionURLRegexp.FindStringSubmatch(rest)
if match == nil {
return "", errors.New("not a valid agent session URL")
}
return match[1], nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/agent-task/shared/log_test.go | pkg/cmd/agent-task/shared/log_test.go | package shared
import (
"os"
"slices"
"strings"
"testing"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestFollow(t *testing.T) {
tests := []struct {
name string
log string
wantStdoutFile string
wantStderrFile string
}{
{
name: "sample log 1",
log: "testdata/log-1-input.txt",
wantStdoutFile: "testdata/log-1-want.txt",
},
{
name: "sample log 2",
log: "testdata/log-2-input.txt",
wantStdoutFile: "testdata/log-2-want.txt",
},
{
name: "sample log 3 (tolerant parse failures)",
log: "testdata/log-3-synthetic-failures-input.txt",
wantStdoutFile: "testdata/log-3-synthetic-failures-want.txt",
wantStderrFile: "testdata/log-3-synthetic-failures-want-stderr.txt",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
raw, err := os.ReadFile(tt.log)
require.NoError(t, err)
// Normalize CRLF to LF to make the tests OS-agnostic.
raw = []byte(strings.ReplaceAll(string(raw), "\r\n", "\n"))
lines := slices.DeleteFunc(strings.Split(string(raw), "\n"), func(line string) bool {
return line == ""
})
var hits int
fetcher := func() ([]byte, error) {
hits++
if hits > len(lines) {
require.FailNow(t, "too many API calls")
}
return []byte(strings.Join(lines[0:hits], "\n\n")), nil
}
ios, _, stdout, stderr := iostreams.Test()
err = NewLogRenderer().Follow(fetcher, stdout, ios)
require.NoError(t, err)
// Handy note for updating the testdata files when they change:
// ext := filepath.Ext(tt.log)
// stripped := strings.TrimSuffix(tt.log, ext)
// stripped = strings.TrimSuffix(stripped, "-input")
// os.WriteFile(stripped+"-want"+ext, stdout.Bytes(), 0644)
// if tt.wantStderrFile != "" {
// os.WriteFile(stripped+"-want-stderr"+ext, stderr.Bytes(), 0644)
// }
wantStdout, err := os.ReadFile(tt.wantStdoutFile)
require.NoError(t, err)
// Normalize CRLF to LF to make the tests OS-agnostic.
wantStdout = []byte(strings.ReplaceAll(string(wantStdout), "\r\n", "\n"))
assert.Equal(t, string(wantStdout), stdout.String())
if tt.wantStderrFile != "" {
wantStderr, err := os.ReadFile(tt.wantStderrFile)
require.NoError(t, err)
// Normalize CRLF to LF to make the tests OS-agnostic.
wantStderr = []byte(strings.ReplaceAll(string(wantStderr), "\r\n", "\n"))
assert.Equal(t, string(wantStderr), stderr.String())
} else {
require.Empty(t, stderr, "expected no stderr output")
}
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/agent-task/shared/capi_test.go | pkg/cmd/agent-task/shared/capi_test.go | package shared
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestIsSession(t *testing.T) {
assert.True(t, IsSessionID("00000000-0000-0000-0000-000000000000"))
assert.True(t, IsSessionID("e2fa49d2-f164-4a56-ab99-498090b8fcdf"))
assert.True(t, IsSessionID("E2FA49D2-F164-4A56-AB99-498090B8FCDF"))
assert.False(t, IsSessionID(""))
assert.False(t, IsSessionID(" "))
assert.False(t, IsSessionID("\n"))
assert.False(t, IsSessionID("not-a-uuid"))
assert.False(t, IsSessionID("000000000000000000000000000000000000"))
assert.False(t, IsSessionID("00000000-0000-0000-0000-000000000000-extra"))
}
func TestParsePullRequestAgentSessionURL(t *testing.T) {
tests := []struct {
name string
url string
wantSessionID string
wantErr bool
}{
{
name: "valid",
url: "https://github.com/OWNER/REPO/pull/123/agent-sessions/e2fa49d2-f164-4a56-ab99-498090b8fcdf",
wantSessionID: "e2fa49d2-f164-4a56-ab99-498090b8fcdf",
},
{
name: "invalid session id",
url: "https://github.com/OWNER/REPO/pull/123/agent-sessions/fff",
wantErr: true,
},
{
name: "no session id, trailing slash",
url: "https://github.com/OWNER/REPO/pull/123/agent-sessions/",
wantErr: true,
},
{
name: "no session id",
url: "https://github.com/OWNER/REPO/pull/123/agent-sessions",
wantErr: true,
},
{
name: "invalid pr url",
url: "https://github.com/OWNER/REPO/issues/123",
wantErr: true,
},
{
name: "empty",
url: "",
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
sessionID, err := ParseSessionIDFromURL(tt.url)
if tt.wantErr {
require.Error(t, err)
assert.Zero(t, sessionID)
return
}
require.NoError(t, err)
assert.Equal(t, tt.wantSessionID, sessionID)
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/agent-task/shared/log.go | pkg/cmd/agent-task/shared/log.go | package shared
import (
"encoding/json"
"errors"
"fmt"
"io"
"path/filepath"
"slices"
"strings"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/pkg/markdown"
)
//go:generate moq -rm -out log_mock.go . LogRenderer
type LogRenderer interface {
Follow(fetcher func() ([]byte, error), w io.Writer, io *iostreams.IOStreams) error
Render(logs []byte, w io.Writer, io *iostreams.IOStreams) (stop bool, err error)
}
type logRenderer struct{}
func NewLogRenderer() LogRenderer {
return &logRenderer{}
}
// Follow continuously fetches logs using the provided fetcher function and
// renders them to the provided writer. It stops when Render indicates to stop.
func (r *logRenderer) Follow(fetcher func() ([]byte, error), w io.Writer, io *iostreams.IOStreams) error {
var last string
for {
raw, err := fetcher()
if err != nil {
return err
}
logs := string(raw)
if logs == last {
continue
}
diff := strings.TrimSpace(logs[len(last):])
if stop, err := r.Render([]byte(diff), w, io); err != nil {
return err
} else if stop {
return nil
}
last = logs
}
}
// Render processes the given logs and writes the rendered output to w.
// Errors are returned when an unexpected log entry is encountered.
func (r *logRenderer) Render(logs []byte, w io.Writer, io *iostreams.IOStreams) (bool, error) {
lines := slices.DeleteFunc(strings.Split(string(logs), "\n"), func(line string) bool {
return line == ""
})
for _, line := range lines {
raw, found := strings.CutPrefix(line, "data: ")
if !found {
return false, errors.New("unexpected log format")
}
// The only log entry type we're interested in is a chat completion chunk,
// which can be verified by a successful unmarshal into the corresponding
// type AND the Object field being equal to "chat.completion.chunk". The
// latter is to avoid accepting an empty JSON object (i.e. "{}"). Also,
// if the entry is not what we expect, we should just skip and avoid
// returning an error.
var entry chatCompletionChunkEntry
err := json.Unmarshal([]byte(raw), &entry)
if err != nil || entry.Object != "chat.completion.chunk" {
continue
}
if stop, err := renderLogEntry(entry, w, io); err != nil {
return false, fmt.Errorf("failed to process log entry: %w", err)
} else if stop {
return true, nil
}
}
return false, nil
}
func renderLogEntry(entry chatCompletionChunkEntry, w io.Writer, io *iostreams.IOStreams) (bool, error) {
cs := io.ColorScheme()
var stop bool
for _, choice := range entry.Choices {
if choice.FinishReason == "stop" {
stop = true
}
if len(choice.Delta.ToolCalls) == 0 {
if choice.Delta.Content != "" && choice.Delta.Role == "assistant" {
// Copilot message and we should display.
renderRawMarkdown(choice.Delta.Content, w, io)
}
continue
}
// Since we don't want to clear-and-reprint live progress of events, we
// need to only process entries that correspond to a finished tool call.
// Such entries have a non-empty Content field.
if choice.Delta.Content == "" {
continue
}
if choice.Delta.ReasoningText != "" {
// Note that this should be formatted as a normal "thought" message,
// without the heading.
renderRawMarkdown(choice.Delta.ReasoningText, w, io)
}
for _, tc := range choice.Delta.ToolCalls {
name := tc.Function.Name
if name == "" {
continue
}
args := tc.Function.Arguments
switch name {
case "run_setup":
if v := unmarshal[runSetupToolArgs](args); v != nil {
renderToolCallTitle(w, cs, v.Name, "")
continue
}
case "view":
args := viewToolArgs{}
if err := json.Unmarshal([]byte(tc.Function.Arguments), &args); err != nil {
fmt.Fprintf(io.ErrOut, "\nfailed to parse 'view' tool call arguments: %v\n", err)
continue
}
renderToolCallTitle(w, cs, fmt.Sprintf("View %s", cs.Bold(relativeFilePath(args.Path))), "")
content := stripDiffFormat(choice.Delta.Content)
if err := renderFileContentAsMarkdown(args.Path, content, w, io); err != nil {
fmt.Fprintf(io.ErrOut, "\nfailed to render viewed file content: %v\n\n", err)
fmt.Fprintln(io.ErrOut, content) // raw fallback
}
case "bash":
if v := unmarshal[bashToolArgs](args); v != nil {
if v.Description != "" {
renderToolCallTitle(w, cs, "Bash", v.Description)
} else {
renderToolCallTitle(w, cs, "Run Bash command", "")
}
contentWithCommand := choice.Delta.Content
if v.Command != "" {
contentWithCommand = fmt.Sprintf("$ %s\n%s", v.Command, choice.Delta.Content)
}
if err := renderFileContentAsMarkdown("commands.sh", contentWithCommand, w, io); err != nil {
fmt.Fprintf(io.ErrOut, "\nfailed to render bash command output: %v\n\n", err)
fmt.Fprintln(io.ErrOut, contentWithCommand)
}
}
// TODO: consider including more details for these bash-related tool calls.
case "write_bash":
if v := unmarshal[writeBashToolArgs](args); v != nil {
renderToolCallTitle(w, cs, "Send input to Bash session", "")
continue
}
case "read_bash":
if v := unmarshal[readBashToolArgs](args); v != nil {
renderToolCallTitle(w, cs, "Read logs from Bash session", "")
continue
}
case "stop_bash":
if v := unmarshal[stopBashToolArgs](args); v != nil {
renderToolCallTitle(w, cs, "Stop Bash session", "")
continue
}
case "async_bash":
if v := unmarshal[asyncBashToolArgs](args); v != nil {
renderToolCallTitle(w, cs, "Start or send input to long-running Bash session", "")
continue
}
case "read_async_bash":
if v := unmarshal[readAsyncBashToolArgs](args); v != nil {
renderToolCallTitle(w, cs, "View logs from long-running Bash session", "")
continue
}
case "stop_async_bash":
if v := unmarshal[stopAsyncBashToolArgs](args); v != nil {
renderToolCallTitle(w, cs, "Stop long-running Bash session", "")
continue
}
case "think":
args := thinkToolArgs{}
if err := json.Unmarshal([]byte(tc.Function.Arguments), &args); err != nil {
fmt.Fprintf(io.ErrOut, "\nfailed to parse 'think' tool call arguments: %v\n", err)
continue
}
// NOTE: omit the delta.content since it's the same as thought
renderToolCallTitle(w, cs, "Thought", "")
if err := renderRawMarkdown(args.Thought, w, io); err != nil {
fmt.Fprintf(io.ErrOut, "\nfailed to render thought: %v\n", err)
}
case "report_progress":
args := reportProgressToolArgs{}
if err := json.Unmarshal([]byte(tc.Function.Arguments), &args); err != nil {
fmt.Fprintf(io.ErrOut, "\nfailed to parse 'report_progress' tool call arguments: %v\n", err)
continue
}
renderToolCallTitle(w, cs, "Progress update", cs.Bold(args.CommitMessage))
if args.PrDescription != "" {
if err := renderRawMarkdown(args.PrDescription, w, io); err != nil {
fmt.Fprintf(io.ErrOut, "\nfailed to render PR description: %v\n", err)
}
}
// TODO: KW I wasn't able to get this case to populate ever.
if choice.Delta.Content != "" {
// Try to treat this as JSON
if err := renderContentAsJSONMarkdown("", choice.Delta.Content, w, io); err != nil {
fmt.Fprintf(io.ErrOut, "\nfailed to render progress update content: %v\n", err)
}
}
case "create":
args := createToolArgs{}
if err := json.Unmarshal([]byte(tc.Function.Arguments), &args); err != nil {
fmt.Fprintf(io.ErrOut, "\nfailed to parse 'create' tool call arguments: %v\n", err)
continue
}
renderToolCallTitle(w, cs, "Create", cs.Bold(relativeFilePath(args.Path)))
if err := renderFileContentAsMarkdown(args.Path, args.FileText, w, io); err != nil {
fmt.Fprintf(io.ErrOut, "\nfailed to render created file content: %v\n\n", err)
fmt.Fprintln(io.ErrOut, args.FileText)
}
case "str_replace":
args := strReplaceToolArgs{}
if err := json.Unmarshal([]byte(tc.Function.Arguments), &args); err != nil {
fmt.Fprintf(io.ErrOut, "\nfailed to parse 'str_replace' tool call arguments: %v\n", err)
continue
}
renderToolCallTitle(w, cs, "Edit", cs.Bold(relativeFilePath(args.Path)))
if err := renderFileContentAsMarkdown("output.diff", choice.Delta.Content, w, io); err != nil {
fmt.Fprintf(io.ErrOut, "\nfailed to render str_replace diff: %v\n\n", err)
fmt.Fprintln(io.ErrOut, choice.Delta.Content)
}
default:
// Unknown tool call. For example for "codeql_checker":
// NOTE: omit the delta.content since we don't know how large could that be
renderGenericToolCall(w, cs, name)
// If it's JSON, treat it as such, otherwise we skip whatever the content is.
_ = renderContentAsJSONMarkdown("Output:", choice.Delta.Content, w, io)
// The entirety of the args can be treated as "input" to the tool call.
// We try to render it as JSON, but if that fails, just skip it.
_ = renderContentAsJSONMarkdown("Input:", args, w, io)
}
}
}
return stop, nil
}
// renderContentAsJSONMarkdown tries to unmarshal the given content as JSON,
// wrap that content in a markdown JSON code block, and render it as markdown.
// If label is non-empty, it is rendered as leading text before and outside of
// the JSON block.
func renderContentAsJSONMarkdown(label, content string, w io.Writer, io *iostreams.IOStreams) error {
var contentAsJSON any
if err := json.Unmarshal([]byte(content), &contentAsJSON); err == nil {
marshaled, err := json.MarshalIndent(contentAsJSON, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal JSON: %w", err)
}
if label != "" {
if err := renderRawMarkdown(label, w, io); err != nil {
return fmt.Errorf("failed to render label: %w", err)
}
}
if err := renderFileContentAsMarkdown("output.json", string(marshaled), w, io); err != nil {
return fmt.Errorf("failed to render JSON: %w", err)
}
}
return nil
}
// renderRawMarkdown renders the given raw markdown string to the given writer.
// Use for complete markdown content from tool calls that need no conversion.
func renderRawMarkdown(md string, w io.Writer, io *iostreams.IOStreams) error {
// Glamour doesn't add leading newlines when content is a complete
// markdown document. So, we must add the leading newline.
formatFunc := func(s string) string {
return fmt.Sprintf("\n%s\n\n", s)
}
return renderMarkdownWithFormat(md, w, io, formatFunc)
}
// renderMarkdownWithFormat renders the given markdown string to the given writer.
// If a formatFunc is provided, the md string is ran through it before
// rendering. This can be used to add newlines before and after the content.
func renderMarkdownWithFormat(md string, w io.Writer, io *iostreams.IOStreams, formatFunc func(string) string) error {
rendered, err := markdown.Render(md,
markdown.WithTheme(io.TerminalTheme()),
markdown.WithWrap(io.TerminalWidth()),
)
if err != nil {
return fmt.Errorf("failed to render markdown: %w", err)
}
rendered = strings.TrimSpace(rendered)
if formatFunc != nil {
rendered = formatFunc(rendered)
}
fmt.Fprint(w, rendered)
return nil
}
// stripDiffFormat implements a primitive conversion from a diff string to a
// plain text representation by removing diff-specific formatting.
func stripDiffFormat(diff string) string {
lines := strings.Split(diff, "\n")
// Find where the hunk header ends.
hunkEndIndex := -1
for i, line := range lines {
if strings.HasPrefix(line, "@@") {
hunkEndIndex = i
break
}
}
// This isn't a diff.
if hunkEndIndex == -1 {
return diff
}
// Removing hunk header.
lines = lines[hunkEndIndex+1:]
// Strip the leading + and - from lines, if they exist.
var stripped []string
for _, line := range lines {
if strings.HasPrefix(line, "+") || strings.HasPrefix(line, "-") {
stripped = append(stripped, line[1:])
} else {
stripped = append(stripped, line)
}
}
return strings.Join(stripped, "\n")
}
// renderFileContentAsMarkdown renders the given content as markdown
// based on the file extension of the path.
func renderFileContentAsMarkdown(path, content string, w io.Writer, io *iostreams.IOStreams) error {
lang := filepath.Ext(filepath.ToSlash(path))
if lang == ".md" {
return renderRawMarkdown(content, w, io)
}
md := fmt.Sprintf("```%s\n%s\n```", lang, content)
// Glamour adds leading newlines when content is only a code block,
// so we only want to add a trailing newline.
formatFunc := func(s string) string {
return fmt.Sprintf("%s\n\n", s)
}
return renderMarkdownWithFormat(md, w, io, formatFunc)
}
// relativeFilePath converts an absolute file path to a relative one.
// We expect paths to be of the form: /home/runner/work/<repo-owner>/<repo-name>/path/to/file
// The expected output of that example is: path/to/file
func relativeFilePath(absPath string) string {
relPath := strings.TrimPrefix(absPath, "/home/runner/work/")
parts := strings.Split(relPath, "/")
// The last two parts of the path are the
// repo name and the repo owner.
// If that's all we have (or less),
// we return a friendly name "repository".
if len(parts) > 2 {
// Drop the repo owner and name, returning the remaining path.
return strings.Join(parts[2:], "/")
}
return "repository"
}
func unmarshal[T any](raw string) *T {
var t T
if err := json.Unmarshal([]byte(raw), &t); err != nil {
return nil
}
return &t
}
// renderToolCallTitle renders a title for a tool call. Should be followed by a
// call to render a markdown representation of the tool call's content.
func renderToolCallTitle(w io.Writer, cs *iostreams.ColorScheme, toolName, title string) {
// Should not happen, but if it does we still want to print a heading
// with the information we do have.
if toolName == "" {
toolName = "Generic tool call"
}
if title != "" {
title = cs.Bold(title)
}
if title != "" {
fmt.Fprintf(w, "%s: %s\n", toolName, title)
} else {
fmt.Fprintf(w, "%s\n", toolName)
}
}
// genericToolCallNamesToTitles maps known generic tool call identifiers to human-friendly titles.
var genericToolCallNamesToTitles = map[string]string{
// Custom tools, the GitHub UI doesn't currently have these.
"codeql_checker": "Run CodeQL analysis",
// Playwright tools.
"playwright-browser_navigate": "Navigate Playwright web browser to a URL",
"playwright-browser_navigate_back": "Navigate back in Playwright web browser",
"playwright-browser_navigate_forward": "Navigate forward in Playwright web browser",
"playwright-browser_click": "Click element in Playwright web browser",
"playwright-browser_take_screenshot": "Take screenshot of Playwright web browser",
"playwright-browser_type": "Type in Playwright web browser",
"playwright-browser_wait_for": "Wait for text to appear/disappear in Playwright web browser",
"playwright-browser_evaluate": "Run JavaScript in Playwright web browser",
"playwright-browser_snapshot": "Take snapshot of page in Playwright web browser",
"playwright-browser_resize": "Resize Playwright web browser window",
"playwright-browser_close": "Close Playwright web browser",
"playwright-browser_press_key": "Press key in Playwright web browser",
"playwright-browser_select_option": "Select option in Playwright web browser",
"playwright-browser_handle_dialog": "Interact with dialog in Playwright web browser",
"playwright-browser_console_messages": "Get console messages from Playwright web browser",
"playwright-browser_drag": "Drag mouse between elements in Playwright web browser",
"playwright-browser_file_upload": "Upload file in Playwright web browser",
"playwright-browser_hover": "Hover mouse over element in Playwright web browser",
"playwright-browser_network_requests": "Get network requests from Playwright web browser",
// GitHub MCP server common tools
"github-mcp-server-get_file_contents": "Get file contents from GitHub",
"github-mcp-server-get_pull_request": "Get pull request from GitHub",
"github-mcp-server-get_issue": "Get issue from GitHub",
"github-mcp-server-get_pull_request_files": "Get pull request changed files from GitHub",
"github-mcp-server-list_pull_requests": "List pull requests on GitHub",
"github-mcp-server-list_branches": "List branches on GitHub",
"github-mcp-server-get_pull_request_diff": "Get pull request diff from GitHub",
"github-mcp-server-get_pull_request_comments": "Get pull request comments from GitHub",
"github-mcp-server-get_commit": "Get commit from GitHub",
"github-mcp-server-search_repositories": "Search repositories on GitHub",
"github-mcp-server-search_code": "Search code on GitHub",
"github-mcp-server-get_issue_comments": "Get issue comments from GitHub",
"github-mcp-server-list_issues": "List issues on GitHub",
"github-mcp-server-search_pull_requests": "Search pull requests on GitHub",
"github-mcp-server-list_commits": "List commits on GitHub",
"github-mcp-server-get_pull_request_status": "Get pull request status from GitHub",
"github-mcp-server-search_issues": "Search issues on GitHub",
"github-mcp-server-get_pull_request_reviews": "Get pull request reviews from GitHub",
"github-mcp-server-download_workflow_run_artifact": "Download GitHub Actions workflow run artifact",
"github-mcp-server-get_job_logs": "Get GitHub Actions job logs",
"github-mcp-server-get_workflow_run": "Get GitHub Actions workflow run",
"github-mcp-server-get_workflow_run_logs": "Get GitHub Actions workflow run logs",
"github-mcp-server-get_workflow_run_usage": "Get GitHub Actions workflow usage",
"github-mcp-server-list_workflow_jobs": "List GitHub Actions workflow jobs",
"github-mcp-server-list_workflow_run_artifacts": "List GitHub Actions workflow run artifacts",
"github-mcp-server-list_workflow_runs": "List GitHub Actions workflow runs",
"github-mcp-server-list_workflows": "List GitHub Actions workflows",
}
func renderGenericToolCall(w io.Writer, cs *iostreams.ColorScheme, name string) {
toolName, ok := genericToolCallNamesToTitles[name]
if !ok {
toolName = fmt.Sprintf("Call to %s", name)
}
renderToolCallTitle(w, cs, toolName, "")
}
type chatCompletionChunkEntry struct {
ID string `json:"id"`
Created int64 `json:"created"`
Model string `json:"model"`
Object string `json:"object"`
Choices []struct {
Delta struct {
ReasoningText string `json:"reasoning_text"`
Content string `json:"content"`
Role string `json:"role"`
ToolCalls []struct {
Function struct {
Name string `json:"name"`
Arguments string `json:"arguments"`
} `json:"function"`
Index int `json:"index"`
ID string `json:"id"`
} `json:"tool_calls"`
} `json:"delta"`
FinishReason string `json:"finish_reason"`
Index int `json:"index"`
} `json:"choices"`
}
type runSetupToolArgs struct {
Name string `json:"name"`
}
type bashToolArgs struct {
Command string `json:"command"`
Description string `json:"description"`
}
type readBashToolArgs struct {
SessionID string `json:"sessionId"`
}
type writeBashToolArgs struct {
SessionID string `json:"sessionId"`
Input string `json:"input"`
}
type stopBashToolArgs struct {
SessionID string `json:"sessionId"`
}
type asyncBashToolArgs struct {
Command string `json:"command"`
SessionID string `json:"sessionId"`
}
type readAsyncBashToolArgs struct {
SessionID string `json:"sessionId"`
}
type stopAsyncBashToolArgs struct {
SessionID string `json:"sessionId"`
}
type viewToolArgs struct {
Path string `json:"path"`
}
type thinkToolArgs struct {
SessionID string `json:"sessionId"`
Thought string `json:"thought"`
}
type reportProgressToolArgs struct {
CommitMessage string `json:"commitMessage"`
PrDescription string `json:"prDescription"`
}
type createToolArgs struct {
FileText string `json:"file_text"`
Path string `json:"path"`
}
type strReplaceToolArgs struct {
NewStr string `json:"new_str"`
OldStr string `json:"old_str"`
Path string `json:"path"`
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/agent-task/shared/display.go | pkg/cmd/agent-task/shared/display.go | package shared
import (
"github.com/cli/cli/v2/pkg/cmd/agent-task/capi"
"github.com/cli/cli/v2/pkg/iostreams"
)
// ColorFuncForSessionState returns a function that colors the session state
func ColorFuncForSessionState(s capi.Session, cs *iostreams.ColorScheme) func(string) string {
var stateColor func(string) string
switch s.State {
case "completed":
stateColor = cs.Green
case "cancelled":
stateColor = cs.Muted
case "in_progress", "queued":
stateColor = cs.Yellow
case "failed":
stateColor = cs.Red
default:
stateColor = cs.Muted
}
return stateColor
}
// SessionStateString returns the humane/capitalised form of the given session state.
func SessionStateString(state string) string {
switch state {
case "queued":
return "Queued"
case "in_progress":
return "In progress"
case "completed":
return "Ready for review"
case "failed":
return "Failed"
case "idle":
return "Idle"
case "waiting_for_user":
return "Waiting for user"
case "timed_out":
return "Timed out"
case "cancelled":
return "Cancelled"
default:
return state
}
}
type ColorFunc func(string) string
func SessionSymbol(cs *iostreams.ColorScheme, state string) string {
noColor := func(s string) string { return s }
switch state {
case "completed":
return cs.SuccessIconWithColor(noColor)
case "failed", "timed_out", "cancelled":
return cs.FailureIconWithColor(noColor)
default:
return "-"
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/agent-task/shared/log_mock.go | pkg/cmd/agent-task/shared/log_mock.go | // Code generated by moq; DO NOT EDIT.
// github.com/matryer/moq
package shared
import (
"github.com/cli/cli/v2/pkg/iostreams"
"io"
"sync"
)
// Ensure, that LogRendererMock does implement LogRenderer.
// If this is not the case, regenerate this file with moq.
var _ LogRenderer = &LogRendererMock{}
// LogRendererMock is a mock implementation of LogRenderer.
//
// func TestSomethingThatUsesLogRenderer(t *testing.T) {
//
// // make and configure a mocked LogRenderer
// mockedLogRenderer := &LogRendererMock{
// FollowFunc: func(fetcher func() ([]byte, error), w io.Writer, ioMoqParam *iostreams.IOStreams) error {
// panic("mock out the Follow method")
// },
// RenderFunc: func(logs []byte, w io.Writer, ioMoqParam *iostreams.IOStreams) (bool, error) {
// panic("mock out the Render method")
// },
// }
//
// // use mockedLogRenderer in code that requires LogRenderer
// // and then make assertions.
//
// }
type LogRendererMock struct {
// FollowFunc mocks the Follow method.
FollowFunc func(fetcher func() ([]byte, error), w io.Writer, ioMoqParam *iostreams.IOStreams) error
// RenderFunc mocks the Render method.
RenderFunc func(logs []byte, w io.Writer, ioMoqParam *iostreams.IOStreams) (bool, error)
// calls tracks calls to the methods.
calls struct {
// Follow holds details about calls to the Follow method.
Follow []struct {
// Fetcher is the fetcher argument value.
Fetcher func() ([]byte, error)
// W is the w argument value.
W io.Writer
// IoMoqParam is the ioMoqParam argument value.
IoMoqParam *iostreams.IOStreams
}
// Render holds details about calls to the Render method.
Render []struct {
// Logs is the logs argument value.
Logs []byte
// W is the w argument value.
W io.Writer
// IoMoqParam is the ioMoqParam argument value.
IoMoqParam *iostreams.IOStreams
}
}
lockFollow sync.RWMutex
lockRender sync.RWMutex
}
// Follow calls FollowFunc.
func (mock *LogRendererMock) Follow(fetcher func() ([]byte, error), w io.Writer, ioMoqParam *iostreams.IOStreams) error {
if mock.FollowFunc == nil {
panic("LogRendererMock.FollowFunc: method is nil but LogRenderer.Follow was just called")
}
callInfo := struct {
Fetcher func() ([]byte, error)
W io.Writer
IoMoqParam *iostreams.IOStreams
}{
Fetcher: fetcher,
W: w,
IoMoqParam: ioMoqParam,
}
mock.lockFollow.Lock()
mock.calls.Follow = append(mock.calls.Follow, callInfo)
mock.lockFollow.Unlock()
return mock.FollowFunc(fetcher, w, ioMoqParam)
}
// FollowCalls gets all the calls that were made to Follow.
// Check the length with:
//
// len(mockedLogRenderer.FollowCalls())
func (mock *LogRendererMock) FollowCalls() []struct {
Fetcher func() ([]byte, error)
W io.Writer
IoMoqParam *iostreams.IOStreams
} {
var calls []struct {
Fetcher func() ([]byte, error)
W io.Writer
IoMoqParam *iostreams.IOStreams
}
mock.lockFollow.RLock()
calls = mock.calls.Follow
mock.lockFollow.RUnlock()
return calls
}
// Render calls RenderFunc.
func (mock *LogRendererMock) Render(logs []byte, w io.Writer, ioMoqParam *iostreams.IOStreams) (bool, error) {
if mock.RenderFunc == nil {
panic("LogRendererMock.RenderFunc: method is nil but LogRenderer.Render was just called")
}
callInfo := struct {
Logs []byte
W io.Writer
IoMoqParam *iostreams.IOStreams
}{
Logs: logs,
W: w,
IoMoqParam: ioMoqParam,
}
mock.lockRender.Lock()
mock.calls.Render = append(mock.calls.Render, callInfo)
mock.lockRender.Unlock()
return mock.RenderFunc(logs, w, ioMoqParam)
}
// RenderCalls gets all the calls that were made to Render.
// Check the length with:
//
// len(mockedLogRenderer.RenderCalls())
func (mock *LogRendererMock) RenderCalls() []struct {
Logs []byte
W io.Writer
IoMoqParam *iostreams.IOStreams
} {
var calls []struct {
Logs []byte
W io.Writer
IoMoqParam *iostreams.IOStreams
}
mock.lockRender.RLock()
calls = mock.calls.Render
mock.lockRender.RUnlock()
return calls
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/browse/browse.go | pkg/cmd/browse/browse.go | package browse
import (
"context"
"fmt"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/browser"
"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/spf13/cobra"
)
const (
emptyCommitFlag = "last"
)
type BrowseOptions struct {
BaseRepo func() (ghrepo.Interface, error)
Browser browser.Browser
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
PathFromRepoRoot func() string
GitClient gitClient
SelectorArg string
Branch string
Commit string
ProjectsFlag bool
ReleasesFlag bool
SettingsFlag bool
WikiFlag bool
ActionsFlag bool
NoBrowserFlag bool
HasRepoOverride bool
}
func NewCmdBrowse(f *cmdutil.Factory, runF func(*BrowseOptions) error) *cobra.Command {
opts := &BrowseOptions{
Browser: f.Browser,
HttpClient: f.HttpClient,
IO: f.IOStreams,
PathFromRepoRoot: func() string {
return f.GitClient.PathFromRoot(context.Background())
},
GitClient: &localGitClient{client: f.GitClient},
}
cmd := &cobra.Command{
Short: "Open repositories, issues, pull requests, and more in the browser",
Long: heredoc.Doc(`
Transition from the terminal to the web browser to view and interact with:
- Issues
- Pull requests
- Repository content
- Repository home page
- Repository settings
`),
Use: "browse [<number> | <path> | <commit-sha>]",
Args: cobra.MaximumNArgs(1),
Example: heredoc.Doc(`
# Open the home page of the current repository
$ gh browse
# Open the script directory of the current repository
$ gh browse script/
# Open issue or pull request 217
$ gh browse 217
# Open commit page
$ gh browse 77507cd94ccafcf568f8560cfecde965fcfa63
# Open repository settings
$ gh browse --settings
# Open main.go at line 312
$ gh browse main.go:312
# Open main.go with the repository at head of bug-fix branch
$ gh browse main.go --branch bug-fix
# Open main.go with the repository at commit 775007cd
$ gh browse main.go --commit=77507cd94ccafcf568f8560cfecde965fcfa63
`),
Annotations: map[string]string{
"help:arguments": heredoc.Doc(`
A browser location can be specified using arguments in the following format:
- by number for issue or pull request, e.g. "123"; or
- by path for opening folders and files, e.g. "cmd/gh/main.go"; or
- by commit SHA
`),
"help:environment": heredoc.Doc(`
To configure a web browser other than the default, use the BROWSER environment variable.
`),
},
GroupID: "core",
RunE: func(cmd *cobra.Command, args []string) error {
opts.BaseRepo = f.BaseRepo
if len(args) > 0 {
opts.SelectorArg = args[0]
}
if err := cmdutil.MutuallyExclusive(
"arguments not supported when using `--projects`, `--releases`, `--settings`, `--actions` or `--wiki`",
opts.SelectorArg != "",
opts.ProjectsFlag,
opts.ReleasesFlag,
opts.SettingsFlag,
opts.WikiFlag,
opts.ActionsFlag,
); err != nil {
return err
}
if err := cmdutil.MutuallyExclusive(
"specify only one of `--branch`, `--commit`, `--projects`, `--releases`, `--settings`, `--actions` or `--wiki`",
opts.Branch != "",
opts.Commit != "",
opts.ProjectsFlag,
opts.ReleasesFlag,
opts.SettingsFlag,
opts.WikiFlag,
opts.ActionsFlag,
); err != nil {
return err
}
if (isNumber(opts.SelectorArg) || isCommit(opts.SelectorArg)) && (opts.Branch != "" || opts.Commit != "") {
return cmdutil.FlagErrorf("%q is an invalid argument when using `--branch` or `--commit`", opts.SelectorArg)
}
if cmd.Flags().Changed("repo") || os.Getenv("GH_REPO") != "" {
opts.GitClient = &remoteGitClient{opts.BaseRepo, opts.HttpClient}
opts.HasRepoOverride = true
}
if runF != nil {
return runF(opts)
}
return runBrowse(opts)
},
}
cmdutil.EnableRepoOverride(cmd, f)
cmd.Flags().BoolVarP(&opts.ProjectsFlag, "projects", "p", false, "Open repository projects")
cmd.Flags().BoolVarP(&opts.ReleasesFlag, "releases", "r", false, "Open repository releases")
cmd.Flags().BoolVarP(&opts.WikiFlag, "wiki", "w", false, "Open repository wiki")
cmd.Flags().BoolVarP(&opts.ActionsFlag, "actions", "a", false, "Open repository actions")
cmd.Flags().BoolVarP(&opts.SettingsFlag, "settings", "s", false, "Open repository settings")
cmd.Flags().BoolVarP(&opts.NoBrowserFlag, "no-browser", "n", false, "Print destination URL instead of opening the browser")
cmd.Flags().StringVarP(&opts.Commit, "commit", "c", "", "Select another commit by passing in the commit SHA, default is the last commit")
cmd.Flags().StringVarP(&opts.Branch, "branch", "b", "", "Select another branch by passing in the branch name")
_ = cmdutil.RegisterBranchCompletionFlags(f.GitClient, cmd, "branch")
// Preserve backwards compatibility for when commit flag used to be a boolean flag.
cmd.Flags().Lookup("commit").NoOptDefVal = emptyCommitFlag
return cmd
}
func runBrowse(opts *BrowseOptions) error {
baseRepo, err := opts.BaseRepo()
if err != nil {
return fmt.Errorf("unable to determine base repository: %w", err)
}
if opts.Commit != "" && opts.Commit == emptyCommitFlag {
commit, err := opts.GitClient.LastCommit()
if err != nil {
return err
}
opts.Commit = commit.Sha
}
section, err := parseSection(baseRepo, opts)
if err != nil {
return err
}
url := ghrepo.GenerateRepoURL(baseRepo, "%s", section)
if opts.NoBrowserFlag {
client, err := opts.HttpClient()
if err != nil {
return err
}
exist, err := api.RepoExists(api.NewClientFromHTTP(client), baseRepo)
if err != nil {
return err
}
if !exist {
return fmt.Errorf("%s doesn't exist", text.DisplayURL(url))
}
_, err = fmt.Fprintln(opts.IO.Out, url)
return err
}
if opts.IO.IsStdoutTTY() {
fmt.Fprintf(opts.IO.Out, "Opening %s in your browser.\n", text.DisplayURL(url))
}
return opts.Browser.Browse(url)
}
func parseSection(baseRepo ghrepo.Interface, opts *BrowseOptions) (string, error) {
if opts.ProjectsFlag {
return "projects", nil
} else if opts.ReleasesFlag {
return "releases", nil
} else if opts.SettingsFlag {
return "settings", nil
} else if opts.WikiFlag {
return "wiki", nil
} else if opts.ActionsFlag {
return "actions", nil
}
ref := opts.Branch
if opts.Commit != "" {
ref = opts.Commit
}
if ref == "" {
if opts.SelectorArg == "" {
return "", nil
}
if isNumber(opts.SelectorArg) {
return fmt.Sprintf("issues/%s", strings.TrimPrefix(opts.SelectorArg, "#")), nil
}
if isCommit(opts.SelectorArg) {
return fmt.Sprintf("commit/%s", opts.SelectorArg), nil
}
}
if ref == "" {
httpClient, err := opts.HttpClient()
if err != nil {
return "", err
}
apiClient := api.NewClientFromHTTP(httpClient)
ref, err = api.RepoDefaultBranch(apiClient, baseRepo)
if err != nil {
return "", fmt.Errorf("error determining the default branch: %w", err)
}
}
filePath, rangeStart, rangeEnd, err := parseFile(*opts, opts.SelectorArg)
if err != nil {
return "", err
}
if rangeStart > 0 {
var rangeFragment string
if rangeEnd > 0 && rangeStart != rangeEnd {
rangeFragment = fmt.Sprintf("L%d-L%d", rangeStart, rangeEnd)
} else {
rangeFragment = fmt.Sprintf("L%d", rangeStart)
}
return fmt.Sprintf("blob/%s/%s?plain=1#%s", escapePath(ref), escapePath(filePath), rangeFragment), nil
}
return strings.TrimSuffix(fmt.Sprintf("tree/%s/%s", escapePath(ref), escapePath(filePath)), "/"), nil
}
// escapePath URL-encodes special characters but leaves slashes unchanged
func escapePath(p string) string {
return strings.ReplaceAll(url.PathEscape(p), "%2F", "/")
}
func parseFile(opts BrowseOptions, f string) (p string, start int, end int, err error) {
if f == "" {
return
}
parts := strings.SplitN(f, ":", 3)
if len(parts) > 2 {
err = fmt.Errorf("invalid file argument: %q", f)
return
}
p = filepath.ToSlash(parts[0])
if !path.IsAbs(p) && !opts.HasRepoOverride {
p = path.Join(opts.PathFromRepoRoot(), p)
if p == "." || strings.HasPrefix(p, "..") {
p = ""
}
}
if len(parts) < 2 {
return
}
if idx := strings.IndexRune(parts[1], '-'); idx >= 0 {
start, err = strconv.Atoi(parts[1][:idx])
if err != nil {
err = fmt.Errorf("invalid file argument: %q", f)
return
}
end, err = strconv.Atoi(parts[1][idx+1:])
if err != nil {
err = fmt.Errorf("invalid file argument: %q", f)
}
return
}
start, err = strconv.Atoi(parts[1])
if err != nil {
err = fmt.Errorf("invalid file argument: %q", f)
}
end = start
return
}
func isNumber(arg string) bool {
_, err := strconv.Atoi(strings.TrimPrefix(arg, "#"))
return err == nil
}
// sha1 and sha256 are supported
var commitHash = regexp.MustCompile(`\A[a-f0-9]{7,64}\z`)
func isCommit(arg string) bool {
return commitHash.MatchString(arg)
}
// gitClient is used to implement functions that can be performed on both local and remote git repositories
type gitClient interface {
LastCommit() (*git.Commit, error)
}
type localGitClient struct {
client *git.Client
}
type remoteGitClient struct {
repo func() (ghrepo.Interface, error)
httpClient func() (*http.Client, error)
}
func (gc *localGitClient) LastCommit() (*git.Commit, error) {
return gc.client.LastCommit(context.Background())
}
func (gc *remoteGitClient) LastCommit() (*git.Commit, error) {
httpClient, err := gc.httpClient()
if err != nil {
return nil, err
}
repo, err := gc.repo()
if err != nil {
return nil, err
}
commit, err := api.LastCommit(api.NewClientFromHTTP(httpClient), repo)
if err != nil {
return nil, err
}
return &git.Commit{Sha: commit.OID}, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/browse/browse_test.go | pkg/cmd/browse/browse_test.go | package browse
import (
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"testing"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/browser"
"github.com/cli/cli/v2/internal/ghrepo"
"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 TestNewCmdBrowse(t *testing.T) {
tests := []struct {
name string
cli string
factory func(*cmdutil.Factory) *cmdutil.Factory
wants BrowseOptions
wantsErr bool
}{
{
name: "no arguments",
cli: "",
wantsErr: false,
},
{
name: "settings flag",
cli: "--settings",
wants: BrowseOptions{
SettingsFlag: true,
},
wantsErr: false,
},
{
name: "projects flag",
cli: "--projects",
wants: BrowseOptions{
ProjectsFlag: true,
},
wantsErr: false,
},
{
name: "releases flag",
cli: "--releases",
wants: BrowseOptions{
ReleasesFlag: true,
},
wantsErr: false,
},
{
name: "wiki flag",
cli: "--wiki",
wants: BrowseOptions{
WikiFlag: true,
},
wantsErr: false,
},
{
name: "actions flag",
cli: "--actions",
wants: BrowseOptions{
ActionsFlag: true,
},
wantsErr: false,
},
{
name: "no browser flag",
cli: "--no-browser",
wants: BrowseOptions{
NoBrowserFlag: true,
},
wantsErr: false,
},
{
name: "branch flag",
cli: "--branch main",
wants: BrowseOptions{
Branch: "main",
},
wantsErr: false,
},
{
name: "branch flag without a branch name",
cli: "--branch",
wantsErr: true,
},
{
name: "combination: settings projects",
cli: "--settings --projects",
wants: BrowseOptions{
SettingsFlag: true,
ProjectsFlag: true,
},
wantsErr: true,
},
{
name: "combination: projects wiki",
cli: "--projects --wiki",
wants: BrowseOptions{
ProjectsFlag: true,
WikiFlag: true,
},
wantsErr: true,
},
{
name: "combination: actions wiki",
cli: "--actions --wiki",
wants: BrowseOptions{
ActionsFlag: true,
WikiFlag: true,
},
wantsErr: true,
},
{
name: "passed argument",
cli: "main.go",
wants: BrowseOptions{
SelectorArg: "main.go",
},
wantsErr: false,
},
{
name: "passed two arguments",
cli: "main.go main.go",
wantsErr: true,
},
{
name: "passed argument and projects flag",
cli: "main.go --projects",
wantsErr: true,
},
{
name: "passed argument and releases flag",
cli: "main.go --releases",
wantsErr: true,
},
{
name: "passed argument and settings flag",
cli: "main.go --settings",
wantsErr: true,
},
{
name: "passed argument and wiki flag",
cli: "main.go --wiki",
wantsErr: true,
},
{
name: "passed argument and actions flag",
cli: "main.go --actions",
wantsErr: true,
},
{
name: "empty commit flag",
cli: "--commit",
wants: BrowseOptions{
Commit: emptyCommitFlag,
},
wantsErr: false,
},
{
name: "commit flag with a hash",
cli: "--commit=12a4",
wants: BrowseOptions{
Commit: "12a4",
},
wantsErr: false,
},
{
name: "commit flag with a hash and a file selector",
cli: "main.go --commit=12a4",
wants: BrowseOptions{
Commit: "12a4",
SelectorArg: "main.go",
},
wantsErr: false,
},
{
name: "passed both branch and commit flags",
cli: "main.go --branch main --commit=12a4",
wantsErr: true,
},
{
name: "passed both number arg and branch flag",
cli: "1 --branch trunk",
wantsErr: true,
},
{
name: "passed both number arg and commit flag",
cli: "1 --commit=12a4",
wantsErr: true,
},
{
name: "passed both commit SHA arg and branch flag",
cli: "de07febc26e19000f8c9e821207f3bc34a3c8038 --branch trunk",
wantsErr: true,
},
{
name: "passed both commit SHA arg and commit flag",
cli: "de07febc26e19000f8c9e821207f3bc34a3c8038 --commit=12a4",
wantsErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f := cmdutil.Factory{}
var opts *BrowseOptions
cmd := NewCmdBrowse(&f, func(o *BrowseOptions) error {
opts = o
return nil
})
argv, err := shlex.Split(tt.cli)
assert.NoError(t, err)
cmd.SetArgs(argv)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
_, err = cmd.ExecuteC()
if tt.wantsErr {
assert.Error(t, err)
return
} else {
assert.NoError(t, err)
}
assert.Equal(t, tt.wants.Branch, opts.Branch)
assert.Equal(t, tt.wants.SelectorArg, opts.SelectorArg)
assert.Equal(t, tt.wants.ProjectsFlag, opts.ProjectsFlag)
assert.Equal(t, tt.wants.ReleasesFlag, opts.ReleasesFlag)
assert.Equal(t, tt.wants.WikiFlag, opts.WikiFlag)
assert.Equal(t, tt.wants.NoBrowserFlag, opts.NoBrowserFlag)
assert.Equal(t, tt.wants.SettingsFlag, opts.SettingsFlag)
assert.Equal(t, tt.wants.ActionsFlag, opts.ActionsFlag)
assert.Equal(t, tt.wants.Commit, opts.Commit)
})
}
}
type testGitClient struct{}
func (gc *testGitClient) LastCommit() (*git.Commit, error) {
return &git.Commit{Sha: "6f1a2405cace1633d89a79c74c65f22fe78f9659"}, nil
}
func Test_runBrowse(t *testing.T) {
s := string(os.PathSeparator)
t.Setenv("GIT_DIR", "../../../git/fixtures/simple.git")
tests := []struct {
name string
opts BrowseOptions
httpStub func(*httpmock.Registry)
baseRepo ghrepo.Interface
defaultBranch string
expectedURL string
wantsErr bool
}{
{
name: "no arguments",
opts: BrowseOptions{
SelectorArg: "",
},
baseRepo: ghrepo.New("jlsestak", "cli"),
expectedURL: "https://github.com/jlsestak/cli",
},
{
name: "settings flag",
opts: BrowseOptions{
SettingsFlag: true,
},
baseRepo: ghrepo.New("bchadwic", "ObscuredByClouds"),
expectedURL: "https://github.com/bchadwic/ObscuredByClouds/settings",
},
{
name: "projects flag",
opts: BrowseOptions{
ProjectsFlag: true,
},
baseRepo: ghrepo.New("ttran112", "7ate9"),
expectedURL: "https://github.com/ttran112/7ate9/projects",
},
{
name: "releases flag",
opts: BrowseOptions{
ReleasesFlag: true,
},
baseRepo: ghrepo.New("ttran112", "7ate9"),
expectedURL: "https://github.com/ttran112/7ate9/releases",
},
{
name: "wiki flag",
opts: BrowseOptions{
WikiFlag: true,
},
baseRepo: ghrepo.New("ravocean", "ThreatLevelMidnight"),
expectedURL: "https://github.com/ravocean/ThreatLevelMidnight/wiki",
},
{
name: "actions flag",
opts: BrowseOptions{
ActionsFlag: true,
},
baseRepo: ghrepo.New("ravocean", "ThreatLevelMidnight"),
expectedURL: "https://github.com/ravocean/ThreatLevelMidnight/actions",
},
{
name: "file argument",
opts: BrowseOptions{SelectorArg: "path/to/file.txt"},
baseRepo: ghrepo.New("ken", "mrprofessor"),
defaultBranch: "main",
expectedURL: "https://github.com/ken/mrprofessor/tree/main/path/to/file.txt",
},
{
name: "issue argument",
opts: BrowseOptions{
SelectorArg: "217",
},
baseRepo: ghrepo.New("kevin", "MinTy"),
expectedURL: "https://github.com/kevin/MinTy/issues/217",
},
{
name: "issue with hashtag argument",
opts: BrowseOptions{
SelectorArg: "#217",
},
baseRepo: ghrepo.New("kevin", "MinTy"),
expectedURL: "https://github.com/kevin/MinTy/issues/217",
},
{
name: "branch flag",
opts: BrowseOptions{
Branch: "trunk",
},
baseRepo: ghrepo.New("jlsestak", "CouldNotThinkOfARepoName"),
expectedURL: "https://github.com/jlsestak/CouldNotThinkOfARepoName/tree/trunk",
},
{
name: "branch flag with file",
opts: BrowseOptions{
Branch: "trunk",
SelectorArg: "main.go",
},
baseRepo: ghrepo.New("bchadwic", "LedZeppelinIV"),
expectedURL: "https://github.com/bchadwic/LedZeppelinIV/tree/trunk/main.go",
},
{
name: "branch flag within dir",
opts: BrowseOptions{
Branch: "feature-123",
PathFromRepoRoot: func() string { return "pkg/dir" },
},
baseRepo: ghrepo.New("bstnc", "yeepers"),
expectedURL: "https://github.com/bstnc/yeepers/tree/feature-123",
},
{
name: "branch flag within dir with .",
opts: BrowseOptions{
Branch: "feature-123",
SelectorArg: ".",
PathFromRepoRoot: func() string { return "pkg/dir" },
},
baseRepo: ghrepo.New("bstnc", "yeepers"),
expectedURL: "https://github.com/bstnc/yeepers/tree/feature-123/pkg/dir",
},
{
name: "branch flag within dir with dir",
opts: BrowseOptions{
Branch: "feature-123",
SelectorArg: "inner/more",
PathFromRepoRoot: func() string { return "pkg/dir" },
},
baseRepo: ghrepo.New("bstnc", "yeepers"),
expectedURL: "https://github.com/bstnc/yeepers/tree/feature-123/pkg/dir/inner/more",
},
{
name: "file with line number",
opts: BrowseOptions{
SelectorArg: "path/to/file.txt:32",
},
baseRepo: ghrepo.New("ravocean", "angur"),
defaultBranch: "trunk",
expectedURL: "https://github.com/ravocean/angur/blob/trunk/path/to/file.txt?plain=1#L32",
},
{
name: "file with line range",
opts: BrowseOptions{
SelectorArg: "path/to/file.txt:32-40",
},
baseRepo: ghrepo.New("ravocean", "angur"),
defaultBranch: "trunk",
expectedURL: "https://github.com/ravocean/angur/blob/trunk/path/to/file.txt?plain=1#L32-L40",
},
{
name: "invalid default branch",
opts: BrowseOptions{
SelectorArg: "chocolate-pecan-pie.txt",
},
baseRepo: ghrepo.New("andrewhsu", "recipes"),
defaultBranch: "",
wantsErr: true,
},
{
name: "file with invalid line number after colon",
opts: BrowseOptions{
SelectorArg: "laptime-notes.txt:w-9",
},
baseRepo: ghrepo.New("andrewhsu", "sonoma-raceway"),
wantsErr: true,
},
{
name: "file with invalid file format",
opts: BrowseOptions{
SelectorArg: "path/to/file.txt:32:32",
},
baseRepo: ghrepo.New("ttran112", "ttrain211"),
wantsErr: true,
},
{
name: "file with invalid line number",
opts: BrowseOptions{
SelectorArg: "path/to/file.txt:32a",
},
baseRepo: ghrepo.New("ttran112", "ttrain211"),
wantsErr: true,
},
{
name: "file with invalid line range",
opts: BrowseOptions{
SelectorArg: "path/to/file.txt:32-abc",
},
baseRepo: ghrepo.New("ttran112", "ttrain211"),
wantsErr: true,
},
{
name: "branch with issue number",
opts: BrowseOptions{
SelectorArg: "217",
Branch: "trunk",
},
baseRepo: ghrepo.New("ken", "grc"),
wantsErr: false,
expectedURL: "https://github.com/ken/grc/tree/trunk/217",
},
{
name: "opening branch file with line number",
opts: BrowseOptions{
Branch: "first-browse-pull",
SelectorArg: "browse.go:32",
},
baseRepo: ghrepo.New("github", "ThankYouGitHub"),
wantsErr: false,
expectedURL: "https://github.com/github/ThankYouGitHub/blob/first-browse-pull/browse.go?plain=1#L32",
},
{
name: "no browser with branch file and line number",
opts: BrowseOptions{
Branch: "3-0-stable",
SelectorArg: "init.rb:6",
NoBrowserFlag: true,
},
httpStub: func(r *httpmock.Registry) {
r.Register(
httpmock.REST("HEAD", "repos/mislav/will_paginate"),
httpmock.StringResponse("{}"),
)
},
baseRepo: ghrepo.New("mislav", "will_paginate"),
wantsErr: false,
expectedURL: "https://github.com/mislav/will_paginate/blob/3-0-stable/init.rb?plain=1#L6",
},
{
name: "open last commit",
opts: BrowseOptions{
Commit: emptyCommitFlag,
GitClient: &testGitClient{},
},
baseRepo: ghrepo.New("vilmibm", "gh-user-status"),
wantsErr: false,
expectedURL: "https://github.com/vilmibm/gh-user-status/tree/6f1a2405cace1633d89a79c74c65f22fe78f9659",
},
{
name: "open last commit with a file",
opts: BrowseOptions{
Commit: emptyCommitFlag,
SelectorArg: "main.go",
GitClient: &testGitClient{},
},
baseRepo: ghrepo.New("vilmibm", "gh-user-status"),
wantsErr: false,
expectedURL: "https://github.com/vilmibm/gh-user-status/tree/6f1a2405cace1633d89a79c74c65f22fe78f9659/main.go",
},
{
name: "open number only commit hash",
opts: BrowseOptions{
Commit: "1234567890",
GitClient: &testGitClient{},
},
baseRepo: ghrepo.New("yanskun", "ILoveGitHub"),
wantsErr: false,
expectedURL: "https://github.com/yanskun/ILoveGitHub/tree/1234567890",
},
{
name: "open file with the repository state at a commit hash",
opts: BrowseOptions{
Commit: "12a4",
SelectorArg: "main.go",
GitClient: &testGitClient{},
},
baseRepo: ghrepo.New("yanskun", "ILoveGitHub"),
wantsErr: false,
expectedURL: "https://github.com/yanskun/ILoveGitHub/tree/12a4/main.go",
},
{
name: "relative path from browse_test.go",
opts: BrowseOptions{
SelectorArg: filepath.Join(".", "browse_test.go"),
PathFromRepoRoot: func() string {
return "pkg/cmd/browse/"
},
},
baseRepo: ghrepo.New("bchadwic", "gh-graph"),
defaultBranch: "trunk",
expectedURL: "https://github.com/bchadwic/gh-graph/tree/trunk/pkg/cmd/browse/browse_test.go",
wantsErr: false,
},
{
name: "relative path to file in parent folder from browse_test.go",
opts: BrowseOptions{
SelectorArg: ".." + s + "pr",
PathFromRepoRoot: func() string {
return "pkg/cmd/browse/"
},
},
baseRepo: ghrepo.New("bchadwic", "gh-graph"),
defaultBranch: "trunk",
expectedURL: "https://github.com/bchadwic/gh-graph/tree/trunk/pkg/cmd/pr",
wantsErr: false,
},
{
name: "does not use relative path when has repo override",
opts: BrowseOptions{
SelectorArg: "README.md",
HasRepoOverride: true,
PathFromRepoRoot: func() string {
return "pkg/cmd/browse/"
},
},
baseRepo: ghrepo.New("bchadwic", "gh-graph"),
defaultBranch: "trunk",
expectedURL: "https://github.com/bchadwic/gh-graph/tree/trunk/README.md",
wantsErr: false,
},
{
name: "use special characters in selector arg",
opts: BrowseOptions{
SelectorArg: "?=hello world/ *:23-44",
Branch: "branch/with spaces?",
},
baseRepo: ghrepo.New("bchadwic", "test"),
expectedURL: "https://github.com/bchadwic/test/blob/branch/with%20spaces%3F/%3F=hello%20world/%20%2A?plain=1#L23-L44",
wantsErr: false,
},
{
name: "commit hash in selector arg",
opts: BrowseOptions{
SelectorArg: "77507cd94ccafcf568f8560cfecde965fcfa63e7",
},
baseRepo: ghrepo.New("bchadwic", "test"),
expectedURL: "https://github.com/bchadwic/test/commit/77507cd94ccafcf568f8560cfecde965fcfa63e7",
wantsErr: false,
},
{
name: "short commit hash in selector arg",
opts: BrowseOptions{
SelectorArg: "6e3689d5",
},
baseRepo: ghrepo.New("bchadwic", "test"),
expectedURL: "https://github.com/bchadwic/test/commit/6e3689d5",
wantsErr: false,
},
{
name: "commit hash with extension",
opts: BrowseOptions{
SelectorArg: "77507cd94ccafcf568f8560cfecde965fcfa63e7.txt",
Branch: "trunk",
},
baseRepo: ghrepo.New("bchadwic", "test"),
expectedURL: "https://github.com/bchadwic/test/tree/trunk/77507cd94ccafcf568f8560cfecde965fcfa63e7.txt",
wantsErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, stdout, stderr := iostreams.Test()
browser := browser.Stub{}
reg := httpmock.Registry{}
defer reg.Verify(t)
if tt.defaultBranch != "" {
reg.StubRepoInfoResponse(tt.baseRepo.RepoOwner(), tt.baseRepo.RepoName(), tt.defaultBranch)
}
if tt.httpStub != nil {
tt.httpStub(®)
}
opts := tt.opts
opts.IO = ios
opts.BaseRepo = func() (ghrepo.Interface, error) {
return tt.baseRepo, nil
}
opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: ®}, nil
}
opts.Browser = &browser
if opts.PathFromRepoRoot == nil {
opts.PathFromRepoRoot = func() string { return "" }
}
err := runBrowse(&opts)
if tt.wantsErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}
if opts.NoBrowserFlag {
assert.Equal(t, fmt.Sprintf("%s\n", tt.expectedURL), stdout.String())
assert.Equal(t, "", stderr.String())
browser.Verify(t, "")
} else {
assert.Equal(t, "", stdout.String())
assert.Equal(t, "", stderr.String())
browser.Verify(t, tt.expectedURL)
}
})
}
}
func Test_parsePathFromFileArg(t *testing.T) {
tests := []struct {
name string
currentDir string
fileArg string
expectedPath string
}{
{
name: "empty paths",
currentDir: "",
fileArg: "",
expectedPath: "",
},
{
name: "root directory",
currentDir: "",
fileArg: ".",
expectedPath: "",
},
{
name: "relative path",
currentDir: "",
fileArg: filepath.FromSlash("foo/bar.py"),
expectedPath: "foo/bar.py",
},
{
name: "go to parent folder",
currentDir: "pkg/cmd/browse/",
fileArg: filepath.FromSlash("../"),
expectedPath: "pkg/cmd",
},
{
name: "current folder",
currentDir: "pkg/cmd/browse/",
fileArg: ".",
expectedPath: "pkg/cmd/browse",
},
{
name: "current folder (alternative)",
currentDir: "pkg/cmd/browse/",
fileArg: filepath.FromSlash("./"),
expectedPath: "pkg/cmd/browse",
},
{
name: "file that starts with '.'",
currentDir: "pkg/cmd/browse/",
fileArg: ".gitignore",
expectedPath: "pkg/cmd/browse/.gitignore",
},
{
name: "file in current folder",
currentDir: "pkg/cmd/browse/",
fileArg: filepath.Join(".", "browse.go"),
expectedPath: "pkg/cmd/browse/browse.go",
},
{
name: "file within parent folder",
currentDir: "pkg/cmd/browse/",
fileArg: filepath.Join("..", "browse.go"),
expectedPath: "pkg/cmd/browse.go",
},
{
name: "file within parent folder uncleaned",
currentDir: "pkg/cmd/browse/",
fileArg: filepath.FromSlash(".././//browse.go"),
expectedPath: "pkg/cmd/browse.go",
},
{
name: "different path from root directory",
currentDir: "pkg/cmd/browse/",
fileArg: filepath.Join("..", "..", "..", "internal/build/build.go"),
expectedPath: "internal/build/build.go",
},
{
name: "go out of repository",
currentDir: "pkg/cmd/browse/",
fileArg: filepath.FromSlash("../../../../../../"),
expectedPath: "",
},
{
name: "go to root of repository",
currentDir: "pkg/cmd/browse/",
fileArg: filepath.FromSlash("../../../"),
expectedPath: "",
},
{
name: "empty fileArg",
fileArg: "",
expectedPath: "",
},
}
for _, tt := range tests {
path, _, _, _ := parseFile(BrowseOptions{
PathFromRepoRoot: func() string {
return tt.currentDir
}}, tt.fileArg)
assert.Equal(t, tt.expectedPath, path, tt.name)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/secret/secret.go | pkg/cmd/secret/secret.go | package secret
import (
"github.com/MakeNowJust/heredoc"
cmdDelete "github.com/cli/cli/v2/pkg/cmd/secret/delete"
cmdList "github.com/cli/cli/v2/pkg/cmd/secret/list"
cmdSet "github.com/cli/cli/v2/pkg/cmd/secret/set"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/spf13/cobra"
)
func NewCmdSecret(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "secret <command>",
Short: "Manage GitHub secrets",
Long: heredoc.Docf(`
Secrets can be set at the repository, or organization level for use in
GitHub Actions or Dependabot. User, organization, and repository secrets can be set for
use in GitHub Codespaces. Environment secrets can be set for use in
GitHub Actions. Run %[1]sgh help secret set%[1]s to learn how to get started.
`, "`"),
}
cmdutil.EnableRepoOverride(cmd, f)
cmd.AddCommand(cmdList.NewCmdList(f, nil))
cmd.AddCommand(cmdSet.NewCmdSet(f, nil))
cmd.AddCommand(cmdDelete.NewCmdDelete(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/secret/delete/delete.go | pkg/cmd/secret/delete/delete.go | package delete
import (
"fmt"
"net/http"
"os"
"github.com/MakeNowJust/heredoc"
"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/cmd/secret/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type DeleteOptions struct {
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
Config func() (gh.Config, error)
BaseRepo func() (ghrepo.Interface, error)
SecretName string
OrgName string
EnvName string
UserSecrets bool
Application string
}
func NewCmdDelete(f *cmdutil.Factory, runF func(*DeleteOptions) error) *cobra.Command {
opts := &DeleteOptions{
IO: f.IOStreams,
Config: f.Config,
HttpClient: f.HttpClient,
}
cmd := &cobra.Command{
Use: "delete <secret-name>",
Short: "Delete secrets",
Long: heredoc.Doc(`
Delete a secret on one of the following levels:
- repository (default): available to GitHub Actions runs or Dependabot in a repository
- environment: available to GitHub Actions runs for a deployment environment in a repository
- organization: available to GitHub Actions runs, Dependabot, or Codespaces within an organization
- user: available to Codespaces for your user
`),
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
// If the user specified a repo directly, then we're using the OverrideBaseRepoFunc set by EnableRepoOverride
// So there's no reason to use the specialised BaseRepoFunc that requires remote disambiguation.
opts.BaseRepo = f.BaseRepo
isRepoUserProvided := cmd.Flags().Changed("repo") || os.Getenv("GH_REPO") != ""
if !isRepoUserProvided {
// If they haven't specified a repo directly, then we will wrap the BaseRepoFunc in one that errors if
// there might be multiple valid remotes.
opts.BaseRepo = shared.RequireNoAmbiguityBaseRepoFunc(opts.BaseRepo, f.Remotes)
// But if we are able to prompt, then we will wrap that up in a BaseRepoFunc that can prompt the user to
// resolve the ambiguity.
if opts.IO.CanPrompt() {
opts.BaseRepo = shared.PromptWhenAmbiguousBaseRepoFunc(opts.BaseRepo, f.IOStreams, f.Prompter)
}
}
if err := cmdutil.MutuallyExclusive("specify only one of `--org`, `--env`, or `--user`", opts.OrgName != "", opts.EnvName != "", opts.UserSecrets); err != nil {
return err
}
opts.SecretName = args[0]
if runF != nil {
return runF(opts)
}
return removeRun(opts)
},
Aliases: []string{
"remove",
},
}
cmd.Flags().StringVarP(&opts.OrgName, "org", "o", "", "Delete a secret for an organization")
cmd.Flags().StringVarP(&opts.EnvName, "env", "e", "", "Delete a secret for an environment")
cmd.Flags().BoolVarP(&opts.UserSecrets, "user", "u", false, "Delete a secret for your user")
cmdutil.StringEnumFlag(cmd, &opts.Application, "app", "a", "", []string{shared.Actions, shared.Codespaces, shared.Dependabot}, "Delete a secret for a specific application")
return cmd
}
func removeRun(opts *DeleteOptions) error {
c, err := opts.HttpClient()
if err != nil {
return fmt.Errorf("could not create http client: %w", err)
}
client := api.NewClientFromHTTP(c)
orgName := opts.OrgName
envName := opts.EnvName
secretEntity, err := shared.GetSecretEntity(orgName, envName, opts.UserSecrets)
if err != nil {
return err
}
var baseRepo ghrepo.Interface
if secretEntity == shared.Repository || secretEntity == shared.Environment {
baseRepo, err = opts.BaseRepo()
if err != nil {
return err
}
}
secretApp, err := shared.GetSecretApp(opts.Application, secretEntity)
if err != nil {
return err
}
if !shared.IsSupportedSecretEntity(secretApp, secretEntity) {
return fmt.Errorf("%s secrets are not supported for %s", secretEntity, secretApp)
}
cfg, err := opts.Config()
if err != nil {
return err
}
var path string
var host string
switch secretEntity {
case shared.Organization:
path = fmt.Sprintf("orgs/%s/%s/secrets/%s", orgName, secretApp, opts.SecretName)
host, _ = cfg.Authentication().DefaultHost()
case shared.Environment:
path = fmt.Sprintf("repos/%s/environments/%s/secrets/%s", ghrepo.FullName(baseRepo), envName, opts.SecretName)
host = baseRepo.RepoHost()
case shared.User:
path = fmt.Sprintf("user/codespaces/secrets/%s", opts.SecretName)
host, _ = cfg.Authentication().DefaultHost()
case shared.Repository:
path = fmt.Sprintf("repos/%s/%s/secrets/%s", ghrepo.FullName(baseRepo), secretApp, opts.SecretName)
host = baseRepo.RepoHost()
}
err = client.REST(host, "DELETE", path, nil, nil)
if err != nil {
return fmt.Errorf("failed to delete secret %s: %w", opts.SecretName, err)
}
if opts.IO.IsStdoutTTY() {
var target string
switch secretEntity {
case shared.Organization:
target = orgName
case shared.User:
target = "your user"
case shared.Repository, shared.Environment:
target = ghrepo.FullName(baseRepo)
}
cs := opts.IO.ColorScheme()
if envName != "" {
fmt.Fprintf(opts.IO.Out, "%s Deleted secret %s from %s environment on %s\n", cs.SuccessIconWithColor(cs.Red), opts.SecretName, envName, target)
} else {
fmt.Fprintf(opts.IO.Out, "%s Deleted %s secret %s from %s\n", cs.SuccessIconWithColor(cs.Red), secretApp.Title(), opts.SecretName, target)
}
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/secret/delete/delete_test.go | pkg/cmd/secret/delete/delete_test.go | package delete
import (
"bytes"
"io"
"net/http"
"testing"
ghContext "github.com/cli/cli/v2/context"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/config"
"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/cmd/secret/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"
"github.com/stretchr/testify/require"
)
func TestNewCmdDelete(t *testing.T) {
tests := []struct {
name string
cli string
wants DeleteOptions
wantsErr bool
}{
{
name: "no args",
wantsErr: true,
},
{
name: "repo",
cli: "cool",
wants: DeleteOptions{
SecretName: "cool",
},
},
{
name: "org",
cli: "cool --org anOrg",
wants: DeleteOptions{
SecretName: "cool",
OrgName: "anOrg",
},
},
{
name: "env",
cli: "cool --env anEnv",
wants: DeleteOptions{
SecretName: "cool",
EnvName: "anEnv",
},
},
{
name: "user",
cli: "cool -u",
wants: DeleteOptions{
SecretName: "cool",
UserSecrets: true,
},
},
{
name: "Dependabot repo",
cli: "cool --app Dependabot",
wants: DeleteOptions{
SecretName: "cool",
Application: "Dependabot",
},
},
{
name: "Dependabot org",
cli: "cool --app Dependabot --org UmbrellaCorporation",
wants: DeleteOptions{
SecretName: "cool",
OrgName: "UmbrellaCorporation",
Application: "Dependabot",
},
},
{
name: "Codespaces org",
cli: "cool --app codespaces --org UmbrellaCorporation",
wants: DeleteOptions{
SecretName: "cool",
OrgName: "UmbrellaCorporation",
Application: "Codespaces",
},
},
}
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 *DeleteOptions
cmd := NewCmdDelete(f, func(opts *DeleteOptions) 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.wantsErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.wants.SecretName, gotOpts.SecretName)
assert.Equal(t, tt.wants.OrgName, gotOpts.OrgName)
assert.Equal(t, tt.wants.EnvName, gotOpts.EnvName)
})
}
}
func TestNewCmdDeleteBaseRepoFuncs(t *testing.T) {
multipleRemotes := ghContext.Remotes{
&ghContext.Remote{
Remote: &git.Remote{
Name: "origin",
},
Repo: ghrepo.New("owner", "fork"),
},
&ghContext.Remote{
Remote: &git.Remote{
Name: "upstream",
},
Repo: ghrepo.New("owner", "repo"),
},
}
singleRemote := ghContext.Remotes{
&ghContext.Remote{
Remote: &git.Remote{
Name: "origin",
},
Repo: ghrepo.New("owner", "repo"),
},
}
tests := []struct {
name string
args string
env map[string]string
remotes ghContext.Remotes
prompterStubs func(*prompter.MockPrompter)
wantRepo ghrepo.Interface
wantErr error
}{
{
name: "when there is a repo flag provided, the factory base repo func is used",
args: "SECRET_NAME --repo owner/repo",
remotes: multipleRemotes,
wantRepo: ghrepo.New("owner", "repo"),
},
{
name: "when GH_REPO env var is provided, the factory base repo func is used",
args: "SECRET_NAME",
env: map[string]string{
"GH_REPO": "owner/repo",
},
remotes: multipleRemotes,
wantRepo: ghrepo.New("owner", "repo"),
},
{
name: "when there is no repo flag or GH_REPO env var provided, and no prompting, the base func requiring no ambiguity is used",
args: "SECRET_NAME",
remotes: multipleRemotes,
wantErr: shared.AmbiguousBaseRepoError{
Remotes: multipleRemotes,
},
},
{
name: "when there is no repo flag or GH_REPO env provided, and there is a single remote, the factory base repo func is used",
args: "SECRET_NAME",
remotes: singleRemote,
wantRepo: ghrepo.New("owner", "repo"),
},
{
name: "when there is no repo flag or GH_REPO env var provided, and can prompt, the base func resolving ambiguity is used",
args: "SECRET_NAME",
remotes: multipleRemotes,
prompterStubs: func(pm *prompter.MockPrompter) {
pm.RegisterSelect(
"Select a repo",
[]string{"owner/fork", "owner/repo"},
func(_, _ string, opts []string) (int, error) {
return prompter.IndexFor(opts, "owner/fork")
},
)
},
wantRepo: ghrepo.New("owner", "fork"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
var pm *prompter.MockPrompter
if tt.prompterStubs != nil {
ios.SetStdinTTY(true)
ios.SetStdoutTTY(true)
ios.SetStderrTTY(true)
pm = prompter.NewMockPrompter(t)
tt.prompterStubs(pm)
}
f := &cmdutil.Factory{
IOStreams: ios,
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("owner/repo")
},
Prompter: pm,
Remotes: func() (ghContext.Remotes, error) {
return tt.remotes, nil
},
}
for k, v := range tt.env {
t.Setenv(k, v)
}
argv, err := shlex.Split(tt.args)
assert.NoError(t, err)
var gotOpts *DeleteOptions
cmd := NewCmdDelete(f, func(opts *DeleteOptions) error {
gotOpts = opts
return nil
})
// Require to support --repo flag
cmdutil.EnableRepoOverride(cmd, f)
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
_, err = cmd.ExecuteC()
require.NoError(t, err)
baseRepo, err := gotOpts.BaseRepo()
if tt.wantErr != nil {
require.Equal(t, tt.wantErr, err)
return
}
require.True(t, ghrepo.IsSame(tt.wantRepo, baseRepo))
})
}
}
func Test_removeRun_repo(t *testing.T) {
tests := []struct {
name string
opts *DeleteOptions
host string
httpStubs func(*httpmock.Registry)
}{
{
name: "Actions",
opts: &DeleteOptions{
Application: "actions",
SecretName: "cool_secret",
},
host: "github.com",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.WithHost(httpmock.REST("DELETE", "repos/owner/repo/actions/secrets/cool_secret"), "api.github.com"), httpmock.StatusStringResponse(204, "No Content"))
},
},
{
name: "Actions GHES",
opts: &DeleteOptions{
Application: "actions",
SecretName: "cool_secret",
},
host: "example.com",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.WithHost(httpmock.REST("DELETE", "api/v3/repos/owner/repo/actions/secrets/cool_secret"), "example.com"), httpmock.StatusStringResponse(204, "No Content"))
},
},
{
name: "Dependabot",
opts: &DeleteOptions{
Application: "dependabot",
SecretName: "cool_dependabot_secret",
},
host: "github.com",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.WithHost(httpmock.REST("DELETE", "repos/owner/repo/dependabot/secrets/cool_dependabot_secret"), "api.github.com"), httpmock.StatusStringResponse(204, "No Content"))
},
},
{
name: "Dependabot GHES",
opts: &DeleteOptions{
Application: "dependabot",
SecretName: "cool_dependabot_secret",
},
host: "example.com",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.WithHost(httpmock.REST("DELETE", "api/v3/repos/owner/repo/dependabot/secrets/cool_dependabot_secret"), "example.com"), httpmock.StatusStringResponse(204, "No Content"))
},
},
{
name: "defaults to Actions",
opts: &DeleteOptions{
SecretName: "cool_secret",
},
host: "github.com",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.WithHost(httpmock.REST("DELETE", "repos/owner/repo/actions/secrets/cool_secret"), "api.github.com"), httpmock.StatusStringResponse(204, "No Content"))
},
},
}
for _, tt := range tests {
reg := &httpmock.Registry{}
tt.httpStubs(reg)
defer reg.Verify(t)
ios, _, _, _ := iostreams.Test()
tt.opts.IO = ios
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
tt.opts.Config = func() (gh.Config, error) {
return config.NewBlankConfig(), nil
}
tt.opts.BaseRepo = func() (ghrepo.Interface, error) {
return ghrepo.FromFullNameWithHost("owner/repo", tt.host)
}
err := removeRun(tt.opts)
assert.NoError(t, err)
}
}
func Test_removeRun_env(t *testing.T) {
tests := []struct {
name string
opts *DeleteOptions
host string
httpStubs func(*httpmock.Registry)
}{
{
name: "delete environment secret",
opts: &DeleteOptions{
SecretName: "cool_secret",
EnvName: "development",
},
host: "github.com",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.WithHost(httpmock.REST("DELETE", "repos/owner/repo/environments/development/secrets/cool_secret"), "api.github.com"),
httpmock.StatusStringResponse(204, "No Content"))
},
},
{
name: "delete environment secret GHES",
opts: &DeleteOptions{
SecretName: "cool_secret",
EnvName: "development",
},
host: "example.com",
httpStubs: func(reg *httpmock.Registry) {
reg.Register(httpmock.WithHost(httpmock.REST("DELETE", "api/v3/repos/owner/repo/environments/development/secrets/cool_secret"), "example.com"),
httpmock.StatusStringResponse(204, "No Content"))
},
},
}
for _, tt := range tests {
reg := &httpmock.Registry{}
tt.httpStubs(reg)
defer reg.Verify(t)
ios, _, _, _ := iostreams.Test()
tt.opts.IO = ios
tt.opts.BaseRepo = func() (ghrepo.Interface, error) {
if tt.host != "" {
return ghrepo.FromFullNameWithHost("owner/repo", tt.host)
}
return ghrepo.FromFullName("owner/repo")
}
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
tt.opts.Config = func() (gh.Config, error) {
return config.NewBlankConfig(), nil
}
err := removeRun(tt.opts)
require.NoError(t, err)
}
}
func Test_removeRun_org(t *testing.T) {
tests := []struct {
name string
opts *DeleteOptions
wantPath string
}{
{
name: "org",
opts: &DeleteOptions{
OrgName: "UmbrellaCorporation",
},
wantPath: "orgs/UmbrellaCorporation/actions/secrets/tVirus",
},
{
name: "Dependabot org",
opts: &DeleteOptions{
Application: "dependabot",
OrgName: "UmbrellaCorporation",
},
wantPath: "orgs/UmbrellaCorporation/dependabot/secrets/tVirus",
},
{
name: "Codespaces org",
opts: &DeleteOptions{
Application: "codespaces",
OrgName: "UmbrellaCorporation",
},
wantPath: "orgs/UmbrellaCorporation/codespaces/secrets/tVirus",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
reg.Register(
httpmock.REST("DELETE", tt.wantPath),
httpmock.StatusStringResponse(204, "No Content"))
ios, _, _, _ := iostreams.Test()
tt.opts.Config = func() (gh.Config, error) {
return config.NewBlankConfig(), nil
}
tt.opts.BaseRepo = func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("owner/repo")
}
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
tt.opts.IO = ios
tt.opts.SecretName = "tVirus"
err := removeRun(tt.opts)
assert.NoError(t, err)
reg.Verify(t)
})
}
}
func Test_removeRun_user(t *testing.T) {
reg := &httpmock.Registry{}
reg.Register(
httpmock.REST("DELETE", "user/codespaces/secrets/cool_secret"),
httpmock.StatusStringResponse(204, "No Content"))
ios, _, _, _ := iostreams.Test()
opts := &DeleteOptions{
IO: ios,
HttpClient: func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
},
Config: func() (gh.Config, error) {
return config.NewBlankConfig(), nil
},
SecretName: "cool_secret",
UserSecrets: true,
}
err := removeRun(opts)
assert.NoError(t, err)
reg.Verify(t)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/secret/list/list_test.go | pkg/cmd/secret/list/list_test.go | package list
import (
"bytes"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"testing"
"time"
ghContext "github.com/cli/cli/v2/context"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/config"
"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/cmd/secret/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"
"github.com/stretchr/testify/require"
)
func Test_NewCmdList(t *testing.T) {
tests := []struct {
name string
cli string
wants ListOptions
}{
{
name: "repo",
cli: "",
wants: ListOptions{
OrgName: "",
},
},
{
name: "org",
cli: "-oUmbrellaCorporation",
wants: ListOptions{
OrgName: "UmbrellaCorporation",
},
},
{
name: "env",
cli: "-eDevelopment",
wants: ListOptions{
EnvName: "Development",
},
},
{
name: "user",
cli: "-u",
wants: ListOptions{
UserSecrets: true,
},
},
{
name: "Dependabot repo",
cli: "--app Dependabot",
wants: ListOptions{
Application: "Dependabot",
},
},
{
name: "Dependabot org",
cli: "--app Dependabot --org UmbrellaCorporation",
wants: ListOptions{
Application: "Dependabot",
OrgName: "UmbrellaCorporation",
},
},
}
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 *ListOptions
cmd := NewCmdList(f, func(opts *ListOptions) error {
gotOpts = opts
return nil
})
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
_, err = cmd.ExecuteC()
assert.NoError(t, err)
assert.Equal(t, tt.wants.OrgName, gotOpts.OrgName)
assert.Equal(t, tt.wants.EnvName, gotOpts.EnvName)
})
}
}
func TestNewCmdListBaseRepoFuncs(t *testing.T) {
multipleRemotes := ghContext.Remotes{
&ghContext.Remote{
Remote: &git.Remote{
Name: "origin",
},
Repo: ghrepo.New("owner", "fork"),
},
&ghContext.Remote{
Remote: &git.Remote{
Name: "upstream",
},
Repo: ghrepo.New("owner", "repo"),
},
}
singleRemote := ghContext.Remotes{
&ghContext.Remote{
Remote: &git.Remote{
Name: "origin",
},
Repo: ghrepo.New("owner", "repo"),
},
}
tests := []struct {
name string
args string
env map[string]string
remotes ghContext.Remotes
prompterStubs func(*prompter.MockPrompter)
wantRepo ghrepo.Interface
wantErr error
}{
{
name: "when there is a repo flag provided, the factory base repo func is used",
args: "--repo owner/repo",
remotes: multipleRemotes,
wantRepo: ghrepo.New("owner", "repo"),
},
{
name: "when GH_REPO env var is provided, the factory base repo func is used",
env: map[string]string{
"GH_REPO": "owner/repo",
},
remotes: multipleRemotes,
wantRepo: ghrepo.New("owner", "repo"),
},
{
name: "when there is no repo flag or GH_REPO env var provided, and no prompting, the base func requiring no ambiguity is used",
args: "",
remotes: multipleRemotes,
wantErr: shared.AmbiguousBaseRepoError{
Remotes: multipleRemotes,
},
},
{
name: "when there is no repo flag or GH_REPO env provided, and there is a single remote, the factory base repo func is used",
args: "",
remotes: singleRemote,
wantRepo: ghrepo.New("owner", "repo"),
},
{
name: "when there is no repo flag or GH_REPO env var provided, and can prompt, the base func resolving ambiguity is used",
args: "",
remotes: multipleRemotes,
prompterStubs: func(pm *prompter.MockPrompter) {
pm.RegisterSelect(
"Select a repo",
[]string{"owner/fork", "owner/repo"},
func(_, _ string, opts []string) (int, error) {
return prompter.IndexFor(opts, "owner/fork")
},
)
},
wantRepo: ghrepo.New("owner", "fork"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
var pm *prompter.MockPrompter
if tt.prompterStubs != nil {
ios.SetStdinTTY(true)
ios.SetStdoutTTY(true)
ios.SetStderrTTY(true)
pm = prompter.NewMockPrompter(t)
tt.prompterStubs(pm)
}
f := &cmdutil.Factory{
IOStreams: ios,
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("owner/repo")
},
Prompter: pm,
Remotes: func() (ghContext.Remotes, error) {
return tt.remotes, nil
},
}
for k, v := range tt.env {
t.Setenv(k, v)
}
argv, err := shlex.Split(tt.args)
assert.NoError(t, err)
var gotOpts *ListOptions
cmd := NewCmdList(f, func(opts *ListOptions) error {
gotOpts = opts
return nil
})
// Require to support --repo flag
cmdutil.EnableRepoOverride(cmd, f)
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
_, err = cmd.ExecuteC()
require.NoError(t, err)
baseRepo, err := gotOpts.BaseRepo()
if tt.wantErr != nil {
require.Equal(t, tt.wantErr, err)
return
}
require.True(t, ghrepo.IsSame(tt.wantRepo, baseRepo))
})
}
}
func Test_listRun(t *testing.T) {
tests := []struct {
name string
tty bool
json bool
opts *ListOptions
wantOut []string
}{
{
name: "repo tty",
tty: true,
opts: &ListOptions{},
wantOut: []string{
"NAME UPDATED",
"SECRET_ONE about 34 years ago",
"SECRET_TWO about 2 years ago",
"SECRET_THREE about 47 years ago",
},
},
{
name: "repo not tty",
tty: false,
opts: &ListOptions{},
wantOut: []string{
"SECRET_ONE\t1988-10-11T00:00:00Z",
"SECRET_TWO\t2020-12-04T00:00:00Z",
"SECRET_THREE\t1975-11-30T00:00:00Z",
},
},
{
name: "org tty",
tty: true,
opts: &ListOptions{
OrgName: "UmbrellaCorporation",
},
wantOut: []string{
"NAME UPDATED VISIBILITY",
"SECRET_ONE about 34 years ago Visible to all repositories",
"SECRET_TWO about 2 years ago Visible to private repositories",
"SECRET_THREE about 47 years ago Visible to 2 selected repositories",
},
},
{
name: "org not tty",
tty: false,
opts: &ListOptions{
OrgName: "UmbrellaCorporation",
},
wantOut: []string{
"SECRET_ONE\t1988-10-11T00:00:00Z\tALL",
"SECRET_TWO\t2020-12-04T00:00:00Z\tPRIVATE",
"SECRET_THREE\t1975-11-30T00:00:00Z\tSELECTED",
},
},
{
name: "org tty, json",
tty: true,
json: true,
opts: &ListOptions{
OrgName: "UmbrellaCorporation",
},
wantOut: []string{
// Note the `"numSelectedRepos":2` pair in the last entry.
`[{"name":"SECRET_ONE","numSelectedRepos":0,"selectedReposURL":"","updatedAt":"1988-10-11T00:00:00Z","visibility":"all"},{"name":"SECRET_TWO","numSelectedRepos":0,"selectedReposURL":"","updatedAt":"2020-12-04T00:00:00Z","visibility":"private"},{"name":"SECRET_THREE","numSelectedRepos":2,"selectedReposURL":"https://api.github.com/orgs/UmbrellaCorporation/actions/secrets/SECRET_THREE/repositories","updatedAt":"1975-11-30T00:00:00Z","visibility":"selected"}]`,
},
},
{
name: "org not tty, json",
tty: false,
json: true,
opts: &ListOptions{
OrgName: "UmbrellaCorporation",
},
wantOut: []string{
// Note the `"numSelectedRepos":2` pair in the last entry.
`[{"name":"SECRET_ONE","numSelectedRepos":0,"selectedReposURL":"","updatedAt":"1988-10-11T00:00:00Z","visibility":"all"},{"name":"SECRET_TWO","numSelectedRepos":0,"selectedReposURL":"","updatedAt":"2020-12-04T00:00:00Z","visibility":"private"},{"name":"SECRET_THREE","numSelectedRepos":2,"selectedReposURL":"https://api.github.com/orgs/UmbrellaCorporation/actions/secrets/SECRET_THREE/repositories","updatedAt":"1975-11-30T00:00:00Z","visibility":"selected"}]`,
},
},
{
name: "env tty",
tty: true,
opts: &ListOptions{
EnvName: "Development",
},
wantOut: []string{
"NAME UPDATED",
"SECRET_ONE about 34 years ago",
"SECRET_TWO about 2 years ago",
"SECRET_THREE about 47 years ago",
},
},
{
name: "env not tty",
tty: false,
opts: &ListOptions{
EnvName: "Development",
},
wantOut: []string{
"SECRET_ONE\t1988-10-11T00:00:00Z",
"SECRET_TWO\t2020-12-04T00:00:00Z",
"SECRET_THREE\t1975-11-30T00:00:00Z",
},
},
{
name: "user tty",
tty: true,
opts: &ListOptions{
UserSecrets: true,
},
wantOut: []string{
"NAME UPDATED VISIBILITY",
"SECRET_ONE about 34 years ago Visible to 1 selected repository",
"SECRET_TWO about 2 years ago Visible to 2 selected repositories",
"SECRET_THREE about 47 years ago Visible to 3 selected repositories",
},
},
{
name: "user not tty",
tty: false,
opts: &ListOptions{
UserSecrets: true,
},
wantOut: []string{
"SECRET_ONE\t1988-10-11T00:00:00Z\tSELECTED",
"SECRET_TWO\t2020-12-04T00:00:00Z\tSELECTED",
"SECRET_THREE\t1975-11-30T00:00:00Z\tSELECTED",
},
},
{
name: "user tty, json",
tty: true,
json: true,
opts: &ListOptions{
UserSecrets: true,
},
wantOut: []string{
// Note that `numSelectedRepos` fields are not set to default (zero).
`[{"name":"SECRET_ONE","numSelectedRepos":1,"selectedReposURL":"https://api.github.com/user/codespaces/secrets/SECRET_ONE/repositories","updatedAt":"1988-10-11T00:00:00Z","visibility":"selected"},{"name":"SECRET_TWO","numSelectedRepos":2,"selectedReposURL":"https://api.github.com/user/codespaces/secrets/SECRET_TWO/repositories","updatedAt":"2020-12-04T00:00:00Z","visibility":"selected"},{"name":"SECRET_THREE","numSelectedRepos":3,"selectedReposURL":"https://api.github.com/user/codespaces/secrets/SECRET_THREE/repositories","updatedAt":"1975-11-30T00:00:00Z","visibility":"selected"}]`,
},
},
{
name: "user not tty, json",
tty: false,
json: true,
opts: &ListOptions{
UserSecrets: true,
},
wantOut: []string{
// Note that `numSelectedRepos` fields are not set to default (zero).
`[{"name":"SECRET_ONE","numSelectedRepos":1,"selectedReposURL":"https://api.github.com/user/codespaces/secrets/SECRET_ONE/repositories","updatedAt":"1988-10-11T00:00:00Z","visibility":"selected"},{"name":"SECRET_TWO","numSelectedRepos":2,"selectedReposURL":"https://api.github.com/user/codespaces/secrets/SECRET_TWO/repositories","updatedAt":"2020-12-04T00:00:00Z","visibility":"selected"},{"name":"SECRET_THREE","numSelectedRepos":3,"selectedReposURL":"https://api.github.com/user/codespaces/secrets/SECRET_THREE/repositories","updatedAt":"1975-11-30T00:00:00Z","visibility":"selected"}]`,
},
},
{
name: "Dependabot repo tty",
tty: true,
opts: &ListOptions{
Application: "Dependabot",
},
wantOut: []string{
"NAME UPDATED",
"SECRET_ONE about 34 years ago",
"SECRET_TWO about 2 years ago",
"SECRET_THREE about 47 years ago",
},
},
{
name: "Dependabot repo not tty",
tty: false,
opts: &ListOptions{
Application: "Dependabot",
},
wantOut: []string{
"SECRET_ONE\t1988-10-11T00:00:00Z",
"SECRET_TWO\t2020-12-04T00:00:00Z",
"SECRET_THREE\t1975-11-30T00:00:00Z",
},
},
{
name: "Dependabot org tty",
tty: true,
opts: &ListOptions{
Application: "Dependabot",
OrgName: "UmbrellaCorporation",
},
wantOut: []string{
"NAME UPDATED VISIBILITY",
"SECRET_ONE about 34 years ago Visible to all repositories",
"SECRET_TWO about 2 years ago Visible to private repositories",
"SECRET_THREE about 47 years ago Visible to 2 selected repositories",
},
},
{
name: "Dependabot org not tty",
tty: false,
opts: &ListOptions{
Application: "Dependabot",
OrgName: "UmbrellaCorporation",
},
wantOut: []string{
"SECRET_ONE\t1988-10-11T00:00:00Z\tALL",
"SECRET_TWO\t2020-12-04T00:00:00Z\tPRIVATE",
"SECRET_THREE\t1975-11-30T00:00:00Z\tSELECTED",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
reg.Verify(t)
path := "repos/owner/repo/actions/secrets"
if tt.opts.EnvName != "" {
path = fmt.Sprintf("repos/owner/repo/environments/%s/secrets", tt.opts.EnvName)
} else if tt.opts.OrgName != "" {
path = fmt.Sprintf("orgs/%s/actions/secrets", tt.opts.OrgName)
}
t0, _ := time.Parse("2006-01-02", "1988-10-11")
t1, _ := time.Parse("2006-01-02", "2020-12-04")
t2, _ := time.Parse("2006-01-02", "1975-11-30")
payload := struct {
Secrets []Secret
}{
Secrets: []Secret{
{
Name: "SECRET_ONE",
UpdatedAt: t0,
},
{
Name: "SECRET_TWO",
UpdatedAt: t1,
},
{
Name: "SECRET_THREE",
UpdatedAt: t2,
},
},
}
if tt.opts.OrgName != "" {
payload.Secrets = []Secret{
{
Name: "SECRET_ONE",
UpdatedAt: t0,
Visibility: shared.All,
},
{
Name: "SECRET_TWO",
UpdatedAt: t1,
Visibility: shared.Private,
},
{
Name: "SECRET_THREE",
UpdatedAt: t2,
Visibility: shared.Selected,
SelectedReposURL: fmt.Sprintf("https://api.github.com/orgs/%s/actions/secrets/SECRET_THREE/repositories", tt.opts.OrgName),
},
}
reg.Register(
httpmock.REST("GET", fmt.Sprintf("orgs/%s/actions/secrets/SECRET_THREE/repositories", tt.opts.OrgName)),
httpmock.JSONResponse(struct {
TotalCount int `json:"total_count"`
}{2}))
}
if tt.opts.UserSecrets {
payload.Secrets = []Secret{
{
Name: "SECRET_ONE",
UpdatedAt: t0,
Visibility: shared.Selected,
SelectedReposURL: "https://api.github.com/user/codespaces/secrets/SECRET_ONE/repositories",
},
{
Name: "SECRET_TWO",
UpdatedAt: t1,
Visibility: shared.Selected,
SelectedReposURL: "https://api.github.com/user/codespaces/secrets/SECRET_TWO/repositories",
},
{
Name: "SECRET_THREE",
UpdatedAt: t2,
Visibility: shared.Selected,
SelectedReposURL: "https://api.github.com/user/codespaces/secrets/SECRET_THREE/repositories",
},
}
path = "user/codespaces/secrets"
for i, secret := range payload.Secrets {
hostLen := len("https://api.github.com/")
path := secret.SelectedReposURL[hostLen:len(secret.SelectedReposURL)]
repositoryCount := i + 1
reg.Register(
httpmock.REST("GET", path),
httpmock.JSONResponse(struct {
TotalCount int `json:"total_count"`
}{repositoryCount}))
}
}
if tt.opts.Application == "Dependabot" {
path = strings.Replace(path, "actions", "dependabot", 1)
}
reg.Register(httpmock.REST("GET", path), httpmock.JSONResponse(payload))
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(tt.tty)
tt.opts.IO = ios
tt.opts.BaseRepo = func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("owner/repo")
}
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
tt.opts.Config = func() (gh.Config, error) {
return config.NewBlankConfig(), nil
}
tt.opts.Now = func() time.Time {
t, _ := time.Parse(time.RFC822, "15 Mar 23 00:00 UTC")
return t
}
if tt.json {
exporter := cmdutil.NewJSONExporter()
exporter.SetFields(secretFields)
tt.opts.Exporter = exporter
}
err := listRun(tt.opts)
assert.NoError(t, err)
expected := fmt.Sprintf("%s\n", strings.Join(tt.wantOut, "\n"))
assert.Equal(t, expected, stdout.String())
})
}
}
// Test_listRun_populatesNumSelectedReposIfRequired asserts that NumSelectedRepos
// field is populated **only** when it's going to be presented in the output. Since
// populating this field costs further API requests (one per secret), it's important
// to avoid extra calls when the output will not present the field's value. Note
// that NumSelectedRepos is only meant for user or organization secrets.
//
// We should only populate the NumSelectedRepos field in these cases:
// 1. The command is run in the TTY mode without the `--json <fields>` option.
// 2. The command is run with `--json <fields>` option, and `numSelectedRepos`
// is among the selected fields. In this case, TTY mode is irrelevant.
func Test_listRun_populatesNumSelectedReposIfRequired(t *testing.T) {
type secretKind string
const secretKindUser secretKind = "user"
const secretKindOrg secretKind = "org"
tests := []struct {
name string
kind secretKind
tty bool
jsonFields []string
wantPopulated bool
}{
{
name: "org tty",
kind: secretKindOrg,
tty: true,
wantPopulated: true,
},
{
name: "org tty, json with numSelectedRepos",
kind: secretKindOrg,
tty: true,
jsonFields: []string{"numSelectedRepos"},
wantPopulated: true,
},
{
name: "org tty, json without numSelectedRepos",
kind: secretKindOrg,
tty: true,
jsonFields: []string{"name"},
wantPopulated: false,
},
{
name: "org not tty",
kind: secretKindOrg,
tty: false,
wantPopulated: false,
},
{
name: "org not tty, json with numSelectedRepos",
kind: secretKindOrg,
tty: false,
jsonFields: []string{"numSelectedRepos"},
wantPopulated: true,
},
{
name: "org not tty, json without numSelectedRepos",
kind: secretKindOrg,
tty: false,
jsonFields: []string{"name"},
wantPopulated: false,
},
{
name: "user tty",
kind: secretKindUser,
tty: true,
wantPopulated: true,
},
{
name: "user tty, json with numSelectedRepos",
kind: secretKindUser,
tty: true,
jsonFields: []string{"numSelectedRepos"},
wantPopulated: true,
},
{
name: "user tty, json without numSelectedRepos",
kind: secretKindUser,
tty: true,
jsonFields: []string{"name"},
wantPopulated: false,
},
{
name: "user not tty",
kind: secretKindUser,
tty: false,
wantPopulated: false,
},
{
name: "user not tty, json with numSelectedRepos",
kind: secretKindUser,
tty: false,
jsonFields: []string{"numSelectedRepos"},
wantPopulated: true,
},
{
name: "user not tty, json without numSelectedRepos",
kind: secretKindUser,
tty: false,
jsonFields: []string{"name"},
wantPopulated: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
reg.Verify(t)
t0, _ := time.Parse("2006-01-02", "1988-10-11")
opts := &ListOptions{}
if tt.kind == secretKindOrg {
opts.OrgName = "umbrellaOrganization"
reg.Register(
httpmock.REST("GET", "orgs/umbrellaOrganization/actions/secrets"),
httpmock.JSONResponse(struct{ Secrets []Secret }{
[]Secret{
{
Name: "SECRET",
UpdatedAt: t0,
Visibility: shared.Selected,
SelectedReposURL: "https://api.github.com/orgs/umbrellaOrganization/actions/secrets/SECRET/repositories",
},
},
}))
reg.Register(
httpmock.REST("GET", "orgs/umbrellaOrganization/actions/secrets/SECRET/repositories"),
httpmock.JSONResponse(struct {
TotalCount int `json:"total_count"`
}{999}))
}
if tt.kind == secretKindUser {
opts.UserSecrets = true
reg.Register(
httpmock.REST("GET", "user/codespaces/secrets"),
httpmock.JSONResponse(struct{ Secrets []Secret }{
[]Secret{
{
Name: "SECRET",
UpdatedAt: t0,
Visibility: shared.Selected,
SelectedReposURL: "https://api.github.com/user/codespaces/secrets/SECRET/repositories",
},
},
}))
reg.Register(
httpmock.REST("GET", "user/codespaces/secrets/SECRET/repositories"),
httpmock.JSONResponse(struct {
TotalCount int `json:"total_count"`
}{999}))
}
if tt.jsonFields != nil {
exporter := cmdutil.NewJSONExporter()
exporter.SetFields(tt.jsonFields)
opts.Exporter = exporter
}
ios, _, _, _ := iostreams.Test()
ios.SetStdoutTTY(tt.tty)
opts.IO = ios
opts.BaseRepo = func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("owner/repo")
}
opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
opts.Config = func() (gh.Config, error) {
return config.NewBlankConfig(), nil
}
opts.Now = func() time.Time {
t, _ := time.Parse(time.RFC822, "4 Apr 24 00:00 UTC")
return t
}
err := listRun(opts)
assert.NoError(t, err)
if tt.wantPopulated {
// There should be 2 requests; one to get the secrets list and
// another to populate the numSelectedRepos field.
assert.Len(t, reg.Requests, 2)
} else {
// Only one requests to get the secrets list.
assert.Len(t, reg.Requests, 1)
}
})
}
}
func Test_getSecrets_pagination(t *testing.T) {
reg := &httpmock.Registry{}
defer reg.Verify(t)
reg.Register(
httpmock.QueryMatcher("GET", "path/to", url.Values{"per_page": []string{"100"}}),
httpmock.WithHeader(
httpmock.StringResponse(`{"secrets":[{},{}]}`),
"Link",
`<http://example.com/page/0>; rel="previous", <http://example.com/page/2>; rel="next"`),
)
reg.Register(
httpmock.REST("GET", "page/2"),
httpmock.StringResponse(`{"secrets":[{},{}]}`),
)
client := &http.Client{Transport: reg}
secrets, err := getSecrets(client, "github.com", "path/to")
assert.NoError(t, err)
assert.Equal(t, 4, len(secrets))
}
func TestExportSecrets(t *testing.T) {
ios, _, stdout, _ := iostreams.Test()
tf, _ := time.Parse(time.RFC3339, "2024-01-01T00:00:00Z")
ss := []Secret{{
Name: "s1",
UpdatedAt: tf,
Visibility: shared.All,
SelectedReposURL: "https://someurl.com",
NumSelectedRepos: 1,
}}
exporter := cmdutil.NewJSONExporter()
exporter.SetFields(secretFields)
require.NoError(t, exporter.Write(ios, ss))
require.JSONEq(t,
`[{"name":"s1","numSelectedRepos":1,"selectedReposURL":"https://someurl.com","updatedAt":"2024-01-01T00:00:00Z","visibility":"all"}]`,
stdout.String())
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/secret/list/list.go | pkg/cmd/secret/list/list.go | package list
import (
"fmt"
"net/http"
"os"
"slices"
"strings"
"time"
"github.com/MakeNowJust/heredoc"
"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/internal/tableprinter"
"github.com/cli/cli/v2/pkg/cmd/secret/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type ListOptions struct {
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
Config func() (gh.Config, error)
BaseRepo func() (ghrepo.Interface, error)
Prompter prompter.Prompter
Now func() time.Time
Exporter cmdutil.Exporter
OrgName string
EnvName string
UserSecrets bool
Application string
}
var secretFields = []string{
"selectedReposURL",
"name",
"visibility",
"updatedAt",
"numSelectedRepos",
}
const fieldNumSelectedRepos = "numSelectedRepos"
func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Command {
opts := &ListOptions{
IO: f.IOStreams,
Config: f.Config,
HttpClient: f.HttpClient,
Now: time.Now,
Prompter: f.Prompter,
}
cmd := &cobra.Command{
Use: "list",
Short: "List secrets",
Long: heredoc.Doc(`
List secrets on one of the following levels:
- repository (default): available to GitHub Actions runs or Dependabot in a repository
- environment: available to GitHub Actions runs for a deployment environment in a repository
- organization: available to GitHub Actions runs, Dependabot, or Codespaces within an organization
- user: available to Codespaces for your user
`),
Aliases: []string{"ls"},
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
// If the user specified a repo directly, then we're using the OverrideBaseRepoFunc set by EnableRepoOverride
// So there's no reason to use the specialised BaseRepoFunc that requires remote disambiguation.
opts.BaseRepo = f.BaseRepo
isRepoUserProvided := cmd.Flags().Changed("repo") || os.Getenv("GH_REPO") != ""
if !isRepoUserProvided {
// If they haven't specified a repo directly, then we will wrap the BaseRepoFunc in one that errors if
// there might be multiple valid remotes.
opts.BaseRepo = shared.RequireNoAmbiguityBaseRepoFunc(opts.BaseRepo, f.Remotes)
// But if we are able to prompt, then we will wrap that up in a BaseRepoFunc that can prompt the user to
// resolve the ambiguity.
if opts.IO.CanPrompt() {
opts.BaseRepo = shared.PromptWhenAmbiguousBaseRepoFunc(opts.BaseRepo, f.IOStreams, f.Prompter)
}
}
if err := cmdutil.MutuallyExclusive("specify only one of `--org`, `--env`, or `--user`", opts.OrgName != "", opts.EnvName != "", opts.UserSecrets); err != nil {
return err
}
if runF != nil {
return runF(opts)
}
return listRun(opts)
},
}
cmd.Flags().StringVarP(&opts.OrgName, "org", "o", "", "List secrets for an organization")
cmd.Flags().StringVarP(&opts.EnvName, "env", "e", "", "List secrets for an environment")
cmd.Flags().BoolVarP(&opts.UserSecrets, "user", "u", false, "List a secret for your user")
cmdutil.StringEnumFlag(cmd, &opts.Application, "app", "a", "", []string{shared.Actions, shared.Codespaces, shared.Dependabot}, "List secrets for a specific application")
cmdutil.AddJSONFlags(cmd, &opts.Exporter, secretFields)
return cmd
}
func listRun(opts *ListOptions) error {
client, err := opts.HttpClient()
if err != nil {
return fmt.Errorf("could not create http client: %w", err)
}
orgName := opts.OrgName
envName := opts.EnvName
var baseRepo ghrepo.Interface
if orgName == "" && !opts.UserSecrets {
baseRepo, err = opts.BaseRepo()
if err != nil {
return err
}
}
secretEntity, err := shared.GetSecretEntity(orgName, envName, opts.UserSecrets)
if err != nil {
return err
}
secretApp, err := shared.GetSecretApp(opts.Application, secretEntity)
if err != nil {
return err
}
if !shared.IsSupportedSecretEntity(secretApp, secretEntity) {
return fmt.Errorf("%s secrets are not supported for %s", secretEntity, secretApp)
}
// Since populating the `NumSelectedRepos` field costs further API requests
// (one per secret), it's important to avoid extra calls when the output will
// not present the field's value. So, we should only populate this field in
// these cases:
// 1. The command is run in the TTY mode without the `--json <fields>` option.
// 2. The command is run with `--json <fields>` option, and `numSelectedRepos`
// is among the selected fields. In this case, TTY mode is irrelevant.
showSelectedRepoInfo := opts.IO.IsStdoutTTY()
if opts.Exporter != nil {
// Note that if there's an exporter set, then we don't mind the TTY mode
// because we just have to populate the requested fields.
showSelectedRepoInfo = slices.Contains(opts.Exporter.Fields(), fieldNumSelectedRepos)
}
var secrets []Secret
switch secretEntity {
case shared.Repository:
secrets, err = getRepoSecrets(client, baseRepo, secretApp)
case shared.Environment:
secrets, err = getEnvSecrets(client, baseRepo, envName)
case shared.Organization, shared.User:
var cfg gh.Config
var host string
cfg, err = opts.Config()
if err != nil {
return err
}
host, _ = cfg.Authentication().DefaultHost()
if secretEntity == shared.User {
secrets, err = getUserSecrets(client, host, showSelectedRepoInfo)
} else {
secrets, err = getOrgSecrets(client, host, orgName, showSelectedRepoInfo, secretApp)
}
}
if err != nil {
return fmt.Errorf("failed to get secrets: %w", err)
}
if len(secrets) == 0 && opts.Exporter == nil {
return cmdutil.NewNoResultsError("no secrets found")
}
if err := opts.IO.StartPager(); err == nil {
defer opts.IO.StopPager()
} else {
fmt.Fprintf(opts.IO.ErrOut, "failed to start pager: %v\n", err)
}
if opts.Exporter != nil {
return opts.Exporter.Write(opts.IO, secrets)
}
var headers []string
if secretEntity == shared.Organization || secretEntity == shared.User {
headers = []string{"Name", "Updated", "Visibility"}
} else {
headers = []string{"Name", "Updated"}
}
table := tableprinter.New(opts.IO, tableprinter.WithHeader(headers...))
for _, secret := range secrets {
table.AddField(secret.Name)
table.AddTimeField(opts.Now(), secret.UpdatedAt, nil)
if secret.Visibility != "" {
if showSelectedRepoInfo {
table.AddField(fmtVisibility(secret))
} else {
table.AddField(strings.ToUpper(string(secret.Visibility)))
}
}
table.EndRow()
}
err = table.Render()
if err != nil {
return err
}
return nil
}
type Secret struct {
Name string `json:"name"`
UpdatedAt time.Time `json:"updated_at"`
Visibility shared.Visibility `json:"visibility"`
SelectedReposURL string `json:"selected_repositories_url"`
NumSelectedRepos int `json:"num_selected_repos"`
}
func (s *Secret) ExportData(fields []string) map[string]interface{} {
return cmdutil.StructExportData(s, fields)
}
func fmtVisibility(s Secret) string {
switch s.Visibility {
case shared.All:
return "Visible to all repositories"
case shared.Private:
return "Visible to private repositories"
case shared.Selected:
if s.NumSelectedRepos == 1 {
return "Visible to 1 selected repository"
} else {
return fmt.Sprintf("Visible to %d selected repositories", s.NumSelectedRepos)
}
}
return ""
}
func getOrgSecrets(client *http.Client, host, orgName string, showSelectedRepoInfo bool, app shared.App) ([]Secret, error) {
secrets, err := getSecrets(client, host, fmt.Sprintf("orgs/%s/%s/secrets", orgName, app))
if err != nil {
return nil, err
}
if showSelectedRepoInfo {
err = populateSelectedRepositoryInformation(client, host, secrets)
if err != nil {
return nil, err
}
}
return secrets, nil
}
func getUserSecrets(client *http.Client, host string, showSelectedRepoInfo bool) ([]Secret, error) {
secrets, err := getSecrets(client, host, "user/codespaces/secrets")
if err != nil {
return nil, err
}
if showSelectedRepoInfo {
err = populateSelectedRepositoryInformation(client, host, secrets)
if err != nil {
return nil, err
}
}
return secrets, nil
}
func getEnvSecrets(client *http.Client, repo ghrepo.Interface, envName string) ([]Secret, error) {
path := fmt.Sprintf("repos/%s/environments/%s/secrets", ghrepo.FullName(repo), envName)
return getSecrets(client, repo.RepoHost(), path)
}
func getRepoSecrets(client *http.Client, repo ghrepo.Interface, app shared.App) ([]Secret, error) {
return getSecrets(client, repo.RepoHost(), fmt.Sprintf("repos/%s/%s/secrets", ghrepo.FullName(repo), app))
}
func getSecrets(client *http.Client, host, path string) ([]Secret, error) {
var results []Secret
apiClient := api.NewClientFromHTTP(client)
path = fmt.Sprintf("%s?per_page=100", path)
for path != "" {
response := struct {
Secrets []Secret
}{}
var err error
path, err = apiClient.RESTWithNext(host, "GET", path, nil, &response)
if err != nil {
return nil, err
}
results = append(results, response.Secrets...)
}
return results, nil
}
func populateSelectedRepositoryInformation(client *http.Client, host string, secrets []Secret) error {
apiClient := api.NewClientFromHTTP(client)
for i, secret := range secrets {
if secret.SelectedReposURL == "" {
continue
}
response := struct {
TotalCount int `json:"total_count"`
}{}
if err := apiClient.REST(host, "GET", secret.SelectedReposURL, nil, &response); err != nil {
return fmt.Errorf("failed determining selected repositories for %s: %w", secret.Name, err)
}
secrets[i].NumSelectedRepos = response.TotalCount
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/secret/shared/shared_test.go | pkg/cmd/secret/shared/shared_test.go | package shared
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestGetSecretEntity(t *testing.T) {
tests := []struct {
name string
orgName string
envName string
userSecrets bool
want SecretEntity
wantErr bool
}{
{
name: "org",
orgName: "myOrg",
want: Organization,
},
{
name: "env",
envName: "myEnv",
want: Environment,
},
{
name: "user",
userSecrets: true,
want: User,
},
{
name: "defaults to repo",
want: Repository,
},
{
name: "Errors if both org and env are set",
orgName: "myOrg",
envName: "myEnv",
wantErr: true,
},
{
name: "Errors if both org and user secrets are set",
orgName: "myOrg",
userSecrets: true,
wantErr: true,
},
{
name: "Errors if both env and user secrets are set",
envName: "myEnv",
userSecrets: true,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
entity, err := GetSecretEntity(tt.orgName, tt.envName, tt.userSecrets)
if tt.wantErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
assert.Equal(t, tt.want, entity)
}
})
}
}
func TestGetSecretApp(t *testing.T) {
tests := []struct {
name string
app string
entity SecretEntity
want App
wantErr bool
}{
{
name: "Actions",
app: "actions",
want: Actions,
},
{
name: "Codespaces",
app: "codespaces",
want: Codespaces,
},
{
name: "Dependabot",
app: "dependabot",
want: Dependabot,
},
{
name: "Defaults to Actions for repository",
app: "",
entity: Repository,
want: Actions,
},
{
name: "Defaults to Actions for organization",
app: "",
entity: Organization,
want: Actions,
},
{
name: "Defaults to Actions for environment",
app: "",
entity: Environment,
want: Actions,
},
{
name: "Defaults to Codespaces for user",
app: "",
entity: User,
want: Codespaces,
},
{
name: "Unknown for invalid apps",
app: "invalid",
want: Unknown,
wantErr: true,
},
{
name: "case insensitive",
app: "ACTIONS",
want: Actions,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
app, err := GetSecretApp(tt.app, tt.entity)
if tt.wantErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}
assert.Equal(t, tt.want, app)
})
}
}
func TestIsSupportedSecretEntity(t *testing.T) {
tests := []struct {
name string
app App
supportedEntities []SecretEntity
unsupportedEntities []SecretEntity
}{
{
name: "Actions",
app: Actions,
supportedEntities: []SecretEntity{
Repository,
Organization,
Environment,
},
unsupportedEntities: []SecretEntity{
User,
Unknown,
},
},
{
name: "Codespaces",
app: Codespaces,
supportedEntities: []SecretEntity{
User,
Repository,
Organization,
},
unsupportedEntities: []SecretEntity{
Environment,
Unknown,
},
},
{
name: "Dependabot",
app: Dependabot,
supportedEntities: []SecretEntity{
Repository,
Organization,
},
unsupportedEntities: []SecretEntity{
Environment,
User,
Unknown,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
for _, entity := range tt.supportedEntities {
assert.True(t, IsSupportedSecretEntity(tt.app, entity))
}
for _, entity := range tt.unsupportedEntities {
assert.False(t, IsSupportedSecretEntity(tt.app, entity))
}
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/secret/shared/base_repo.go | pkg/cmd/secret/shared/base_repo.go | package shared
import (
"errors"
"fmt"
ghContext "github.com/cli/cli/v2/context"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/prompter"
"github.com/cli/cli/v2/pkg/iostreams"
)
type AmbiguousBaseRepoError struct {
Remotes ghContext.Remotes
}
func (e AmbiguousBaseRepoError) Error() string {
return "multiple remotes detected. please specify which repo to use by providing the -R, --repo argument"
}
type baseRepoFn func() (ghrepo.Interface, error)
type remotesFn func() (ghContext.Remotes, error)
func PromptWhenAmbiguousBaseRepoFunc(baseRepoFn baseRepoFn, ios *iostreams.IOStreams, prompter prompter.Prompter) baseRepoFn {
return func() (ghrepo.Interface, error) {
baseRepo, err := baseRepoFn()
if err != nil {
var ambiguousBaseRepoErr AmbiguousBaseRepoError
if !errors.As(err, &ambiguousBaseRepoErr) {
return nil, err
}
baseRepoOptions := make([]string, len(ambiguousBaseRepoErr.Remotes))
for i, remote := range ambiguousBaseRepoErr.Remotes {
baseRepoOptions[i] = ghrepo.FullName(remote)
}
fmt.Fprintf(ios.Out, "%s Multiple remotes detected. Due to the sensitive nature of secrets, requiring disambiguation.\n", ios.ColorScheme().WarningIcon())
selectedBaseRepo, err := prompter.Select("Select a repo", baseRepoOptions[0], baseRepoOptions)
if err != nil {
return nil, err
}
selectedRepo, err := ghrepo.FromFullName(baseRepoOptions[selectedBaseRepo])
if err != nil {
return nil, err
}
return selectedRepo, nil
}
return baseRepo, nil
}
}
// RequireNoAmbiguityBaseRepoFunc returns a function to resolve the base repo, ensuring that
// there was only one option, regardless of whether the base repo had been set.
func RequireNoAmbiguityBaseRepoFunc(baseRepo baseRepoFn, remotes remotesFn) baseRepoFn {
return func() (ghrepo.Interface, error) {
remotes, err := remotes()
if err != nil {
return nil, err
}
if remotes.Len() > 1 {
return nil, AmbiguousBaseRepoError{Remotes: remotes}
}
return baseRepo()
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/secret/shared/base_repo_test.go | pkg/cmd/secret/shared/base_repo_test.go | package shared_test
import (
"errors"
"testing"
ghContext "github.com/cli/cli/v2/context"
"github.com/cli/cli/v2/pkg/cmd/secret/shared"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/stretchr/testify/require"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/prompter"
)
func TestRequireNoAmbiguityBaseRepoFunc(t *testing.T) {
t.Parallel()
t.Run("succeeds when there is only one remote", func(t *testing.T) {
t.Parallel()
// Given there is only one remote
baseRepoFn := shared.RequireNoAmbiguityBaseRepoFunc(baseRepoStubFn, oneRemoteStubFn)
// When fetching the base repo
baseRepo, err := baseRepoFn()
// It succeeds and returns the inner base repo
require.NoError(t, err)
require.True(t, ghrepo.IsSame(ghrepo.New("owner", "repo"), baseRepo))
})
t.Run("returns specific error when there are multiple remotes", func(t *testing.T) {
t.Parallel()
// Given there are multiple remotes
baseRepoFn := shared.RequireNoAmbiguityBaseRepoFunc(baseRepoStubFn, twoRemotesStubFn)
// When fetching the base repo
_, err := baseRepoFn()
// It succeeds and returns the inner base repo
var multipleRemotesError shared.AmbiguousBaseRepoError
require.ErrorAs(t, err, &multipleRemotesError)
require.Equal(t, ghContext.Remotes{
{
Remote: &git.Remote{
Name: "origin",
},
Repo: ghrepo.New("owner", "fork"),
},
{
Remote: &git.Remote{
Name: "upstream",
},
Repo: ghrepo.New("owner", "repo"),
},
}, multipleRemotesError.Remotes)
})
t.Run("when the remote fetching function fails, it returns the error", func(t *testing.T) {
t.Parallel()
// Given the remote fetching function fails
baseRepoFn := shared.RequireNoAmbiguityBaseRepoFunc(baseRepoStubFn, errRemoteStubFn)
// When fetching the base repo
_, err := baseRepoFn()
// It returns the error
require.Equal(t, errors.New("test remote error"), err)
})
t.Run("when the wrapped base repo function fails, it returns the error", func(t *testing.T) {
t.Parallel()
// Given the wrapped base repo function fails
baseRepoFn := shared.RequireNoAmbiguityBaseRepoFunc(errBaseRepoStubFn, oneRemoteStubFn)
// When fetching the base repo
_, err := baseRepoFn()
// It returns the error
require.Equal(t, errors.New("test base repo error"), err)
})
}
func TestPromptWhenMultipleRemotesBaseRepoFunc(t *testing.T) {
t.Parallel()
t.Run("when there is no error from wrapped base repo func, then it succeeds without prompting", func(t *testing.T) {
t.Parallel()
ios, _, _, _ := iostreams.Test()
// Given the base repo function succeeds
baseRepoFn := shared.PromptWhenAmbiguousBaseRepoFunc(baseRepoStubFn, ios, nil)
// When fetching the base repo
baseRepo, err := baseRepoFn()
// It succeeds and returns the inner base repo
require.NoError(t, err)
require.True(t, ghrepo.IsSame(ghrepo.New("owner", "repo"), baseRepo))
})
t.Run("when the wrapped base repo func returns a specific error, then the prompter is used for disambiguation, with the remote ordering remaining unchanged", func(t *testing.T) {
t.Parallel()
ios, _, stdout, _ := iostreams.Test()
pm := prompter.NewMockPrompter(t)
pm.RegisterSelect(
"Select a repo",
[]string{"owner/fork", "owner/repo"},
func(_, def string, opts []string) (int, error) {
require.Equal(t, "owner/fork", def)
return prompter.IndexFor(opts, "owner/repo")
},
)
// Given the wrapped base repo func returns a specific error
baseRepoFn := shared.PromptWhenAmbiguousBaseRepoFunc(errMultipleRemotesStubFn, ios, pm)
// When fetching the base repo
baseRepo, err := baseRepoFn()
// It prints an informative message
require.Equal(t, "! Multiple remotes detected. Due to the sensitive nature of secrets, requiring disambiguation.\n", stdout.String())
// And it uses the prompter for disambiguation
require.NoError(t, err)
require.True(t, ghrepo.IsSame(ghrepo.New("owner", "repo"), baseRepo))
})
t.Run("when the prompter returns an error, then it is returned", func(t *testing.T) {
t.Parallel()
ios, _, _, _ := iostreams.Test()
// Given the prompter returns an error
pm := prompter.NewMockPrompter(t)
pm.RegisterSelect(
"Select a repo",
[]string{"owner/fork", "owner/repo"},
func(_, _ string, opts []string) (int, error) {
return 0, errors.New("test prompt error")
},
)
// Given the wrapped base repo func returns a specific error
baseRepoFn := shared.PromptWhenAmbiguousBaseRepoFunc(errMultipleRemotesStubFn, ios, pm)
// When fetching the base repo
_, err := baseRepoFn()
// It returns the error
require.Equal(t, errors.New("test prompt error"), err)
})
t.Run("when the wrapped base repo func returns a non-specific error, then it is returned", func(t *testing.T) {
t.Parallel()
ios, _, _, _ := iostreams.Test()
// Given the wrapped base repo func returns a non-specific error
baseRepoFn := shared.PromptWhenAmbiguousBaseRepoFunc(errBaseRepoStubFn, ios, nil)
// When fetching the base repo
_, err := baseRepoFn()
// It returns the error
require.Equal(t, errors.New("test base repo error"), err)
})
}
func TestMultipleRemotesErrorMessage(t *testing.T) {
err := shared.AmbiguousBaseRepoError{}
require.EqualError(t, err, "multiple remotes detected. please specify which repo to use by providing the -R, --repo argument")
}
func errMultipleRemotesStubFn() (ghrepo.Interface, error) {
remote1 := &ghContext.Remote{
Remote: &git.Remote{
Name: "origin",
},
Repo: ghrepo.New("owner", "fork"),
}
remote2 := &ghContext.Remote{
Remote: &git.Remote{
Name: "upstream",
},
Repo: ghrepo.New("owner", "repo"),
}
return nil, shared.AmbiguousBaseRepoError{
Remotes: ghContext.Remotes{
remote1,
remote2,
},
}
}
func baseRepoStubFn() (ghrepo.Interface, error) {
return ghrepo.New("owner", "repo"), nil
}
func oneRemoteStubFn() (ghContext.Remotes, error) {
remote := &ghContext.Remote{
Remote: &git.Remote{
Name: "origin",
},
Repo: ghrepo.New("owner", "repo"),
}
return ghContext.Remotes{
remote,
}, nil
}
func twoRemotesStubFn() (ghContext.Remotes, error) {
remote1 := &ghContext.Remote{
Remote: &git.Remote{
Name: "origin",
},
Repo: ghrepo.New("owner", "fork"),
}
remote2 := &ghContext.Remote{
Remote: &git.Remote{
Name: "upstream",
},
Repo: ghrepo.New("owner", "repo"),
}
return ghContext.Remotes{
remote1,
remote2,
}, nil
}
func errRemoteStubFn() (ghContext.Remotes, error) {
return nil, errors.New("test remote error")
}
func errBaseRepoStubFn() (ghrepo.Interface, error) {
return nil, errors.New("test base repo error")
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/secret/shared/shared.go | pkg/cmd/secret/shared/shared.go | package shared
import (
"errors"
"fmt"
"strings"
"github.com/cli/cli/v2/internal/text"
)
type Visibility string
const (
All = "all"
Private = "private"
Selected = "selected"
)
type App string
const (
Actions = "actions"
Codespaces = "codespaces"
Dependabot = "dependabot"
Unknown = "unknown"
)
func (app App) String() string {
return string(app)
}
func (app App) Title() string {
return text.Title(app.String())
}
type SecretEntity string
const (
Repository = "repository"
Organization = "organization"
User = "user"
Environment = "environment"
)
func GetSecretEntity(orgName, envName string, userSecrets bool) (SecretEntity, error) {
orgSet := orgName != ""
envSet := envName != ""
if orgSet && envSet || orgSet && userSecrets || envSet && userSecrets {
return "", errors.New("cannot specify multiple secret entities")
}
if orgSet {
return Organization, nil
}
if envSet {
return Environment, nil
}
if userSecrets {
return User, nil
}
return Repository, nil
}
func GetSecretApp(app string, entity SecretEntity) (App, error) {
switch strings.ToLower(app) {
case Actions:
return Actions, nil
case Codespaces:
return Codespaces, nil
case Dependabot:
return Dependabot, nil
case "":
if entity == User {
return Codespaces, nil
}
return Actions, nil
default:
return Unknown, fmt.Errorf("invalid application: %s", app)
}
}
func IsSupportedSecretEntity(app App, entity SecretEntity) bool {
switch app {
case Actions:
return entity == Repository || entity == Organization || entity == Environment
case Codespaces:
return entity == User || entity == Organization || entity == Repository
case Dependabot:
return entity == Repository || entity == Organization
default:
return false
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/secret/set/set_test.go | pkg/cmd/secret/set/set_test.go | package set
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"testing"
"github.com/MakeNowJust/heredoc"
ghContext "github.com/cli/cli/v2/context"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/config"
"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/cmd/secret/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"
"github.com/stretchr/testify/require"
)
func TestNewCmdSet(t *testing.T) {
tests := []struct {
name string
args string
wants SetOptions
stdinTTY bool
wantsErr bool
wantsErrMessage string
}{
{
name: "invalid visibility",
args: "cool_secret --org coolOrg -v mistyVeil",
wantsErr: true,
},
{
name: "when visibility is selected, requires indication of repos",
args: "cool_secret --org coolOrg -v selected",
wantsErr: true,
wantsErrMessage: "`--repos` or `--no-repos-selected` required with `--visibility=selected`",
},
{
name: "visibilities other than selected do not accept --repos",
args: "cool_secret --org coolOrg -v private -r coolRepo",
wantsErr: true,
wantsErrMessage: "`--repos` is only supported with `--visibility=selected`",
},
{
name: "visibilities other than selected do not accept --no-repos-selected",
args: "cool_secret --org coolOrg -v private --no-repos-selected",
wantsErr: true,
wantsErrMessage: "`--no-repos-selected` is only supported with `--visibility=selected`",
},
{
name: "--repos and --no-repos-selected are mutually exclusive",
args: `--repos coolRepo --no-repos-selected cool_secret`,
wantsErr: true,
wantsErrMessage: "specify only one of `--repos` or `--no-repos-selected`",
},
{
name: "secret name is required",
args: "",
wantsErr: true,
},
{
name: "multiple positional arguments are not allowed",
args: "cool_secret good_secret",
wantsErr: true,
},
{
name: "visibility is only allowed with --org",
args: "cool_secret -v all",
wantsErr: true,
},
{
name: "providing --repos without --visibility implies selected visibility",
args: "cool_secret --body secret-body --org coolOrg --repos coolRepo",
wants: SetOptions{
SecretName: "cool_secret",
Visibility: shared.Selected,
RepositoryNames: []string{"coolRepo"},
Body: "secret-body",
OrgName: "coolOrg",
},
},
{
name: "providing --no-repos-selected without --visibility implies selected visibility",
args: "cool_secret --body secret-body --org coolOrg --no-repos-selected",
wants: SetOptions{
SecretName: "cool_secret",
Visibility: shared.Selected,
RepositoryNames: []string{},
Body: "secret-body",
OrgName: "coolOrg",
},
},
{
name: "org with selected repo",
args: "-o coolOrg --body secret-body -v selected -r coolRepo cool_secret",
wants: SetOptions{
SecretName: "cool_secret",
Visibility: shared.Selected,
RepositoryNames: []string{"coolRepo"},
Body: "secret-body",
OrgName: "coolOrg",
},
},
{
name: "org with selected repos",
args: `--org coolOrg --body secret-body -v selected --repos "coolRepo,radRepo,goodRepo" cool_secret`,
wants: SetOptions{
SecretName: "cool_secret",
Visibility: shared.Selected,
RepositoryNames: []string{"coolRepo", "goodRepo", "radRepo"},
Body: "secret-body",
OrgName: "coolOrg",
},
},
{
name: "user with selected repos",
args: `-u --body secret-body -r "monalisa/coolRepo,cli/cli,github/hub" cool_secret`,
wants: SetOptions{
SecretName: "cool_secret",
Visibility: shared.Selected,
RepositoryNames: []string{"monalisa/coolRepo", "cli/cli", "github/hub"},
Body: "secret-body",
},
},
{
name: "--user is mutually exclusive with --no-repos-selected",
args: `-u --no-repos-selected cool_secret`,
wantsErr: true,
wantsErrMessage: "`--no-repos-selected` must be omitted when used with `--user`",
},
{
name: "repo",
args: `cool_secret --body "a secret"`,
wants: SetOptions{
SecretName: "cool_secret",
Visibility: shared.Private,
Body: "a secret",
OrgName: "",
},
},
{
name: "env",
args: `cool_secret --body "a secret" --env Release`,
wants: SetOptions{
SecretName: "cool_secret",
Visibility: shared.Private,
Body: "a secret",
OrgName: "",
EnvName: "Release",
},
},
{
name: "vis all",
args: `cool_secret --org coolOrg --body "cool" --visibility all`,
wants: SetOptions{
SecretName: "cool_secret",
Visibility: shared.All,
Body: "cool",
OrgName: "coolOrg",
},
},
{
name: "no store",
args: `cool_secret --no-store`,
wants: SetOptions{
SecretName: "cool_secret",
Visibility: shared.Private,
DoNotStore: true,
},
},
{
name: "Dependabot repo",
args: `cool_secret --body "a secret" --app Dependabot`,
wants: SetOptions{
SecretName: "cool_secret",
Visibility: shared.Private,
Body: "a secret",
OrgName: "",
Application: "Dependabot",
},
},
{
name: "Dependabot org",
args: "--org coolOrg --body secret-body --visibility selected --repos coolRepo cool_secret --app Dependabot",
wants: SetOptions{
SecretName: "cool_secret",
Visibility: shared.Selected,
RepositoryNames: []string{"coolRepo"},
Body: "secret-body",
OrgName: "coolOrg",
Application: "Dependabot",
},
},
{
name: "Codespaces org",
args: `random_secret --org coolOrg --body "random value" --visibility selected --repos "coolRepo,cli/cli" --app Codespaces`,
wants: SetOptions{
SecretName: "random_secret",
Visibility: shared.Selected,
RepositoryNames: []string{"coolRepo", "cli/cli"},
Body: "random value",
OrgName: "coolOrg",
Application: "Codespaces",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
f := &cmdutil.Factory{
IOStreams: ios,
}
ios.SetStdinTTY(tt.stdinTTY)
argv, err := shlex.Split(tt.args)
assert.NoError(t, err)
var gotOpts *SetOptions
cmd := NewCmdSet(f, func(opts *SetOptions) 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.wantsErr {
assert.Error(t, err)
if tt.wantsErrMessage != "" {
assert.EqualError(t, err, tt.wantsErrMessage)
}
return
}
assert.NoError(t, err)
assert.Equal(t, tt.wants.SecretName, gotOpts.SecretName)
assert.Equal(t, tt.wants.Body, gotOpts.Body)
assert.Equal(t, tt.wants.Visibility, gotOpts.Visibility)
assert.Equal(t, tt.wants.OrgName, gotOpts.OrgName)
assert.Equal(t, tt.wants.EnvName, gotOpts.EnvName)
assert.Equal(t, tt.wants.DoNotStore, gotOpts.DoNotStore)
assert.ElementsMatch(t, tt.wants.RepositoryNames, gotOpts.RepositoryNames)
assert.Equal(t, tt.wants.Application, gotOpts.Application)
})
}
}
func TestNewCmdSetBaseRepoFuncs(t *testing.T) {
multipleRemotes := ghContext.Remotes{
&ghContext.Remote{
Remote: &git.Remote{
Name: "origin",
},
Repo: ghrepo.New("owner", "fork"),
},
&ghContext.Remote{
Remote: &git.Remote{
Name: "upstream",
},
Repo: ghrepo.New("owner", "repo"),
},
}
singleRemote := ghContext.Remotes{
&ghContext.Remote{
Remote: &git.Remote{
Name: "origin",
},
Repo: ghrepo.New("owner", "repo"),
},
}
tests := []struct {
name string
args string
env map[string]string
remotes ghContext.Remotes
prompterStubs func(*prompter.MockPrompter)
wantRepo ghrepo.Interface
wantErr error
}{
{
name: "when there is a repo flag provided, the factory base repo func is used",
args: "SECRET_NAME --repo owner/repo",
remotes: multipleRemotes,
wantRepo: ghrepo.New("owner", "repo"),
},
{
name: "when GH_REPO env var is provided, the factory base repo func is used",
args: "SECRET_NAME",
env: map[string]string{
"GH_REPO": "owner/repo",
},
remotes: multipleRemotes,
wantRepo: ghrepo.New("owner", "repo"),
},
{
name: "when there is no repo flag or GH_REPO env var provided, and no prompting, the base func requiring no ambiguity is used",
args: "SECRET_NAME",
remotes: multipleRemotes,
wantErr: shared.AmbiguousBaseRepoError{
Remotes: multipleRemotes,
},
},
{
name: "when there is no repo flag or GH_REPO env provided, and there is a single remote, the factory base repo func is used",
args: "SECRET_NAME",
remotes: singleRemote,
wantRepo: ghrepo.New("owner", "repo"),
},
{
name: "when there is no repo flag or GH_REPO env var provided, and can prompt, the base func resolving ambiguity is used",
args: "SECRET_NAME",
remotes: multipleRemotes,
prompterStubs: func(pm *prompter.MockPrompter) {
pm.RegisterSelect(
"Select a repo",
[]string{"owner/fork", "owner/repo"},
func(_, _ string, opts []string) (int, error) {
return prompter.IndexFor(opts, "owner/fork")
},
)
},
wantRepo: ghrepo.New("owner", "fork"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
var pm *prompter.MockPrompter
if tt.prompterStubs != nil {
ios.SetStdinTTY(true)
ios.SetStdoutTTY(true)
ios.SetStderrTTY(true)
pm = prompter.NewMockPrompter(t)
tt.prompterStubs(pm)
}
f := &cmdutil.Factory{
IOStreams: ios,
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("owner/repo")
},
Prompter: pm,
Remotes: func() (ghContext.Remotes, error) {
return tt.remotes, nil
},
}
for k, v := range tt.env {
t.Setenv(k, v)
}
argv, err := shlex.Split(tt.args)
assert.NoError(t, err)
var gotOpts *SetOptions
cmd := NewCmdSet(f, func(opts *SetOptions) error {
gotOpts = opts
return nil
})
// Require to support --repo flag
cmdutil.EnableRepoOverride(cmd, f)
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
_, err = cmd.ExecuteC()
require.NoError(t, err)
baseRepo, err := gotOpts.BaseRepo()
if tt.wantErr != nil {
require.Equal(t, tt.wantErr, err)
return
}
require.True(t, ghrepo.IsSame(tt.wantRepo, baseRepo))
})
}
}
func Test_setRun_repo(t *testing.T) {
tests := []struct {
name string
opts *SetOptions
wantApp string
}{
{
name: "Actions",
opts: &SetOptions{
Application: "actions",
},
wantApp: "actions",
},
{
name: "Dependabot",
opts: &SetOptions{
Application: "dependabot",
},
wantApp: "dependabot",
},
{
name: "defaults to Actions",
opts: &SetOptions{
Application: "",
},
wantApp: "actions",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
reg.Register(httpmock.REST("GET", fmt.Sprintf("repos/owner/repo/%s/secrets/public-key", tt.wantApp)),
httpmock.JSONResponse(PubKey{ID: "123", Key: "CDjXqf7AJBXWhMczcy+Fs7JlACEptgceysutztHaFQI="}))
reg.Register(httpmock.REST("PUT", fmt.Sprintf("repos/owner/repo/%s/secrets/cool_secret", tt.wantApp)),
httpmock.StatusStringResponse(201, `{}`))
ios, _, _, _ := iostreams.Test()
opts := &SetOptions{
HttpClient: func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
},
Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil },
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("owner/repo")
},
IO: ios,
SecretName: "cool_secret",
Body: "a secret",
RandomOverride: fakeRandom,
Application: tt.opts.Application,
}
err := setRun(opts)
assert.NoError(t, err)
reg.Verify(t)
data, err := io.ReadAll(reg.Requests[1].Body)
assert.NoError(t, err)
var payload SecretPayload
err = json.Unmarshal(data, &payload)
assert.NoError(t, err)
assert.Equal(t, payload.KeyID, "123")
assert.Equal(t, payload.EncryptedValue, "UKYUCbHd0DJemxa3AOcZ6XcsBwALG9d4bpB8ZT0gSV39vl3BHiGSgj8zJapDxgB2BwqNqRhpjC4=")
})
}
}
func Test_setRun_env(t *testing.T) {
reg := &httpmock.Registry{}
reg.Register(httpmock.REST("GET", "repos/owner/repo/environments/development/secrets/public-key"),
httpmock.JSONResponse(PubKey{ID: "123", Key: "CDjXqf7AJBXWhMczcy+Fs7JlACEptgceysutztHaFQI="}))
reg.Register(httpmock.REST("PUT", "repos/owner/repo/environments/development/secrets/cool_secret"), httpmock.StatusStringResponse(201, `{}`))
ios, _, _, _ := iostreams.Test()
opts := &SetOptions{
HttpClient: func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
},
Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil },
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("owner/repo")
},
EnvName: "development",
IO: ios,
SecretName: "cool_secret",
Body: "a secret",
RandomOverride: fakeRandom,
}
err := setRun(opts)
assert.NoError(t, err)
reg.Verify(t)
data, err := io.ReadAll(reg.Requests[1].Body)
assert.NoError(t, err)
var payload SecretPayload
err = json.Unmarshal(data, &payload)
assert.NoError(t, err)
assert.Equal(t, payload.KeyID, "123")
assert.Equal(t, payload.EncryptedValue, "UKYUCbHd0DJemxa3AOcZ6XcsBwALG9d4bpB8ZT0gSV39vl3BHiGSgj8zJapDxgB2BwqNqRhpjC4=")
}
func Test_setRun_org(t *testing.T) {
tests := []struct {
name string
opts *SetOptions
wantVisibility shared.Visibility
wantRepositories []int64
wantDependabotRepositories []string
wantApp string
}{
{
name: "all vis",
opts: &SetOptions{
OrgName: "UmbrellaCorporation",
Visibility: shared.All,
},
wantApp: "actions",
},
{
name: "selected visibility",
opts: &SetOptions{
OrgName: "UmbrellaCorporation",
Visibility: shared.Selected,
RepositoryNames: []string{"birkin", "UmbrellaCorporation/wesker"},
},
wantRepositories: []int64{1, 2},
wantApp: "actions",
},
{
name: "no repos visibility",
opts: &SetOptions{
OrgName: "UmbrellaCorporation",
Visibility: shared.Selected,
RepositoryNames: []string{},
},
wantRepositories: []int64{},
wantApp: "actions",
},
{
name: "Dependabot",
opts: &SetOptions{
OrgName: "UmbrellaCorporation",
Visibility: shared.All,
Application: shared.Dependabot,
},
wantApp: "dependabot",
},
{
name: "Dependabot selected visibility",
opts: &SetOptions{
OrgName: "UmbrellaCorporation",
Visibility: shared.Selected,
Application: shared.Dependabot,
RepositoryNames: []string{"birkin", "UmbrellaCorporation/wesker"},
},
wantDependabotRepositories: []string{"1", "2"},
wantApp: "dependabot",
},
{
name: "Dependabot no repos visibility",
opts: &SetOptions{
OrgName: "UmbrellaCorporation",
Visibility: shared.Selected,
Application: shared.Dependabot,
RepositoryNames: []string{},
},
wantRepositories: []int64{},
wantApp: "dependabot",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
orgName := tt.opts.OrgName
reg.Register(httpmock.REST("GET",
fmt.Sprintf("orgs/%s/%s/secrets/public-key", orgName, tt.wantApp)),
httpmock.JSONResponse(PubKey{ID: "123", Key: "CDjXqf7AJBXWhMczcy+Fs7JlACEptgceysutztHaFQI="}))
reg.Register(httpmock.REST("PUT",
fmt.Sprintf("orgs/%s/%s/secrets/cool_secret", orgName, tt.wantApp)),
httpmock.StatusStringResponse(201, `{}`))
if len(tt.opts.RepositoryNames) > 0 {
reg.Register(httpmock.GraphQL(`query MapRepositoryNames\b`),
httpmock.StringResponse(`{"data":{"repo_0001":{"databaseId":1},"repo_0002":{"databaseId":2}}}`))
}
ios, _, _, _ := iostreams.Test()
tt.opts.BaseRepo = func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("owner/repo")
}
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
tt.opts.Config = func() (gh.Config, error) {
return config.NewBlankConfig(), nil
}
tt.opts.IO = ios
tt.opts.SecretName = "cool_secret"
tt.opts.Body = "a secret"
tt.opts.RandomOverride = fakeRandom
err := setRun(tt.opts)
assert.NoError(t, err)
reg.Verify(t)
data, err := io.ReadAll(reg.Requests[len(reg.Requests)-1].Body)
assert.NoError(t, err)
if tt.opts.Application == shared.Dependabot {
var payload DependabotSecretPayload
err = json.Unmarshal(data, &payload)
assert.NoError(t, err)
assert.Equal(t, payload.KeyID, "123")
assert.Equal(t, payload.EncryptedValue, "UKYUCbHd0DJemxa3AOcZ6XcsBwALG9d4bpB8ZT0gSV39vl3BHiGSgj8zJapDxgB2BwqNqRhpjC4=")
assert.Equal(t, payload.Visibility, tt.opts.Visibility)
assert.ElementsMatch(t, payload.Repositories, tt.wantDependabotRepositories)
} else {
var payload SecretPayload
err = json.Unmarshal(data, &payload)
assert.NoError(t, err)
assert.Equal(t, payload.KeyID, "123")
assert.Equal(t, payload.EncryptedValue, "UKYUCbHd0DJemxa3AOcZ6XcsBwALG9d4bpB8ZT0gSV39vl3BHiGSgj8zJapDxgB2BwqNqRhpjC4=")
assert.Equal(t, payload.Visibility, tt.opts.Visibility)
assert.ElementsMatch(t, payload.Repositories, tt.wantRepositories)
}
})
}
}
func Test_setRun_user(t *testing.T) {
tests := []struct {
name string
opts *SetOptions
wantVisibility shared.Visibility
wantRepositories []int64
}{
{
name: "all vis",
opts: &SetOptions{
UserSecrets: true,
Visibility: shared.All,
},
},
{
name: "selected visibility",
opts: &SetOptions{
UserSecrets: true,
Visibility: shared.Selected,
RepositoryNames: []string{"cli/cli", "github/hub"},
},
wantRepositories: []int64{212613049, 401025},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
reg.Register(httpmock.REST("GET", "user/codespaces/secrets/public-key"),
httpmock.JSONResponse(PubKey{ID: "123", Key: "CDjXqf7AJBXWhMczcy+Fs7JlACEptgceysutztHaFQI="}))
reg.Register(httpmock.REST("PUT", "user/codespaces/secrets/cool_secret"),
httpmock.StatusStringResponse(201, `{}`))
if len(tt.opts.RepositoryNames) > 0 {
reg.Register(httpmock.GraphQL(`query MapRepositoryNames\b`),
httpmock.StringResponse(`{"data":{"repo_0001":{"databaseId":212613049},"repo_0002":{"databaseId":401025}}}`))
}
ios, _, _, _ := iostreams.Test()
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
tt.opts.Config = func() (gh.Config, error) {
return config.NewBlankConfig(), nil
}
tt.opts.IO = ios
tt.opts.SecretName = "cool_secret"
tt.opts.Body = "a secret"
tt.opts.RandomOverride = fakeRandom
err := setRun(tt.opts)
assert.NoError(t, err)
reg.Verify(t)
data, err := io.ReadAll(reg.Requests[len(reg.Requests)-1].Body)
assert.NoError(t, err)
var payload SecretPayload
err = json.Unmarshal(data, &payload)
assert.NoError(t, err)
assert.Equal(t, payload.KeyID, "123")
assert.Equal(t, payload.EncryptedValue, "UKYUCbHd0DJemxa3AOcZ6XcsBwALG9d4bpB8ZT0gSV39vl3BHiGSgj8zJapDxgB2BwqNqRhpjC4=")
assert.ElementsMatch(t, payload.Repositories, tt.wantRepositories)
})
}
}
func Test_setRun_shouldNotStore(t *testing.T) {
reg := &httpmock.Registry{}
defer reg.Verify(t)
reg.Register(httpmock.REST("GET", "repos/owner/repo/actions/secrets/public-key"),
httpmock.JSONResponse(PubKey{ID: "123", Key: "CDjXqf7AJBXWhMczcy+Fs7JlACEptgceysutztHaFQI="}))
ios, _, stdout, stderr := iostreams.Test()
opts := &SetOptions{
HttpClient: func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
},
Config: func() (gh.Config, error) {
return config.NewBlankConfig(), nil
},
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.FromFullName("owner/repo")
},
IO: ios,
Body: "a secret",
DoNotStore: true,
RandomOverride: fakeRandom,
}
err := setRun(opts)
assert.NoError(t, err)
assert.Equal(t, "UKYUCbHd0DJemxa3AOcZ6XcsBwALG9d4bpB8ZT0gSV39vl3BHiGSgj8zJapDxgB2BwqNqRhpjC4=\n", stdout.String())
assert.Equal(t, "", stderr.String())
}
func Test_getBody(t *testing.T) {
tests := []struct {
name string
bodyArg string
want string
stdin string
}{
{
name: "literal value",
bodyArg: "a secret",
want: "a secret",
},
{
name: "from stdin",
want: "a secret",
stdin: "a secret",
},
{
name: "from stdin with trailing newline character",
want: "a secret",
stdin: "a secret\n",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, stdin, _, _ := iostreams.Test()
ios.SetStdinTTY(false)
_, err := stdin.WriteString(tt.stdin)
assert.NoError(t, err)
body, err := getBody(&SetOptions{
Body: tt.bodyArg,
IO: ios,
})
assert.NoError(t, err)
assert.Equal(t, tt.want, string(body))
})
}
}
func Test_getBodyPrompt(t *testing.T) {
ios, _, _, _ := iostreams.Test()
ios.SetStdinTTY(true)
ios.SetStdoutTTY(true)
pm := prompter.NewMockPrompter(t)
pm.RegisterPassword("Paste your secret:", func(_ string) (string, error) {
return "cool secret", nil
})
body, err := getBody(&SetOptions{
IO: ios,
Prompter: pm,
})
assert.NoError(t, err)
assert.Equal(t, string(body), "cool secret")
}
func Test_getSecretsFromOptions(t *testing.T) {
genFile := func(s string) string {
f, err := os.CreateTemp("", "gh-env.*")
if err != nil {
t.Fatal(err)
return ""
}
defer f.Close()
t.Cleanup(func() {
_ = os.Remove(f.Name())
})
_, err = f.WriteString(s)
if err != nil {
t.Fatal(err)
}
return f.Name()
}
tests := []struct {
name string
opts SetOptions
isTTY bool
stdin string
want map[string]string
wantErr bool
}{
{
name: "secret from arg",
opts: SetOptions{
SecretName: "FOO",
Body: "bar",
EnvFile: "",
},
want: map[string]string{"FOO": "bar"},
},
{
name: "secrets from stdin",
opts: SetOptions{
Body: "",
EnvFile: "-",
},
stdin: `FOO=bar`,
want: map[string]string{"FOO": "bar"},
},
{
name: "secrets from file",
opts: SetOptions{
Body: "",
EnvFile: genFile(heredoc.Doc(`
FOO=bar
QUOTED="my value"
#IGNORED=true
export SHELL=bash
`)),
},
stdin: `FOO=bar`,
want: map[string]string{
"FOO": "bar",
"SHELL": "bash",
"QUOTED": "my value",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, stdin, _, _ := iostreams.Test()
ios.SetStdinTTY(tt.isTTY)
ios.SetStdoutTTY(tt.isTTY)
stdin.WriteString(tt.stdin)
opts := tt.opts
opts.IO = ios
gotSecrets, err := getSecretsFromOptions(&opts)
if err != nil {
if !tt.wantErr {
t.Fatalf("getSecretsFromOptions() error = %v, wantErr %v", err, tt.wantErr)
}
} else if tt.wantErr {
t.Fatalf("getSecretsFromOptions() error = %v, wantErr %v", err, tt.wantErr)
}
if len(gotSecrets) != len(tt.want) {
t.Fatalf("getSecretsFromOptions() = got %d secrets, want %d", len(gotSecrets), len(tt.want))
}
for k, v := range gotSecrets {
if tt.want[k] != string(v) {
t.Errorf("getSecretsFromOptions() %s = got %q, want %q", k, string(v), tt.want[k])
}
}
})
}
}
func fakeRandom() io.Reader {
return bytes.NewReader(bytes.Repeat([]byte{5}, 32))
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/secret/set/http.go | pkg/cmd/secret/set/http.go | package set
import (
"bytes"
"encoding/json"
"fmt"
"strconv"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmd/secret/shared"
)
type SecretPayload struct {
EncryptedValue string `json:"encrypted_value"`
Visibility string `json:"visibility,omitempty"`
Repositories []int64 `json:"selected_repository_ids,omitempty"`
KeyID string `json:"key_id"`
}
type DependabotSecretPayload struct {
EncryptedValue string `json:"encrypted_value"`
Visibility string `json:"visibility,omitempty"`
Repositories []string `json:"selected_repository_ids,omitempty"`
KeyID string `json:"key_id"`
}
type PubKey struct {
ID string `json:"key_id"`
Key string
}
func getPubKey(client *api.Client, host, path string) (*PubKey, error) {
pk := PubKey{}
err := client.REST(host, "GET", path, nil, &pk)
if err != nil {
return nil, err
}
return &pk, nil
}
func getOrgPublicKey(client *api.Client, host, orgName string, app shared.App) (*PubKey, error) {
return getPubKey(client, host, fmt.Sprintf("orgs/%s/%s/secrets/public-key", orgName, app))
}
func getUserPublicKey(client *api.Client, host string) (*PubKey, error) {
return getPubKey(client, host, "user/codespaces/secrets/public-key")
}
func getRepoPubKey(client *api.Client, repo ghrepo.Interface, app shared.App) (*PubKey, error) {
return getPubKey(client, repo.RepoHost(), fmt.Sprintf("repos/%s/%s/secrets/public-key",
ghrepo.FullName(repo), app))
}
func getEnvPubKey(client *api.Client, repo ghrepo.Interface, envName string) (*PubKey, error) {
return getPubKey(client, repo.RepoHost(), fmt.Sprintf("repos/%s/environments/%s/secrets/public-key",
ghrepo.FullName(repo), envName))
}
func putSecret(client *api.Client, host, path string, payload interface{}) error {
payloadBytes, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("failed to serialize: %w", err)
}
requestBody := bytes.NewReader(payloadBytes)
return client.REST(host, "PUT", path, requestBody, nil)
}
func putOrgSecret(client *api.Client, host string, pk *PubKey, orgName, visibility, secretName, eValue string, repositoryIDs []int64, app shared.App) error {
path := fmt.Sprintf("orgs/%s/%s/secrets/%s", orgName, app, secretName)
if app == shared.Dependabot {
repos := make([]string, len(repositoryIDs))
for i, id := range repositoryIDs {
repos[i] = strconv.FormatInt(id, 10)
}
payload := DependabotSecretPayload{
EncryptedValue: eValue,
KeyID: pk.ID,
Repositories: repos,
Visibility: visibility,
}
return putSecret(client, host, path, payload)
}
payload := SecretPayload{
EncryptedValue: eValue,
KeyID: pk.ID,
Repositories: repositoryIDs,
Visibility: visibility,
}
return putSecret(client, host, path, payload)
}
func putUserSecret(client *api.Client, host string, pk *PubKey, key, eValue string, repositoryIDs []int64) error {
payload := SecretPayload{
EncryptedValue: eValue,
KeyID: pk.ID,
Repositories: repositoryIDs,
}
path := fmt.Sprintf("user/codespaces/secrets/%s", key)
return putSecret(client, host, path, payload)
}
func putEnvSecret(client *api.Client, pk *PubKey, repo ghrepo.Interface, envName string, secretName, eValue string) error {
payload := SecretPayload{
EncryptedValue: eValue,
KeyID: pk.ID,
}
path := fmt.Sprintf("repos/%s/environments/%s/secrets/%s", ghrepo.FullName(repo), envName, secretName)
return putSecret(client, repo.RepoHost(), path, payload)
}
func putRepoSecret(client *api.Client, pk *PubKey, repo ghrepo.Interface, secretName, eValue string, app shared.App) error {
payload := SecretPayload{
EncryptedValue: eValue,
KeyID: pk.ID,
}
path := fmt.Sprintf("repos/%s/%s/secrets/%s", ghrepo.FullName(repo), app, secretName)
return putSecret(client, repo.RepoHost(), path, payload)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/secret/set/set.go | pkg/cmd/secret/set/set.go | package set
import (
"bytes"
"encoding/base64"
"errors"
"fmt"
"io"
"net/http"
"os"
"strings"
"github.com/cli/cli/v2/internal/prompter"
"github.com/MakeNowJust/heredoc"
"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/cmd/secret/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/joho/godotenv"
"github.com/spf13/cobra"
"golang.org/x/crypto/nacl/box"
)
type SetOptions struct {
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
Config func() (gh.Config, error)
BaseRepo func() (ghrepo.Interface, error)
Prompter prompter.Prompter
RandomOverride func() io.Reader
SecretName string
OrgName string
EnvName string
UserSecrets bool
Body string
DoNotStore bool
Visibility string
RepositoryNames []string
EnvFile string
Application string
}
func NewCmdSet(f *cmdutil.Factory, runF func(*SetOptions) error) *cobra.Command {
opts := &SetOptions{
IO: f.IOStreams,
Config: f.Config,
HttpClient: f.HttpClient,
Prompter: f.Prompter,
}
// It is possible for a user to say `--no-repos-selected=false --repos cli/cli` and that would be equivalent to not
// specifying the flag at all. We could avoid this by checking whether the flag was set at all, but it seems like
// more trouble than it's worth since anyone who does `--no-repos-selected=false` is gonna get what's coming to them.
var noRepositoriesSelected bool
cmd := &cobra.Command{
Use: "set <secret-name>",
Short: "Create or update secrets",
Long: heredoc.Doc(`
Set a value for a secret on one of the following levels:
- repository (default): available to GitHub Actions runs or Dependabot in a repository
- environment: available to GitHub Actions runs for a deployment environment in a repository
- organization: available to GitHub Actions runs, Dependabot, or Codespaces within an organization
- user: available to Codespaces for your user
Organization and user secrets can optionally be restricted to only be available to
specific repositories.
Secret values are locally encrypted before being sent to GitHub.
`),
Example: heredoc.Doc(`
# Paste secret value for the current repository in an interactive prompt
$ gh secret set MYSECRET
# Read secret value from an environment variable
$ gh secret set MYSECRET --body "$ENV_VALUE"
# Set secret for a specific remote repository
$ gh secret set MYSECRET --repo origin/repo --body "$ENV_VALUE"
# Read secret value from a file
$ gh secret set MYSECRET < myfile.txt
# Set secret for a deployment environment in the current repository
$ gh secret set MYSECRET --env myenvironment
# Set organization-level secret visible to both public and private repositories
$ gh secret set MYSECRET --org myOrg --visibility all
# Set organization-level secret visible to specific repositories
$ gh secret set MYSECRET --org myOrg --repos repo1,repo2,repo3
# Set organization-level secret visible to no repositories
$ gh secret set MYSECRET --org myOrg --no-repos-selected
# Set user-level secret for Codespaces
$ gh secret set MYSECRET --user
# Set repository-level secret for Dependabot
$ gh secret set MYSECRET --app dependabot
# Set multiple secrets imported from the ".env" file
$ gh secret set -f .env
# Set multiple secrets from stdin
$ gh secret set -f - < myfile.txt
`),
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
// If the user specified a repo directly, then we're using the OverrideBaseRepoFunc set by EnableRepoOverride
// So there's no reason to use the specialised BaseRepoFunc that requires remote disambiguation.
opts.BaseRepo = f.BaseRepo
isRepoUserProvided := cmd.Flags().Changed("repo") || os.Getenv("GH_REPO") != ""
if !isRepoUserProvided {
// If they haven't specified a repo directly, then we will wrap the BaseRepoFunc in one that errors if
// there might be multiple valid remotes.
opts.BaseRepo = shared.RequireNoAmbiguityBaseRepoFunc(opts.BaseRepo, f.Remotes)
// But if we are able to prompt, then we will wrap that up in a BaseRepoFunc that can prompt the user to
// resolve the ambiguity.
if opts.IO.CanPrompt() {
opts.BaseRepo = shared.PromptWhenAmbiguousBaseRepoFunc(opts.BaseRepo, f.IOStreams, f.Prompter)
}
}
if err := cmdutil.MutuallyExclusive("specify only one of `--org`, `--env`, or `--user`", opts.OrgName != "", opts.EnvName != "", opts.UserSecrets); err != nil {
return err
}
if err := cmdutil.MutuallyExclusive("specify only one of `--body` or `--env-file`", opts.Body != "", opts.EnvFile != ""); err != nil {
return err
}
if err := cmdutil.MutuallyExclusive("specify only one of `--env-file` or `--no-store`", opts.EnvFile != "", opts.DoNotStore); err != nil {
return err
}
if err := cmdutil.MutuallyExclusive("specify only one of `--repos` or `--no-repos-selected`", len(opts.RepositoryNames) > 0, noRepositoriesSelected); err != nil {
return err
}
if err := cmdutil.MutuallyExclusive("`--no-repos-selected` must be omitted when used with `--user`", opts.UserSecrets, noRepositoriesSelected); err != nil {
return err
}
if len(args) == 0 {
if !opts.DoNotStore && opts.EnvFile == "" {
return cmdutil.FlagErrorf("must pass name argument")
}
} else {
opts.SecretName = args[0]
}
if cmd.Flags().Changed("visibility") {
if opts.OrgName == "" {
return cmdutil.FlagErrorf("`--visibility` is only supported with `--org`")
}
if opts.Visibility != shared.Selected && len(opts.RepositoryNames) > 0 {
return cmdutil.FlagErrorf("`--repos` is only supported with `--visibility=selected`")
}
if opts.Visibility != shared.Selected && noRepositoriesSelected {
return cmdutil.FlagErrorf("`--no-repos-selected` is only supported with `--visibility=selected`")
}
if opts.Visibility == shared.Selected && (len(opts.RepositoryNames) == 0 && !noRepositoriesSelected) {
return cmdutil.FlagErrorf("`--repos` or `--no-repos-selected` required with `--visibility=selected`")
}
} else {
if len(opts.RepositoryNames) > 0 || noRepositoriesSelected {
opts.Visibility = shared.Selected
}
}
if runF != nil {
return runF(opts)
}
return setRun(opts)
},
}
cmd.Flags().StringVarP(&opts.OrgName, "org", "o", "", "Set `organization` secret")
cmd.Flags().StringVarP(&opts.EnvName, "env", "e", "", "Set deployment `environment` secret")
cmd.Flags().BoolVarP(&opts.UserSecrets, "user", "u", false, "Set a secret for your user")
cmdutil.StringEnumFlag(cmd, &opts.Visibility, "visibility", "v", shared.Private, []string{shared.All, shared.Private, shared.Selected}, "Set visibility for an organization secret")
cmd.Flags().StringSliceVarP(&opts.RepositoryNames, "repos", "r", []string{}, "List of `repositories` that can access an organization or user secret")
cmd.Flags().BoolVar(&noRepositoriesSelected, "no-repos-selected", false, "No repositories can access the organization secret")
cmd.Flags().StringVarP(&opts.Body, "body", "b", "", "The value for the secret (reads from standard input if not specified)")
cmd.Flags().BoolVar(&opts.DoNotStore, "no-store", false, "Print the encrypted, base64-encoded value instead of storing it on GitHub")
cmd.Flags().StringVarP(&opts.EnvFile, "env-file", "f", "", "Load secret names and values from a dotenv-formatted `file`")
cmdutil.StringEnumFlag(cmd, &opts.Application, "app", "a", "", []string{shared.Actions, shared.Codespaces, shared.Dependabot}, "Set the application for a secret")
return cmd
}
func setRun(opts *SetOptions) error {
orgName := opts.OrgName
envName := opts.EnvName
var host string
var baseRepo ghrepo.Interface
if orgName == "" && !opts.UserSecrets {
var err error
baseRepo, err = opts.BaseRepo()
if err != nil {
return err
}
host = baseRepo.RepoHost()
} else {
cfg, err := opts.Config()
if err != nil {
return err
}
host, _ = cfg.Authentication().DefaultHost()
}
secrets, err := getSecretsFromOptions(opts)
if err != nil {
return err
}
c, err := opts.HttpClient()
if err != nil {
return fmt.Errorf("could not create http client: %w", err)
}
client := api.NewClientFromHTTP(c)
secretEntity, err := shared.GetSecretEntity(orgName, envName, opts.UserSecrets)
if err != nil {
return err
}
secretApp, err := shared.GetSecretApp(opts.Application, secretEntity)
if err != nil {
return err
}
if !shared.IsSupportedSecretEntity(secretApp, secretEntity) {
return fmt.Errorf("%s secrets are not supported for %s", secretEntity, secretApp)
}
var pk *PubKey
switch secretEntity {
case shared.Organization:
pk, err = getOrgPublicKey(client, host, orgName, secretApp)
case shared.Environment:
pk, err = getEnvPubKey(client, baseRepo, envName)
case shared.User:
pk, err = getUserPublicKey(client, host)
default:
pk, err = getRepoPubKey(client, baseRepo, secretApp)
}
if err != nil {
return fmt.Errorf("failed to fetch public key: %w", err)
}
type repoNamesResult struct {
ids []int64
err error
}
repoNamesC := make(chan repoNamesResult, 1)
go func() {
if len(opts.RepositoryNames) == 0 {
repoNamesC <- repoNamesResult{}
return
}
repositoryIDs, err := mapRepoNamesToIDs(client, host, opts.OrgName, opts.RepositoryNames)
repoNamesC <- repoNamesResult{
ids: repositoryIDs,
err: err,
}
}()
var repositoryIDs []int64
if result := <-repoNamesC; result.err == nil {
repositoryIDs = result.ids
} else {
return result.err
}
setc := make(chan setResult)
for secretKey, secret := range secrets {
key := secretKey
value := secret
go func() {
setc <- setSecret(opts, pk, host, client, baseRepo, key, value, repositoryIDs, secretApp, secretEntity)
}()
}
var errs []error
cs := opts.IO.ColorScheme()
for i := 0; i < len(secrets); i++ {
result := <-setc
if result.err != nil {
errs = append(errs, result.err)
continue
}
if result.encrypted != "" {
fmt.Fprintln(opts.IO.Out, result.encrypted)
continue
}
if !opts.IO.IsStdoutTTY() {
continue
}
target := orgName
if opts.UserSecrets {
target = "your user"
} else if orgName == "" {
target = ghrepo.FullName(baseRepo)
}
fmt.Fprintf(opts.IO.Out, "%s Set %s secret %s for %s\n", cs.SuccessIcon(), secretApp.Title(), result.key, target)
}
return errors.Join(errs...)
}
type setResult struct {
key string
encrypted string
err error
}
func setSecret(opts *SetOptions, pk *PubKey, host string, client *api.Client, baseRepo ghrepo.Interface, secretKey string, secret []byte, repositoryIDs []int64, app shared.App, entity shared.SecretEntity) (res setResult) {
orgName := opts.OrgName
envName := opts.EnvName
res.key = secretKey
decodedPubKey, err := base64.StdEncoding.DecodeString(pk.Key)
if err != nil {
res.err = fmt.Errorf("failed to decode public key: %w", err)
return
}
var peersPubKey [32]byte
copy(peersPubKey[:], decodedPubKey[0:32])
var rand io.Reader
if opts.RandomOverride != nil {
rand = opts.RandomOverride()
}
eBody, err := box.SealAnonymous(nil, secret[:], &peersPubKey, rand)
if err != nil {
res.err = fmt.Errorf("failed to encrypt body: %w", err)
return
}
encoded := base64.StdEncoding.EncodeToString(eBody)
if opts.DoNotStore {
res.encrypted = encoded
return
}
switch entity {
case shared.Organization:
err = putOrgSecret(client, host, pk, orgName, opts.Visibility, secretKey, encoded, repositoryIDs, app)
case shared.Environment:
err = putEnvSecret(client, pk, baseRepo, envName, secretKey, encoded)
case shared.User:
err = putUserSecret(client, host, pk, secretKey, encoded, repositoryIDs)
default:
err = putRepoSecret(client, pk, baseRepo, secretKey, encoded, app)
}
if err != nil {
res.err = fmt.Errorf("failed to set secret %q: %w", secretKey, err)
return
}
return
}
func getSecretsFromOptions(opts *SetOptions) (map[string][]byte, error) {
secrets := make(map[string][]byte)
if opts.EnvFile != "" {
var r io.Reader
if opts.EnvFile == "-" {
defer opts.IO.In.Close()
r = opts.IO.In
} else {
f, err := os.Open(opts.EnvFile)
if err != nil {
return nil, fmt.Errorf("failed to open env file: %w", err)
}
defer f.Close()
r = f
}
envs, err := godotenv.Parse(r)
if err != nil {
return nil, fmt.Errorf("error parsing env file: %w", err)
}
if len(envs) == 0 {
return nil, fmt.Errorf("no secrets found in file")
}
for key, value := range envs {
secrets[key] = []byte(value)
}
return secrets, nil
}
body, err := getBody(opts)
if err != nil {
return nil, fmt.Errorf("did not understand secret body: %w", err)
}
secrets[opts.SecretName] = body
return secrets, nil
}
func getBody(opts *SetOptions) ([]byte, error) {
if opts.Body != "" {
return []byte(opts.Body), nil
}
if opts.IO.CanPrompt() {
bodyInput, err := opts.Prompter.Password("Paste your secret:")
if err != nil {
return nil, err
}
fmt.Fprintln(opts.IO.Out)
return []byte(bodyInput), nil
}
body, err := io.ReadAll(opts.IO.In)
if err != nil {
return nil, fmt.Errorf("failed to read from standard input: %w", err)
}
return bytes.TrimRight(body, "\r\n"), nil
}
func mapRepoNamesToIDs(client *api.Client, host, defaultOwner string, repositoryNames []string) ([]int64, error) {
repos := make([]ghrepo.Interface, 0, len(repositoryNames))
for _, repositoryName := range repositoryNames {
var repo ghrepo.Interface
if strings.Contains(repositoryName, "/") || defaultOwner == "" {
var err error
repo, err = ghrepo.FromFullNameWithHost(repositoryName, host)
if err != nil {
return nil, fmt.Errorf("invalid repository name: %w", err)
}
} else {
repo = ghrepo.NewWithHost(defaultOwner, repositoryName, host)
}
repos = append(repos, repo)
}
repositoryIDs, err := api.GetRepoIDs(client, host, repos)
if err != nil {
return nil, fmt.Errorf("failed to look up IDs for repositories %v: %w", repositoryNames, err)
}
return repositoryIDs, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/label/create.go | pkg/cmd/label/create.go | package label
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"math/rand"
"net/http"
"strings"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
var randomColors = []string{
"B60205",
"D93F0B",
"FBCA04",
"0E8A16",
"006B75",
"1D76DB",
"0052CC",
"5319E7",
"E99695",
"F9D0C4",
"FEF2C0",
"C2E0C6",
"BFDADC",
"C5DEF5",
"BFD4F2",
"D4C5F9",
}
type createOptions struct {
BaseRepo func() (ghrepo.Interface, error)
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
Color string
Description string
Name string
Force bool
}
func newCmdCreate(f *cmdutil.Factory, runF func(*createOptions) error) *cobra.Command {
opts := createOptions{
HttpClient: f.HttpClient,
IO: f.IOStreams,
}
cmd := &cobra.Command{
Use: "create <name>",
Short: "Create a new label",
Long: heredoc.Docf(`
Create a new label on GitHub, or update an existing one with %[1]s--force%[1]s.
Must specify name for the label. The description and color are optional.
If a color isn't provided, a random one will be chosen.
The label color needs to be 6 character hex value.
`, "`"),
Example: heredoc.Doc(`
# Create new bug label
$ gh label create bug --description "Something isn't working" --color E99695
`),
Args: cmdutil.ExactArgs(1, "cannot create label: name argument required"),
RunE: func(c *cobra.Command, args []string) error {
opts.BaseRepo = f.BaseRepo
opts.Name = args[0]
opts.Color = strings.TrimPrefix(opts.Color, "#")
if runF != nil {
return runF(&opts)
}
return createRun(&opts)
},
}
cmd.Flags().StringVarP(&opts.Description, "description", "d", "", "Description of the label")
cmd.Flags().StringVarP(&opts.Color, "color", "c", "", "Color of the label")
cmd.Flags().BoolVarP(&opts.Force, "force", "f", false, "Update the label color and description if label already exists")
return cmd
}
var errLabelAlreadyExists = errors.New("label already exists")
func createRun(opts *createOptions) error {
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
baseRepo, err := opts.BaseRepo()
if err != nil {
return err
}
if opts.Color == "" {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
opts.Color = randomColors[r.Intn(len(randomColors)-1)]
}
opts.IO.StartProgressIndicator()
err = createLabel(httpClient, baseRepo, opts)
opts.IO.StopProgressIndicator()
if err != nil {
if errors.Is(err, errLabelAlreadyExists) {
return fmt.Errorf("label with name %q already exists; use `--force` to update its color and description", opts.Name)
}
return err
}
if opts.IO.IsStdoutTTY() {
cs := opts.IO.ColorScheme()
successMsg := fmt.Sprintf("%s Label %q created in %s\n", cs.SuccessIcon(), opts.Name, ghrepo.FullName(baseRepo))
fmt.Fprint(opts.IO.Out, successMsg)
}
return nil
}
func createLabel(client *http.Client, repo ghrepo.Interface, opts *createOptions) error {
apiClient := api.NewClientFromHTTP(client)
path := fmt.Sprintf("repos/%s/%s/labels", repo.RepoOwner(), repo.RepoName())
requestByte, err := json.Marshal(map[string]string{
"name": opts.Name,
"description": opts.Description,
"color": opts.Color,
})
if err != nil {
return err
}
requestBody := bytes.NewReader(requestByte)
err = apiClient.REST(repo.RepoHost(), "POST", path, requestBody, nil)
if httpError, ok := err.(api.HTTPError); ok && isLabelAlreadyExistsError(httpError) {
err = errLabelAlreadyExists
}
if opts.Force && errors.Is(err, errLabelAlreadyExists) {
editOpts := editOptions{
Description: opts.Description,
Color: opts.Color,
Name: opts.Name,
}
return updateLabel(apiClient, repo, &editOpts)
}
return err
}
func updateLabel(apiClient *api.Client, repo ghrepo.Interface, opts *editOptions) error {
path := fmt.Sprintf("repos/%s/%s/labels/%s", repo.RepoOwner(), repo.RepoName(), opts.Name)
properties := map[string]string{}
if opts.Description != "" {
properties["description"] = opts.Description
}
if opts.Color != "" {
properties["color"] = opts.Color
}
if opts.NewName != "" {
properties["new_name"] = opts.NewName
}
requestByte, err := json.Marshal(properties)
if err != nil {
return err
}
requestBody := bytes.NewReader(requestByte)
err = apiClient.REST(repo.RepoHost(), "PATCH", path, requestBody, nil)
if httpError, ok := err.(api.HTTPError); ok && isLabelAlreadyExistsError(httpError) {
err = errLabelAlreadyExists
}
return err
}
func isLabelAlreadyExistsError(err api.HTTPError) bool {
return err.StatusCode == 422 && len(err.Errors) == 1 && err.Errors[0].Field == "name" && err.Errors[0].Code == "already_exists"
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/label/delete.go | pkg/cmd/label/delete.go | package label
import (
"fmt"
"net/http"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type iprompter interface {
ConfirmDeletion(string) error
}
type deleteOptions struct {
BaseRepo func() (ghrepo.Interface, error)
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
Prompter iprompter
Name string
Confirmed bool
}
func newCmdDelete(f *cmdutil.Factory, runF func(*deleteOptions) error) *cobra.Command {
opts := deleteOptions{
HttpClient: f.HttpClient,
IO: f.IOStreams,
Prompter: f.Prompter,
}
cmd := &cobra.Command{
Use: "delete <name>",
Short: "Delete a label from a repository",
Args: cmdutil.ExactArgs(1, "cannot delete label: name argument required"),
RunE: func(c *cobra.Command, args []string) error {
// support `-R, --repo` override
opts.BaseRepo = f.BaseRepo
opts.Name = 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, "Confirm deletion without prompting")
_ = cmd.Flags().MarkDeprecated("confirm", "use `--yes` instead")
cmd.Flags().BoolVar(&opts.Confirmed, "yes", false, "Confirm deletion without prompting")
return cmd
}
func deleteRun(opts *deleteOptions) error {
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
baseRepo, err := opts.BaseRepo()
if err != nil {
return err
}
if !opts.Confirmed {
if err := opts.Prompter.ConfirmDeletion(opts.Name); err != nil {
return err
}
}
opts.IO.StartProgressIndicator()
err = deleteLabel(httpClient, baseRepo, opts.Name)
opts.IO.StopProgressIndicator()
if err != nil {
return err
}
if opts.IO.IsStdoutTTY() {
cs := opts.IO.ColorScheme()
successMsg := fmt.Sprintf("%s Label %q deleted from %s\n", cs.SuccessIcon(), opts.Name, ghrepo.FullName(baseRepo))
fmt.Fprint(opts.IO.Out, successMsg)
}
return nil
}
func deleteLabel(client *http.Client, repo ghrepo.Interface, name string) error {
apiClient := api.NewClientFromHTTP(client)
path := fmt.Sprintf("repos/%s/%s/labels/%s", repo.RepoOwner(), repo.RepoName(), name)
return apiClient.REST(repo.RepoHost(), "DELETE", path, nil, nil)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/label/create_test.go | pkg/cmd/label/create_test.go | package label
import (
"bytes"
"encoding/json"
"io"
"net/http"
"testing"
"github.com/cli/cli/v2/internal/ghrepo"
"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 TestNewCmdCreate(t *testing.T) {
tests := []struct {
name string
input string
output createOptions
wantErr bool
errMsg string
}{
{
name: "no argument",
input: "",
wantErr: true,
errMsg: "cannot create label: name argument required",
},
{
name: "name argument",
input: "test",
output: createOptions{Name: "test"},
},
{
name: "description flag",
input: "test --description 'some description'",
output: createOptions{Name: "test", Description: "some description"},
},
{
name: "color flag",
input: "test --color FFFFFF",
output: createOptions{Name: "test", Color: "FFFFFF"},
},
{
name: "color flag with pound sign",
input: "test --color '#AAAAAA'",
output: createOptions{Name: "test", Color: "AAAAAA"},
},
}
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.input)
assert.NoError(t, err)
var gotOpts *createOptions
cmd := newCmdCreate(f, func(opts *createOptions) 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.wantErr {
assert.EqualError(t, err, tt.errMsg)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.output.Color, gotOpts.Color)
assert.Equal(t, tt.output.Description, gotOpts.Description)
assert.Equal(t, tt.output.Name, gotOpts.Name)
})
}
}
func TestCreateRun(t *testing.T) {
tests := []struct {
name string
tty bool
opts *createOptions
httpStubs func(*httpmock.Registry)
wantStdout string
}{
{
name: "creates label",
tty: true,
opts: &createOptions{Name: "test", Description: "some description"},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("POST", "repos/OWNER/REPO/labels"),
httpmock.StatusStringResponse(201, "{}"),
)
},
wantStdout: "✓ Label \"test\" created in OWNER/REPO\n",
},
{
name: "creates label notty",
tty: false,
opts: &createOptions{Name: "test", Description: "some description"},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("POST", "repos/OWNER/REPO/labels"),
httpmock.StatusStringResponse(201, "{}"),
)
},
wantStdout: "",
},
{
name: "creates existing label",
opts: &createOptions{Name: "test", Description: "some description", Force: true},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("POST", "repos/OWNER/REPO/labels"),
httpmock.WithHeader(
httpmock.StatusStringResponse(422, `{"message":"Validation Failed","errors":[{"resource":"Label","code":"already_exists","field":"name"}]}`),
"Content-Type",
"application/json",
),
)
reg.Register(
httpmock.REST("PATCH", "repos/OWNER/REPO/labels/test"),
httpmock.StatusStringResponse(201, "{}"),
)
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
if tt.httpStubs != nil {
tt.httpStubs(reg)
}
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
ios, _, stdout, _ := iostreams.Test()
ios.SetStdoutTTY(tt.tty)
ios.SetStdinTTY(tt.tty)
ios.SetStderrTTY(tt.tty)
tt.opts.IO = ios
tt.opts.BaseRepo = func() (ghrepo.Interface, error) {
return ghrepo.New("OWNER", "REPO"), nil
}
defer reg.Verify(t)
err := createRun(tt.opts)
assert.NoError(t, err)
assert.Equal(t, tt.wantStdout, stdout.String())
bodyBytes, _ := io.ReadAll(reg.Requests[0].Body)
reqBody := map[string]string{}
err = json.Unmarshal(bodyBytes, &reqBody)
assert.NoError(t, err)
assert.NotEqual(t, "", reqBody["color"])
assert.Equal(t, "some description", reqBody["description"])
assert.Equal(t, "test", reqBody["name"])
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/label/edit.go | pkg/cmd/label/edit.go | package label
import (
"errors"
"fmt"
"net/http"
"strings"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type editOptions struct {
BaseRepo func() (ghrepo.Interface, error)
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
Color string
Description string
Name string
NewName string
}
func newCmdEdit(f *cmdutil.Factory, runF func(*editOptions) error) *cobra.Command {
opts := editOptions{
HttpClient: f.HttpClient,
IO: f.IOStreams,
}
cmd := &cobra.Command{
Use: "edit <name>",
Short: "Edit a label",
Long: heredoc.Docf(`
Update a label on GitHub.
A label can be renamed using the %[1]s--name%[1]s flag.
The label color needs to be 6 character hex value.
`, "`"),
Example: heredoc.Doc(`
# Update the color of the bug label
$ gh label edit bug --color FF0000
# Rename and edit the description of the bug label
$ gh label edit bug --name big-bug --description "Bigger than normal bug"
`),
Args: cmdutil.ExactArgs(1, "cannot update label: name argument required"),
RunE: func(c *cobra.Command, args []string) error {
opts.BaseRepo = f.BaseRepo
opts.Name = args[0]
opts.Color = strings.TrimPrefix(opts.Color, "#")
if opts.Description == "" &&
opts.Color == "" &&
opts.NewName == "" {
return cmdutil.FlagErrorf("specify at least one of `--color`, `--description`, or `--name`")
}
if runF != nil {
return runF(&opts)
}
return editRun(&opts)
},
}
cmd.Flags().StringVarP(&opts.Description, "description", "d", "", "Description of the label")
cmd.Flags().StringVarP(&opts.Color, "color", "c", "", "Color of the label")
cmd.Flags().StringVarP(&opts.NewName, "name", "n", "", "New name of the label")
return cmd
}
func editRun(opts *editOptions) error {
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
apiClient := api.NewClientFromHTTP(httpClient)
baseRepo, err := opts.BaseRepo()
if err != nil {
return err
}
opts.IO.StartProgressIndicator()
err = updateLabel(apiClient, baseRepo, opts)
opts.IO.StopProgressIndicator()
if err != nil {
if errors.Is(err, errLabelAlreadyExists) {
return fmt.Errorf("label with name %q already exists", opts.NewName)
}
return err
}
if opts.IO.IsStdoutTTY() {
cs := opts.IO.ColorScheme()
successMsg := fmt.Sprintf("%s Label %q updated in %s\n", cs.SuccessIcon(), opts.Name, ghrepo.FullName(baseRepo))
fmt.Fprint(opts.IO.Out, successMsg)
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/label/delete_test.go | pkg/cmd/label/delete_test.go | package label
import (
"bytes"
"net/http"
"testing"
"github.com/cli/cli/v2/internal/ghrepo"
"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: "no argument",
input: "",
wantErr: true,
wantErrMsg: "cannot delete label: name argument required",
},
{
name: "name argument",
tty: true,
input: "test",
output: deleteOptions{Name: "test"},
},
{
name: "confirm argument",
input: "test --yes",
output: deleteOptions{Name: "test", Confirmed: true},
},
{
name: "confirm no tty",
input: "test",
wantErr: true,
wantErrMsg: "--yes required when not running interactively",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
io, _, _, _ := iostreams.Test()
f := &cmdutil.Factory{
IOStreams: io,
}
io.SetStdinTTY(tt.tty)
io.SetStdoutTTY(tt.tty)
argv, err := shlex.Split(tt.input)
assert.NoError(t, err)
var gotOpts *deleteOptions
cmd := newCmdDelete(f, func(opts *deleteOptions) 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.wantErr {
assert.EqualError(t, err, tt.wantErrMsg)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.output.Name, gotOpts.Name)
})
}
}
func TestDeleteRun(t *testing.T) {
tests := []struct {
name string
tty bool
opts *deleteOptions
httpStubs func(*httpmock.Registry)
prompterStubs func(*prompter.PrompterMock)
wantStdout string
wantErr bool
errMsg string
}{
{
name: "deletes label",
tty: true,
opts: &deleteOptions{Name: "test"},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("DELETE", "repos/OWNER/REPO/labels/test"),
httpmock.StatusStringResponse(204, "{}"),
)
},
prompterStubs: func(pm *prompter.PrompterMock) {
pm.ConfirmDeletionFunc = func(_ string) error {
return nil
}
},
wantStdout: "✓ Label \"test\" deleted from OWNER/REPO\n",
},
{
name: "deletes label notty",
tty: false,
opts: &deleteOptions{Name: "test", Confirmed: true},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("DELETE", "repos/OWNER/REPO/labels/test"),
httpmock.StatusStringResponse(204, "{}"),
)
},
wantStdout: "",
},
{
name: "missing label",
tty: false,
opts: &deleteOptions{Name: "missing", Confirmed: true},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("DELETE", "repos/OWNER/REPO/labels/missing"),
httpmock.WithHeader(
httpmock.StatusStringResponse(422, `
{
"message":"Not Found"
}`),
"Content-Type",
"application/json",
),
)
},
wantErr: true,
errMsg: "HTTP 422: Not Found (https://api.github.com/repos/OWNER/REPO/labels/missing)",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
if tt.httpStubs != nil {
tt.httpStubs(reg)
}
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
pm := &prompter.PrompterMock{}
if tt.prompterStubs != nil {
tt.prompterStubs(pm)
}
tt.opts.Prompter = pm
io, _, stdout, _ := iostreams.Test()
io.SetStdoutTTY(tt.tty)
io.SetStdinTTY(tt.tty)
io.SetStderrTTY(tt.tty)
tt.opts.IO = io
tt.opts.BaseRepo = func() (ghrepo.Interface, error) {
return ghrepo.New("OWNER", "REPO"), nil
}
defer reg.Verify(t)
err := deleteRun(tt.opts)
if tt.wantErr {
assert.EqualError(t, err, tt.errMsg)
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/label/clone_test.go | pkg/cmd/label/clone_test.go | package label
import (
"bytes"
"net/http"
"testing"
"github.com/cli/cli/v2/internal/ghrepo"
"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 TestNewCmdClone(t *testing.T) {
tests := []struct {
name string
input string
output cloneOptions
wantErr bool
errMsg string
}{
{
name: "no argument",
input: "",
wantErr: true,
errMsg: "cannot clone labels: source-repository argument required",
},
{
name: "source-repository argument",
input: "OWNER/REPO",
output: cloneOptions{
SourceRepo: ghrepo.New("OWNER", "REPO"),
},
},
{
name: "force flag",
input: "OWNER/REPO --force",
output: cloneOptions{
SourceRepo: ghrepo.New("OWNER", "REPO"),
Force: true,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
io, _, _, _ := iostreams.Test()
f := &cmdutil.Factory{
IOStreams: io,
}
var gotOpts *cloneOptions
cmd := newCmdClone(f, func(opts *cloneOptions) error {
gotOpts = opts
return nil
})
argv, err := shlex.Split(tt.input)
assert.NoError(t, err)
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
_, err = cmd.ExecuteC()
if tt.wantErr {
assert.EqualError(t, err, tt.errMsg)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.output.SourceRepo, gotOpts.SourceRepo)
assert.Equal(t, tt.output.Force, gotOpts.Force)
})
}
}
func TestCloneRun(t *testing.T) {
tests := []struct {
name string
tty bool
opts *cloneOptions
httpStubs func(*httpmock.Registry)
wantStdout string
wantErr bool
wantErrMsg string
}{
{
name: "clones all labels",
tty: true,
opts: &cloneOptions{SourceRepo: ghrepo.New("cli", "cli")},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query LabelList\b`),
httpmock.GraphQLQuery(`
{
"data": {
"repository": {
"labels": {
"totalCount": 2,
"nodes": [
{
"name": "bug",
"color": "d73a4a",
"description": "Something isn't working"
},
{
"name": "docs",
"color": "6cafc9"
}
],
"pageInfo": {
"hasNextPage": false,
"endCursor": "abcd1234"
}
}
}
}
}`, func(s string, m map[string]interface{}) {
expected := map[string]interface{}{
"owner": "cli",
"repo": "cli",
"orderBy": map[string]interface{}{
"direction": "ASC",
"field": "CREATED_AT",
},
"query": "",
"limit": float64(100),
}
assert.Equal(t, expected, m)
}),
)
reg.Register(
httpmock.REST("POST", "repos/OWNER/REPO/labels"),
httpmock.StatusStringResponse(201, `
{
"name": "bug",
"color": "d73a4a",
"description": "Something isn't working"
}`),
)
reg.Register(
httpmock.REST("POST", "repos/OWNER/REPO/labels"),
httpmock.StatusStringResponse(201, `
{
"name": "docs",
"color": "6cafc9"
}`),
)
},
wantStdout: "✓ Cloned 2 labels from cli/cli to OWNER/REPO\n",
},
{
name: "clones one label",
tty: true,
opts: &cloneOptions{SourceRepo: ghrepo.New("cli", "cli")},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query LabelList\b`),
httpmock.StringResponse(`
{
"data": {
"repository": {
"labels": {
"totalCount": 1,
"nodes": [
{
"name": "bug",
"color": "d73a4a",
"description": "Something isn't working"
}
],
"pageInfo": {
"hasNextPage": false,
"endCursor": "abcd1234"
}
}
}
}
}`),
)
reg.Register(
httpmock.REST("POST", "repos/OWNER/REPO/labels"),
httpmock.StatusStringResponse(201, `
{
"name": "bug",
"color": "d73a4a",
"description": "Something isn't working"
}`),
)
},
wantStdout: "✓ Cloned 1 label from cli/cli to OWNER/REPO\n",
},
{
name: "has no labels",
tty: true,
opts: &cloneOptions{SourceRepo: ghrepo.New("cli", "cli")},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query LabelList\b`),
httpmock.StringResponse(`
{
"data": {
"repository": {
"labels": {
"totalCount": 0,
"nodes": [],
"pageInfo": {
"hasNextPage": false,
"endCursor": "abcd1234"
}
}
}
}
}`),
)
},
wantStdout: "✓ Cloned 0 labels from cli/cli to OWNER/REPO\n",
},
{
name: "clones some labels",
tty: true,
opts: &cloneOptions{SourceRepo: ghrepo.New("cli", "cli")},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query LabelList\b`),
httpmock.StringResponse(`
{
"data": {
"repository": {
"labels": {
"totalCount": 2,
"nodes": [
{
"name": "bug",
"color": "d73a4a",
"description": "Something isn't working"
},
{
"name": "docs",
"color": "6cafc9"
}
],
"pageInfo": {
"hasNextPage": false,
"endCursor": "abcd1234"
}
}
}
}
}`),
)
reg.Register(
httpmock.REST("POST", "repos/OWNER/REPO/labels"),
httpmock.StatusStringResponse(201, `
{
"name": "bug",
"color": "d73a4a",
"description": "Something isn't working"
}`),
)
reg.Register(
httpmock.REST("POST", "repos/OWNER/REPO/labels"),
httpmock.WithHeader(
httpmock.StatusStringResponse(422, `{"message":"Validation Failed","errors":[{"resource":"Label","code":"already_exists","field":"name"}]}`),
"Content-Type",
"application/json",
),
)
},
wantStdout: "! Cloned 1 label of 2 from cli/cli to OWNER/REPO\n",
},
{
name: "clones no labels",
tty: true,
opts: &cloneOptions{SourceRepo: ghrepo.New("cli", "cli")},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query LabelList\b`),
httpmock.StringResponse(`
{
"data": {
"repository": {
"labels": {
"totalCount": 2,
"nodes": [
{
"name": "bug",
"color": "d73a4a",
"description": "Something isn't working"
},
{
"name": "docs",
"color": "6cafc9"
}
],
"pageInfo": {
"hasNextPage": false,
"endCursor": "abcd1234"
}
}
}
}
}`),
)
reg.Register(
httpmock.REST("POST", "repos/OWNER/REPO/labels"),
httpmock.WithHeader(
httpmock.StatusStringResponse(422, `{"message":"Validation Failed","errors":[{"resource":"Label","code":"already_exists","field":"name"}]}`),
"Content-Type",
"application/json",
),
)
reg.Register(
httpmock.REST("POST", "repos/OWNER/REPO/labels"),
httpmock.WithHeader(
httpmock.StatusStringResponse(422, `{"message":"Validation Failed","errors":[{"resource":"Label","code":"already_exists","field":"name"}]}`),
"Content-Type",
"application/json",
),
)
},
wantStdout: "! Cloned 0 labels of 2 from cli/cli to OWNER/REPO\n",
},
{
name: "overwrites all labels",
tty: true,
opts: &cloneOptions{SourceRepo: ghrepo.New("cli", "cli"), Force: true},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query LabelList\b`),
httpmock.StringResponse(`
{
"data": {
"repository": {
"labels": {
"totalCount": 2,
"nodes": [
{
"name": "bug",
"color": "d73a4a",
"description": "Something isn't working"
},
{
"name": "docs",
"color": "6cafc9"
}
],
"pageInfo": {
"hasNextPage": false,
"endCursor": "abcd1234"
}
}
}
}
}`),
)
reg.Register(
httpmock.REST("POST", "repos/OWNER/REPO/labels"),
httpmock.WithHeader(
httpmock.StatusStringResponse(422, `{"message":"Validation Failed","errors":[{"resource":"Label","code":"already_exists","field":"name"}]}`),
"Content-Type",
"application/json",
),
)
reg.Register(
httpmock.REST("PATCH", "repos/OWNER/REPO/labels/bug"),
httpmock.StatusStringResponse(201, `
{
"color": "d73a4a",
"description": "Something isn't working"
}`),
)
reg.Register(
httpmock.REST("POST", "repos/OWNER/REPO/labels"),
httpmock.WithHeader(
httpmock.StatusStringResponse(422, `{"message":"Validation Failed","errors":[{"resource":"Label","code":"already_exists","field":"name"}]}`),
"Content-Type",
"application/json",
),
)
reg.Register(
httpmock.REST("PATCH", "repos/OWNER/REPO/labels/docs"),
httpmock.StatusStringResponse(201, `
{
"color": "6cafc9"
}`),
)
},
wantStdout: "✓ Cloned 2 labels from cli/cli to OWNER/REPO\n",
},
{
name: "list error",
tty: true,
opts: &cloneOptions{SourceRepo: ghrepo.New("cli", "invalid"), Force: true},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query LabelList\b`),
httpmock.WithHeader(
httpmock.StatusStringResponse(200, `
{
"data": {
"repository": null
},
"errors": [
{
"type": "NOT_FOUND",
"path": [
"repository"
],
"locations": [
{
"line": 3,
"column": 1
}
],
"message": "Could not resolve to a Repository with the name 'cli/invalid'."
}
]
}`),
"Content-Type",
"application/json",
),
)
},
wantErr: true,
wantErrMsg: "GraphQL: Could not resolve to a Repository with the name 'cli/invalid'. (repository)",
},
{
name: "create error",
tty: true,
opts: &cloneOptions{SourceRepo: ghrepo.New("cli", "cli"), Force: true},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query LabelList\b`),
httpmock.StringResponse(`
{
"data": {
"repository": {
"labels": {
"totalCount": 1,
"nodes": [
{
"name": "bug",
"color": "d73a4a",
"description": "Something isn't working"
}
],
"pageInfo": {
"hasNextPage": false,
"endCursor": "abcd1234"
}
}
}
}
}`),
)
reg.Register(
httpmock.REST("POST", "repos/OWNER/REPO/labels"),
httpmock.WithHeader(
httpmock.StatusStringResponse(422, `{"message":"Validation Failed","errors":[{"resource":"Label","code":"invalid","field":"color"}]}`),
"Content-Type",
"application/json",
),
)
},
wantErr: true,
wantErrMsg: "HTTP 422: Validation Failed (https://api.github.com/repos/OWNER/REPO/labels)\nLabel.color is invalid",
},
{
name: "clones pages of labels",
tty: true,
opts: &cloneOptions{SourceRepo: ghrepo.New("cli", "cli"), Force: true},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query LabelList\b`),
httpmock.GraphQLQuery(`
{
"data": {
"repository": {
"labels": {
"totalCount": 2,
"nodes": [
{
"name": "bug",
"color": "d73a4a",
"description": "Something isn't working"
}
],
"pageInfo": {
"hasNextPage": true,
"endCursor": "abcd1234"
}
}
}
}
}`, func(s string, m map[string]interface{}) {
assert.Equal(t, "cli", m["owner"])
assert.Equal(t, "cli", m["repo"])
assert.Equal(t, float64(100), m["limit"].(float64))
}),
)
reg.Register(
httpmock.GraphQL(`query LabelList\b`),
httpmock.GraphQLQuery(`
{
"data": {
"repository": {
"labels": {
"totalCount": 2,
"nodes": [
{
"name": "docs",
"color": "6cafc9"
}
],
"pageInfo": {
"hasNextPage": false,
"endCursor": "abcd1234"
}
}
}
}
}`, func(s string, m map[string]interface{}) {
assert.Equal(t, "cli", m["owner"])
assert.Equal(t, "cli", m["repo"])
assert.Equal(t, float64(100), m["limit"].(float64))
}),
)
reg.Register(
httpmock.REST("POST", "repos/OWNER/REPO/labels"),
httpmock.StatusStringResponse(201, `
{
"name": "bug",
"color": "d73a4a",
"description": "Something isn't working"
}`),
)
reg.Register(
httpmock.REST("POST", "repos/OWNER/REPO/labels"),
httpmock.StatusStringResponse(201, `
{
"name": "docs",
"color": "6cafc9"
}`),
)
},
wantStdout: "✓ Cloned 2 labels from cli/cli to OWNER/REPO\n",
},
}
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)
}
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
io, _, stdout, _ := iostreams.Test()
io.SetStdoutTTY(tt.tty)
io.SetStdinTTY(tt.tty)
io.SetStderrTTY(tt.tty)
tt.opts.IO = io
tt.opts.BaseRepo = func() (ghrepo.Interface, error) {
return ghrepo.New("OWNER", "REPO"), nil
}
err := cloneRun(tt.opts)
if tt.wantErr {
assert.EqualError(t, err, tt.wantErrMsg)
} else {
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/label/edit_test.go | pkg/cmd/label/edit_test.go | package label
import (
"bytes"
"net/http"
"testing"
"github.com/cli/cli/v2/internal/ghrepo"
"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 TestNewCmdEdit(t *testing.T) {
tests := []struct {
name string
input string
output editOptions
wantErr bool
errMsg string
}{
{
name: "no argument",
input: "",
wantErr: true,
errMsg: "cannot update label: name argument required",
},
{
name: "name argument",
input: "test",
wantErr: true,
errMsg: "specify at least one of `--color`, `--description`, or `--name`",
},
{
name: "description flag",
input: "test --description 'some description'",
output: editOptions{Name: "test", Description: "some description"},
},
{
name: "color flag",
input: "test --color FFFFFF",
output: editOptions{Name: "test", Color: "FFFFFF"},
},
{
name: "color flag with pound sign",
input: "test --color '#AAAAAA'",
output: editOptions{Name: "test", Color: "AAAAAA"},
},
{
name: "name flag",
input: "test --name test1",
output: editOptions{Name: "test", NewName: "test1"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
io, _, _, _ := iostreams.Test()
f := &cmdutil.Factory{
IOStreams: io,
}
argv, err := shlex.Split(tt.input)
assert.NoError(t, err)
var gotOpts *editOptions
cmd := newCmdEdit(f, func(opts *editOptions) 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.wantErr {
assert.EqualError(t, err, tt.errMsg)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.output.Color, gotOpts.Color)
assert.Equal(t, tt.output.Description, gotOpts.Description)
assert.Equal(t, tt.output.Name, gotOpts.Name)
assert.Equal(t, tt.output.NewName, gotOpts.NewName)
})
}
}
func TestEditRun(t *testing.T) {
tests := []struct {
name string
tty bool
opts *editOptions
httpStubs func(*httpmock.Registry)
wantStdout string
wantErrMsg string
}{
{
name: "updates label",
tty: true,
opts: &editOptions{Name: "test", Description: "some description"},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("PATCH", "repos/OWNER/REPO/labels/test"),
httpmock.StatusStringResponse(201, "{}"),
)
},
wantStdout: "✓ Label \"test\" updated in OWNER/REPO\n",
},
{
name: "updates label notty",
tty: false,
opts: &editOptions{Name: "test", Description: "some description"},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("PATCH", "repos/OWNER/REPO/labels/test"),
httpmock.StatusStringResponse(201, "{}"),
)
},
wantStdout: "",
},
{
name: "updates missing label",
opts: &editOptions{Name: "invalid", Description: "some description"},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.REST("PATCH", "repos/OWNER/REPO/labels/invalid"),
httpmock.WithHeader(
httpmock.StatusStringResponse(404, `{"message":"Not Found"}`),
"Content-Type",
"application/json",
),
)
},
wantErrMsg: "HTTP 404: Not Found (https://api.github.com/repos/OWNER/REPO/labels/invalid)",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
if tt.httpStubs != nil {
tt.httpStubs(reg)
}
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
io, _, stdout, _ := iostreams.Test()
io.SetStdoutTTY(tt.tty)
io.SetStdinTTY(tt.tty)
io.SetStderrTTY(tt.tty)
tt.opts.IO = io
tt.opts.BaseRepo = func() (ghrepo.Interface, error) {
return ghrepo.New("OWNER", "REPO"), nil
}
defer reg.Verify(t)
err := editRun(tt.opts)
if tt.wantErrMsg != "" {
assert.EqualError(t, err, tt.wantErrMsg)
} else {
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/label/clone.go | pkg/cmd/label/clone.go | package label
import (
"context"
"errors"
"fmt"
"net/http"
"sync/atomic"
"github.com/MakeNowJust/heredoc"
"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/spf13/cobra"
"golang.org/x/sync/errgroup"
)
type cloneOptions struct {
BaseRepo func() (ghrepo.Interface, error)
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
SourceRepo ghrepo.Interface
Force bool
}
func newCmdClone(f *cmdutil.Factory, runF func(*cloneOptions) error) *cobra.Command {
opts := cloneOptions{
HttpClient: f.HttpClient,
IO: f.IOStreams,
}
cmd := &cobra.Command{
Use: "clone <source-repository>",
Short: "Clones labels from one repository to another",
Long: heredoc.Docf(`
Clones labels from a source repository to a destination repository on GitHub.
By default, the destination repository is the current repository.
All labels from the source repository will be copied to the destination
repository. Labels in the destination repository that are not in the source
repository will not be deleted or modified.
Labels from the source repository that already exist in the destination
repository will be skipped. You can overwrite existing labels in the
destination repository using the %[1]s--force%[1]s flag.
`, "`"),
Example: heredoc.Doc(`
# Clone and overwrite labels from cli/cli repository into the current repository
$ gh label clone cli/cli --force
# Clone labels from cli/cli repository into a octocat/cli repository
$ gh label clone cli/cli --repo octocat/cli
`),
Args: cmdutil.ExactArgs(1, "cannot clone labels: source-repository argument required"),
RunE: func(c *cobra.Command, args []string) error {
var err error
opts.BaseRepo = f.BaseRepo
opts.SourceRepo, err = ghrepo.FromFullName(args[0])
if err != nil {
return err
}
if runF != nil {
return runF(&opts)
}
return cloneRun(&opts)
},
}
cmd.Flags().BoolVarP(&opts.Force, "force", "f", false, "Overwrite labels in the destination repository")
return cmd
}
func cloneRun(opts *cloneOptions) error {
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
baseRepo, err := opts.BaseRepo()
if err != nil {
return err
}
opts.IO.StartProgressIndicator()
successCount, totalCount, err := cloneLabels(httpClient, baseRepo, opts)
opts.IO.StopProgressIndicator()
if err != nil {
return err
}
if opts.IO.IsStdoutTTY() {
cs := opts.IO.ColorScheme()
pluralize := func(num int) string {
return text.Pluralize(num, "label")
}
successCount := int(successCount)
switch {
case successCount == totalCount:
fmt.Fprintf(opts.IO.Out, "%s Cloned %s from %s to %s\n", cs.SuccessIcon(), pluralize(successCount), ghrepo.FullName(opts.SourceRepo), ghrepo.FullName(baseRepo))
default:
fmt.Fprintf(opts.IO.Out, "%s Cloned %s of %d from %s to %s\n", cs.WarningIcon(), pluralize(successCount), totalCount, ghrepo.FullName(opts.SourceRepo), ghrepo.FullName(baseRepo))
}
}
return nil
}
func cloneLabels(client *http.Client, destination ghrepo.Interface, opts *cloneOptions) (successCount uint32, totalCount int, err error) {
successCount = 0
labels, totalCount, err := listLabels(client, opts.SourceRepo, listQueryOptions{Limit: -1})
if err != nil {
return
}
workers := 10
toCreate := make(chan createOptions)
wg, ctx := errgroup.WithContext(context.Background())
for i := 0; i < workers; i++ {
wg.Go(func() error {
for {
select {
case <-ctx.Done():
return nil
case l, ok := <-toCreate:
if !ok {
return nil
}
err := createLabel(client, destination, &l)
if err != nil {
if !errors.Is(err, errLabelAlreadyExists) {
return err
}
} else {
atomic.AddUint32(&successCount, 1)
}
}
}
})
}
for _, label := range labels {
createOpts := createOptions{
Name: label.Name,
Description: label.Description,
Color: label.Color,
Force: opts.Force,
}
toCreate <- createOpts
}
close(toCreate)
err = wg.Wait()
return
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/label/shared.go | pkg/cmd/label/shared.go | package label
import (
"time"
"github.com/cli/cli/v2/pkg/cmdutil"
)
var labelFields = []string{
"color",
"createdAt",
"description",
"id",
"isDefault",
"name",
"updatedAt",
"url",
}
type label struct {
Color string `json:"color"`
CreatedAt time.Time `json:"createdAt"`
Description string `json:"description"`
ID string `json:"id"`
IsDefault bool `json:"isDefault"`
Name string `json:"name"`
URL string `json:"url"`
UpdatedAt time.Time `json:"updatedAt"`
}
func (l *label) ExportData(fields []string) map[string]interface{} {
return cmdutil.StructExportData(l, fields)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/label/list_test.go | pkg/cmd/label/list_test.go | package label
import (
"bytes"
"net/http"
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/browser"
"github.com/cli/cli/v2/internal/ghrepo"
"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 TestNewCmdList(t *testing.T) {
tests := []struct {
name string
input string
output listOptions
wantErr bool
errMsg string
}{
{
name: "no argument",
input: "",
output: listOptions{Query: listQueryOptions{Limit: 30, Order: "asc", Sort: "created"}},
},
{
name: "limit flag",
input: "--limit 10",
output: listOptions{Query: listQueryOptions{Limit: 10, Order: "asc", Sort: "created"}},
},
{
name: "invalid limit flag",
input: "--limit 0",
wantErr: true,
errMsg: "invalid limit: 0",
},
{
name: "web flag",
input: "--web",
output: listOptions{Query: listQueryOptions{Limit: 30, Order: "asc", Sort: "created"}, WebMode: true},
},
{
name: "search flag",
input: "--search core",
output: listOptions{Query: listQueryOptions{Limit: 30, Query: "core", Order: "asc", Sort: "created"}},
},
{
name: "sort name flag",
input: "--sort name",
output: listOptions{Query: listQueryOptions{Limit: 30, Order: "asc", Sort: "name"}},
},
{
name: "sort created flag",
input: "--sort created",
output: listOptions{Query: listQueryOptions{Limit: 30, Order: "asc", Sort: "created"}},
},
{
name: "sort invalid flag",
input: "--sort invalid",
wantErr: true,
errMsg: `invalid argument "invalid" for "--sort" flag: valid values are {created|name}`,
},
{
name: "order asc flag",
input: "--order asc",
output: listOptions{Query: listQueryOptions{Limit: 30, Order: "asc", Sort: "created"}},
},
{
name: "order desc flag",
input: "--order desc",
output: listOptions{Query: listQueryOptions{Limit: 30, Order: "desc", Sort: "created"}},
},
{
name: "order invalid flag",
input: "--order invalid",
wantErr: true,
errMsg: `invalid argument "invalid" for "--order" flag: valid values are {asc|desc}`,
},
{
name: "search flag with sort flag",
input: "--search test --sort name",
wantErr: true,
errMsg: "cannot specify `--order` or `--sort` with `--search`",
},
{
name: "search flag with order flag",
input: "--search test --order asc",
wantErr: true,
errMsg: "cannot specify `--order` or `--sort` with `--search`",
},
{
name: "search flag with order and sort flags",
input: "--search test --order asc --sort name",
wantErr: true,
errMsg: "cannot specify `--order` or `--sort` with `--search`",
},
{
name: "json flag",
input: "--json name,color,description,createdAt",
output: listOptions{
Query: listQueryOptions{
Limit: 30,
Order: "asc",
Sort: "created",
fields: []string{
"name",
"color",
"description",
"createdAt",
},
},
},
},
{
name: "invalid json flag",
input: "--json invalid",
wantErr: true,
errMsg: heredoc.Doc(`
Unknown JSON field: "invalid"
Available fields:
color
createdAt
description
id
isDefault
name
updatedAt
url`),
},
}
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.input)
assert.NoError(t, err)
var gotOpts *listOptions
cmd := newCmdList(f, func(opts *listOptions) 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.wantErr {
assert.EqualError(t, err, tt.errMsg)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.output.Query.Limit, gotOpts.Query.Limit)
assert.Equal(t, tt.output.Query.Order, gotOpts.Query.Order)
assert.Equal(t, tt.output.Query.Query, tt.output.Query.Query)
assert.Equal(t, tt.output.Query.Sort, gotOpts.Query.Sort)
assert.Equal(t, tt.output.WebMode, gotOpts.WebMode)
})
}
}
func TestListRun(t *testing.T) {
tests := []struct {
name string
tty bool
opts *listOptions
httpStubs func(*httpmock.Registry)
wantErr bool
wantErrMsg string
wantStdout string
wantStderr string
}{
{
name: "lists labels",
tty: true,
opts: &listOptions{},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query LabelList\b`),
httpmock.StringResponse(`
{
"data": {
"repository": {
"labels": {
"totalCount": 2,
"nodes": [
{
"name": "bug",
"color": "d73a4a",
"description": "This is a bug label"
},
{
"name": "docs",
"color": "ffa8da",
"description": "This is a docs label"
}
],
"pageInfo": {
"hasNextPage": false,
"endCursor": "Y3Vyc29yOnYyOpK5MjAxOS0xMC0xMVQwMTozODowMyswODowMM5f3HZq"
}
}
}
}
}`,
),
)
},
wantStdout: heredoc.Doc(`
Showing 2 of 2 labels in OWNER/REPO
NAME DESCRIPTION COLOR
bug This is a bug label #d73a4a
docs This is a docs label #ffa8da
`),
},
{
name: "lists labels notty",
tty: false,
opts: &listOptions{},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query LabelList\b`),
httpmock.StringResponse(`
{
"data": {
"repository": {
"labels": {
"totalCount": 2,
"nodes": [
{
"name": "bug",
"color": "d73a4a",
"description": "This is a bug label"
},
{
"name": "docs",
"color": "ffa8da",
"description": "This is a docs label"
}
],
"pageInfo": {
"hasNextPage": false,
"endCursor": "Y3Vyc29yOnYyOpK5MjAxOS0xMC0xMVQwMTozODowMyswODowMM5f3HZq"
}
}
}
}
}`,
),
)
},
wantStdout: "bug\tThis is a bug label\t#d73a4a\ndocs\tThis is a docs label\t#ffa8da\n",
},
{
name: "empty label list",
tty: true,
opts: &listOptions{},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query LabelList\b`),
httpmock.StringResponse(`
{"data":{"repository":{"labels":{"totalCount":0,"nodes":[],"pageInfo":{"hasNextPage":false,"endCursor":null}}}}}`,
),
)
},
wantErr: true,
wantErrMsg: "no labels found in OWNER/REPO",
},
{
name: "empty label list search",
tty: true,
opts: &listOptions{Query: listQueryOptions{Query: "test"}},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query LabelList\b`),
httpmock.StringResponse(`
{"data":{"repository":{"labels":{"totalCount":0,"nodes":[],"pageInfo":{"hasNextPage":false,"endCursor":null}}}}}`,
),
)
},
wantErr: true,
wantErrMsg: "no labels in OWNER/REPO matched your search",
},
{
name: "web mode",
tty: true,
opts: &listOptions{WebMode: true},
wantStderr: "Opening https://github.com/OWNER/REPO/labels in your browser.\n",
},
{
name: "order by name ascending",
tty: true,
opts: &listOptions{
Query: listQueryOptions{
Limit: 30,
Order: "asc",
Sort: "name",
},
},
httpStubs: func(reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query LabelList\b`),
httpmock.GraphQLQuery(`
{
"data": {
"repository": {
"labels": {
"totalCount": 2,
"nodes": [
{
"name": "bug",
"color": "d73a4a",
"description": "This is a bug label",
"createdAt": "2022-04-20T06:17:50Z"
},
{
"name": "docs",
"color": "ffa8da",
"description": "This is a docs label",
"createdAt": "2022-04-20T06:17:49Z"
}
],
"pageInfo": {
"hasNextPage": false,
"endCursor": "Y3Vyc29yOnYyOpK5MjAxOS0xMC0xMVQwMTozODowMyswODowMM5f3HZq"
}
}
}
}
}`, func(s string, m map[string]interface{}) {
assert.Equal(t, "OWNER", m["owner"])
assert.Equal(t, "REPO", m["repo"])
assert.Equal(t, float64(30), m["limit"].(float64))
assert.Equal(t, map[string]interface{}{"direction": "ASC", "field": "NAME"}, m["orderBy"])
}),
)
},
wantStdout: heredoc.Doc(`
Showing 2 of 2 labels in OWNER/REPO
NAME DESCRIPTION COLOR
bug This is a bug label #d73a4a
docs This is a docs label #ffa8da
`),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
if tt.httpStubs != nil {
tt.httpStubs(reg)
}
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdoutTTY(tt.tty)
ios.SetStdinTTY(tt.tty)
ios.SetStderrTTY(tt.tty)
tt.opts.IO = ios
tt.opts.Browser = &browser.Stub{}
tt.opts.BaseRepo = func() (ghrepo.Interface, error) {
return ghrepo.New("OWNER", "REPO"), nil
}
defer reg.Verify(t)
err := listRun(tt.opts)
if tt.wantErr {
if tt.wantErrMsg != "" {
assert.EqualError(t, err, tt.wantErrMsg)
} else {
assert.Error(t, err)
}
} 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/label/list.go | pkg/cmd/label/list.go | package label
import (
"fmt"
"net/http"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/browser"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/tableprinter"
"github.com/cli/cli/v2/internal/text"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/spf13/cobra"
)
type listOptions struct {
BaseRepo func() (ghrepo.Interface, error)
Browser browser.Browser
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
Exporter cmdutil.Exporter
Query listQueryOptions
WebMode bool
}
func newCmdList(f *cmdutil.Factory, runF func(*listOptions) error) *cobra.Command {
opts := listOptions{
Browser: f.Browser,
HttpClient: f.HttpClient,
IO: f.IOStreams,
}
cmd := &cobra.Command{
Use: "list",
Short: "List labels in a repository",
Long: heredoc.Docf(`
Display labels in a GitHub repository.
When using the %[1]s--search%[1]s flag results are sorted by best match of the query.
This behavior cannot be configured with the %[1]s--order%[1]s or %[1]s--sort%[1]s flags.
`, "`"),
Example: heredoc.Doc(`
# Sort labels by name
$ gh label list --sort name
# Find labels with "bug" in the name or description
$ gh label list --search bug
`),
Args: cobra.NoArgs,
Aliases: []string{"ls"},
RunE: func(c *cobra.Command, args []string) error {
// support `-R, --repo` override
opts.BaseRepo = f.BaseRepo
if opts.Query.Limit < 1 {
return cmdutil.FlagErrorf("invalid limit: %v", opts.Query.Limit)
}
if opts.Query.Query != "" &&
(c.Flags().Changed("order") || c.Flags().Changed("sort")) {
return cmdutil.FlagErrorf("cannot specify `--order` or `--sort` with `--search`")
}
if runF != nil {
return runF(&opts)
}
return listRun(&opts)
},
}
cmd.Flags().BoolVarP(&opts.WebMode, "web", "w", false, "List labels in the web browser")
cmd.Flags().IntVarP(&opts.Query.Limit, "limit", "L", 30, "Maximum number of labels to fetch")
cmd.Flags().StringVarP(&opts.Query.Query, "search", "S", "", "Search label names and descriptions")
cmdutil.StringEnumFlag(cmd, &opts.Query.Order, "order", "", defaultOrder, []string{"asc", "desc"}, "Order of labels returned")
cmdutil.StringEnumFlag(cmd, &opts.Query.Sort, "sort", "", defaultSort, []string{"created", "name"}, "Sort fetched labels")
cmdutil.AddJSONFlags(cmd, &opts.Exporter, labelFields)
return cmd
}
func listRun(opts *listOptions) error {
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
baseRepo, err := opts.BaseRepo()
if err != nil {
return err
}
if opts.WebMode {
labelListURL := ghrepo.GenerateRepoURL(baseRepo, "labels")
if opts.IO.IsStdoutTTY() {
fmt.Fprintf(opts.IO.ErrOut, "Opening %s in your browser.\n", text.DisplayURL(labelListURL))
}
return opts.Browser.Browse(labelListURL)
}
if opts.Exporter != nil {
opts.Query.fields = opts.Exporter.Fields()
}
opts.IO.StartProgressIndicator()
labels, totalCount, err := listLabels(httpClient, baseRepo, opts.Query)
opts.IO.StopProgressIndicator()
if err != nil {
return err
}
if len(labels) == 0 {
if opts.Query.Query != "" {
return cmdutil.NewNoResultsError(fmt.Sprintf("no labels in %s matched your search", ghrepo.FullName(baseRepo)))
}
return cmdutil.NewNoResultsError(fmt.Sprintf("no labels found in %s", ghrepo.FullName(baseRepo)))
}
if opts.Exporter != nil {
return opts.Exporter.Write(opts.IO, labels)
}
if opts.IO.IsStdoutTTY() {
title := listHeader(ghrepo.FullName(baseRepo), len(labels), totalCount)
fmt.Fprintf(opts.IO.Out, "\n%s\n\n", title)
}
return printLabels(opts.IO, labels)
}
func printLabels(io *iostreams.IOStreams, labels []label) error {
cs := io.ColorScheme()
table := tableprinter.New(io, tableprinter.WithHeader("NAME", "DESCRIPTION", "COLOR"))
for _, label := range labels {
// Colorize the label using tableprinter's WithColor function for it to handle non-TTY situations
labelColor := tableprinter.WithColor(func(s string) string {
return cs.Label(label.Color, s)
})
table.AddField(label.Name, labelColor)
table.AddField(label.Description)
table.AddField("#" + label.Color)
table.EndRow()
}
return table.Render()
}
func listHeader(repoName string, count int, totalCount int) string {
return fmt.Sprintf("Showing %d of %s in %s", count, text.Pluralize(totalCount, "label"), repoName)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/label/http_test.go | pkg/cmd/label/http_test.go | package label
import (
"net/http"
"testing"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/stretchr/testify/assert"
)
func TestLabelList_pagination(t *testing.T) {
reg := &httpmock.Registry{}
client := &http.Client{Transport: reg}
reg.Register(
httpmock.GraphQL(`query LabelList\b`),
httpmock.StringResponse(`
{
"data": {
"repository": {
"labels": {
"totalCount": 2,
"nodes": [
{
"name": "bug",
"color": "d73a4a",
"description": "This is a bug label"
}
],
"pageInfo": {
"hasNextPage": true,
"endCursor": "Y3Vyc29yOnYyOpK5MjAxOS0xMC0xMVQwMTozODowMyswODowMM5f3HZq"
}
}
}
}
}`),
)
reg.Register(
httpmock.GraphQL(`query LabelList\b`),
httpmock.StringResponse(`
{
"data": {
"repository": {
"labels": {
"totalCount": 2,
"nodes": [
{
"name": "docs",
"color": "ffa8da",
"description": "This is a docs label"
}
],
"pageInfo": {
"hasNextPage": false,
"endCursor": "Y3Vyc29yOnYyOpK5MjAyMi0wMS0zMVQxODo1NTo1MiswODowMM7hiAL3"
}
}
}
}
}`),
)
repo := ghrepo.New("OWNER", "REPO")
labels, totalCount, err := listLabels(client, repo, listQueryOptions{Limit: 10})
assert.NoError(t, err)
assert.Equal(t, 2, totalCount)
assert.Equal(t, 2, len(labels))
assert.Equal(t, "bug", labels[0].Name)
assert.Equal(t, "d73a4a", labels[0].Color)
assert.Equal(t, "This is a bug label", labels[0].Description)
assert.Equal(t, "docs", labels[1].Name)
assert.Equal(t, "ffa8da", labels[1].Color)
assert.Equal(t, "This is a docs label", labels[1].Description)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/label/http.go | pkg/cmd/label/http.go | package label
import (
"fmt"
"net/http"
"strings"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghrepo"
)
const (
maxPageSize = 100
defaultOrder = "asc"
defaultSort = "created"
)
var defaultFields = []string{
"color",
"description",
"name",
}
type listLabelsResponseData struct {
Repository struct {
Labels struct {
TotalCount int
Nodes []label
PageInfo struct {
HasNextPage bool
EndCursor string
}
}
}
}
type listQueryOptions struct {
Limit int
Query string
Order string
Sort string
fields []string
}
func (opts listQueryOptions) OrderBy() map[string]string {
// Set on copy to keep original intact.
if opts.Order == "" {
opts.Order = defaultOrder
}
if opts.Sort == "" {
opts.Sort = defaultSort
}
field := strings.ToUpper(opts.Sort)
if opts.Sort == "created" {
field = "CREATED_AT"
}
return map[string]string{
"direction": strings.ToUpper(opts.Order),
"field": field,
}
}
// listLabels lists the labels in the given repo. Pass -1 for limit to list all labels;
// otherwise, only that number of labels is returned for any number of pages.
func listLabels(client *http.Client, repo ghrepo.Interface, opts listQueryOptions) ([]label, int, error) {
if len(opts.fields) == 0 {
opts.fields = defaultFields
}
apiClient := api.NewClientFromHTTP(client)
fragment := fmt.Sprintf("fragment label on Label{%s}", strings.Join(opts.fields, ","))
query := fragment + `
query LabelList($owner: String!, $repo: String!, $limit: Int!, $endCursor: String, $query: String, $orderBy: LabelOrder) {
repository(owner: $owner, name: $repo) {
labels(first: $limit, after: $endCursor, query: $query, orderBy: $orderBy) {
totalCount,
nodes {
...label
}
pageInfo {
hasNextPage
endCursor
}
}
}
}`
variables := map[string]interface{}{
"owner": repo.RepoOwner(),
"repo": repo.RepoName(),
"orderBy": opts.OrderBy(),
"query": opts.Query,
}
var labels []label
var totalCount int
loop:
for {
var response listLabelsResponseData
variables["limit"] = determinePageSize(opts.Limit - len(labels))
err := apiClient.GraphQL(repo.RepoHost(), query, variables, &response)
if err != nil {
return nil, 0, err
}
totalCount = response.Repository.Labels.TotalCount
for _, label := range response.Repository.Labels.Nodes {
labels = append(labels, label)
if len(labels) == opts.Limit {
break loop
}
}
if response.Repository.Labels.PageInfo.HasNextPage {
variables["endCursor"] = response.Repository.Labels.PageInfo.EndCursor
} else {
break
}
}
return labels, totalCount, nil
}
func determinePageSize(numRequestedItems int) int {
// If numRequestedItems is -1 then retrieve maxPageSize
if numRequestedItems < 0 || numRequestedItems > maxPageSize {
return maxPageSize
}
return numRequestedItems
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/label/label.go | pkg/cmd/label/label.go | package label
import (
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/spf13/cobra"
)
func NewCmdLabel(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "label <command>",
Short: "Manage labels",
Long: `Work with GitHub labels.`,
}
cmdutil.EnableRepoOverride(cmd, f)
cmd.AddCommand(newCmdList(f, nil))
cmd.AddCommand(newCmdCreate(f, nil))
cmd.AddCommand(newCmdClone(f, nil))
cmd.AddCommand(newCmdEdit(f, nil))
cmd.AddCommand(newCmdDelete(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/pr/pr.go | pkg/cmd/pr/pr.go | package pr
import (
"github.com/MakeNowJust/heredoc"
cmdLock "github.com/cli/cli/v2/pkg/cmd/issue/lock"
cmdCheckout "github.com/cli/cli/v2/pkg/cmd/pr/checkout"
cmdChecks "github.com/cli/cli/v2/pkg/cmd/pr/checks"
cmdClose "github.com/cli/cli/v2/pkg/cmd/pr/close"
cmdComment "github.com/cli/cli/v2/pkg/cmd/pr/comment"
cmdCreate "github.com/cli/cli/v2/pkg/cmd/pr/create"
cmdDiff "github.com/cli/cli/v2/pkg/cmd/pr/diff"
cmdEdit "github.com/cli/cli/v2/pkg/cmd/pr/edit"
cmdList "github.com/cli/cli/v2/pkg/cmd/pr/list"
cmdMerge "github.com/cli/cli/v2/pkg/cmd/pr/merge"
cmdReady "github.com/cli/cli/v2/pkg/cmd/pr/ready"
cmdReopen "github.com/cli/cli/v2/pkg/cmd/pr/reopen"
cmdRevert "github.com/cli/cli/v2/pkg/cmd/pr/revert"
cmdReview "github.com/cli/cli/v2/pkg/cmd/pr/review"
cmdStatus "github.com/cli/cli/v2/pkg/cmd/pr/status"
cmdUpdateBranch "github.com/cli/cli/v2/pkg/cmd/pr/update-branch"
cmdView "github.com/cli/cli/v2/pkg/cmd/pr/view"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/spf13/cobra"
)
func NewCmdPR(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "pr <command>",
Short: "Manage pull requests",
Long: "Work with GitHub pull requests.",
Example: heredoc.Doc(`
$ gh pr checkout 353
$ gh pr create --fill
$ gh pr view --web
`),
Annotations: map[string]string{
"help:arguments": heredoc.Doc(`
A pull request can be supplied as argument in any of the following formats:
- by number, e.g. "123";
- by URL, e.g. "https://github.com/OWNER/REPO/pull/123"; or
- by the name of its head branch, e.g. "patch-1" or "OWNER:patch-1".
`),
},
GroupID: "core",
}
cmdutil.EnableRepoOverride(cmd, f)
cmdutil.AddGroup(cmd, "General commands",
cmdList.NewCmdList(f, nil),
cmdCreate.NewCmdCreate(f, nil),
cmdStatus.NewCmdStatus(f, nil),
)
cmdutil.AddGroup(cmd, "Targeted commands",
cmdView.NewCmdView(f, nil),
cmdDiff.NewCmdDiff(f, nil),
cmdCheckout.NewCmdCheckout(f, nil),
cmdChecks.NewCmdChecks(f, nil),
cmdReview.NewCmdReview(f, nil),
cmdMerge.NewCmdMerge(f, nil),
cmdUpdateBranch.NewCmdUpdateBranch(f, nil),
cmdReady.NewCmdReady(f, nil),
cmdComment.NewCmdComment(f, nil),
cmdClose.NewCmdClose(f, nil),
cmdReopen.NewCmdReopen(f, nil),
cmdRevert.NewCmdRevert(f, nil),
cmdEdit.NewCmdEdit(f, nil),
cmdLock.NewCmdLock(f, cmd.Name(), nil),
cmdLock.NewCmdUnlock(f, cmd.Name(), nil),
)
return cmd
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/revert/revert.go | pkg/cmd/pr/revert/revert.go | package revert
import (
"fmt"
"net/http"
"github.com/cli/cli/v2/api"
"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/shurcooL/githubv4"
"github.com/spf13/cobra"
)
type RevertOptions struct {
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
Finder shared.PRFinder
SelectorArg string
Body string
BodySet bool
Title string
IsDraft bool
}
func NewCmdRevert(f *cmdutil.Factory, runF func(*RevertOptions) error) *cobra.Command {
opts := &RevertOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
}
var bodyFile string
cmd := &cobra.Command{
Use: "revert {<number> | <url> | <branch>}",
Short: "Revert a pull request",
Args: cmdutil.ExactArgs(1, "cannot revert pull request: number, url, or branch required"),
RunE: func(cmd *cobra.Command, args []string) error {
opts.Finder = shared.NewFinder(f)
if len(args) > 0 {
opts.SelectorArg = args[0]
}
bodyProvided := cmd.Flags().Changed("body")
bodyFileProvided := bodyFile != ""
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)
}
}
if runF != nil {
return runF(opts)
}
return revertRun(opts)
},
}
cmd.Flags().BoolVarP(&opts.IsDraft, "draft", "d", false, "Mark revert pull request as a draft")
cmd.Flags().StringVarP(&opts.Title, "title", "t", "", "Title for the revert pull request")
cmd.Flags().StringVarP(&opts.Body, "body", "b", "", "Body for the revert pull request")
cmd.Flags().StringVarP(&bodyFile, "body-file", "F", "", "Read body text from `file` (use \"-\" to read from standard input)")
return cmd
}
func revertRun(opts *RevertOptions) error {
cs := opts.IO.ColorScheme()
findOptions := shared.FindOptions{
Selector: opts.SelectorArg,
Fields: []string{"id", "number", "state", "title"},
}
pr, baseRepo, err := opts.Finder.Find(findOptions)
if err != nil {
return err
}
if pr.State != "MERGED" {
fmt.Fprintf(opts.IO.ErrOut, "%s Pull request %s#%d (%s) can't be reverted because it has not been merged\n", cs.FailureIcon(), ghrepo.FullName(baseRepo), pr.Number, pr.Title)
return cmdutil.SilentError
}
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
apiClient := api.NewClientFromHTTP(httpClient)
params := githubv4.RevertPullRequestInput{
PullRequestID: pr.ID,
Draft: githubv4.NewBoolean(githubv4.Boolean(opts.IsDraft)),
}
// Only set the Body field when opts.BodySet is true to avoid overriding
// GitHub's default revert body generation.
if opts.BodySet {
params.Body = githubv4.NewString(githubv4.String(opts.Body))
}
// Only set the Title field when opts.Title is not empty to avoid overriding
// GitHub's default revert title generation.
if opts.Title != "" {
params.Title = githubv4.NewString(githubv4.String(opts.Title))
}
revertPR, err := api.PullRequestRevert(apiClient, baseRepo, params)
if err != nil {
fmt.Fprintf(opts.IO.ErrOut, "%s %s\n", cs.FailureIcon(), err)
return fmt.Errorf("API call failed: %w", err)
}
if revertPR != nil {
fmt.Fprintln(opts.IO.Out, revertPR.URL)
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/revert/revert_test.go | pkg/cmd/pr/revert/revert_test.go | package revert
import (
"bytes"
"io"
"net/http"
"testing"
"github.com/cli/cli/v2/api"
"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/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, 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
},
}
cmd := NewCmdRevert(factory, nil)
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 TestPRRevert_missingArgument(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t, "123", &api.PullRequest{
ID: "SOME-ID",
Number: 123,
State: "MERGED",
Title: "The title of the PR",
}, ghrepo.New("OWNER", "REPO"))
// No arguments provided.
_, err := runCommand(http, true, "")
// Exits non-zero and prints an argument error.
assert.EqualError(t, err, "cannot revert pull request: number, url, or branch required")
}
func TestPRRevert_acceptedIdentifierFormats(t *testing.T) {
tests := []struct {
name string
args string
}{
{
name: "Revert by pull request number",
args: "123",
},
{
name: "Revert by pull request identifier",
args: "owner/repo#123",
},
{
name: "Revert by pull request URL",
args: "https://github.com/owner/repo/pull/123",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t, tt.args, &api.PullRequest{
ID: "SOME-ID",
Number: 123,
State: "MERGED",
Title: "The title of the PR",
}, ghrepo.New("OWNER", "REPO"))
http.Register(
httpmock.GraphQL(`mutation PullRequestRevert\b`),
httpmock.GraphQLMutation(`
{ "data": { "revertPullRequest": { "pullRequest": {
"ID": "SOME-ID"
}, "revertPullRequest": {
"ID": "NEW-ID",
"Number": 456,
"URL": "https://github.com/OWNER/REPO/pull/456"
} } } }
`,
func(inputs map[string]interface{}) {
assert.Equal(t, inputs["pullRequestId"], "SOME-ID")
}),
)
output, err := runCommand(http, true, tt.args)
// Revert PR is created and only its URL is printed.
assert.NoError(t, err)
assert.Equal(t, "https://github.com/OWNER/REPO/pull/456\n", output.String())
assert.Equal(t, "", output.Stderr())
})
}
}
func TestPRRevert_notRevertable(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t, "123", &api.PullRequest{
ID: "SOME-ID",
Number: 123,
State: "OPEN",
Title: "The title of the PR",
}, ghrepo.New("OWNER", "REPO"))
// Target PR is not merged.
output, err := runCommand(http, true, "123")
// API error, non-zero exit.
assert.EqualError(t, err, "SilentError")
assert.Equal(t, "X Pull request OWNER/REPO#123 (The title of the PR) can't be reverted because it has not been merged\n", output.Stderr())
// No URL printed.
assert.Equal(t, "", output.String())
}
func TestPRRevert_withTitleAndBody(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t, "123", &api.PullRequest{
ID: "SOME-ID",
Number: 123,
State: "MERGED",
Title: "The title of the PR",
}, ghrepo.New("OWNER", "REPO"))
http.Register(
httpmock.GraphQL(`mutation PullRequestRevert\b`),
httpmock.GraphQLMutation(`
{ "data": { "revertPullRequest": { "pullRequest": {
"ID": "SOME-ID"
}, "revertPullRequest": {
"ID": "NEW-ID",
"Number": 456,
"URL": "https://github.com/OWNER/REPO/pull/456"
} } } }
`,
func(inputs map[string]interface{}) {
assert.Equal(t, inputs["pullRequestId"], "SOME-ID")
assert.Equal(t, inputs["title"], "Revert PR title")
assert.Equal(t, inputs["body"], "Revert PR body")
}),
)
output, err := runCommand(http, true, "123 --title 'Revert PR title' --body 'Revert PR body'")
// Revert PR created.
assert.NoError(t, err)
// Only URL printed.
assert.Equal(t, "https://github.com/OWNER/REPO/pull/456\n", output.String())
assert.Equal(t, "", output.Stderr())
}
func TestPRRevert_withDraft(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t, "123", &api.PullRequest{
ID: "SOME-ID",
Number: 123,
State: "MERGED",
Title: "The title of the PR",
}, ghrepo.New("OWNER", "REPO"))
http.Register(
httpmock.GraphQL(`mutation PullRequestRevert\b`),
httpmock.GraphQLMutation(`
{ "data": { "revertPullRequest": { "pullRequest": {
"ID": "SOME-ID"
}, "revertPullRequest": {
"ID": "NEW-ID",
"Number": 456,
"URL": "https://github.com/OWNER/REPO/pull/456"
} } } }
`,
func(inputs map[string]interface{}) {
assert.Equal(t, inputs["pullRequestId"], "SOME-ID")
assert.Equal(t, inputs["draft"], true)
}),
)
output, err := runCommand(http, true, "123 --draft")
// Revert PR created as a draft.
assert.NoError(t, err)
// Only URL printed.
assert.Equal(t, "https://github.com/OWNER/REPO/pull/456\n", output.String())
assert.Equal(t, "", output.Stderr())
}
func TestPRRevert_APIFailure(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t, "123", &api.PullRequest{
ID: "SOME-ID",
Number: 123,
State: "MERGED",
Title: "The title of the PR",
}, ghrepo.New("OWNER", "REPO"))
http.Register(
httpmock.GraphQL(`mutation PullRequestRevert\b`),
httpmock.GraphQLMutation(`
{ "errors": [{
"message": "Authorization error"
}]}`,
func(inputs map[string]interface{}) {
assert.Equal(t, inputs["pullRequestId"], "SOME-ID")
}),
)
output, err := runCommand(http, true, "123")
// Non-zero exit, stderr shows the API error, stdout empty.
assert.EqualError(t, err, "API call failed: GraphQL: Authorization error")
assert.Equal(t, "X GraphQL: Authorization error\n", output.Stderr())
assert.Equal(t, "", output.String())
}
func TestPRRevert_multipleInvocations(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t, "123", &api.PullRequest{
ID: "SOME-ID",
Number: 123,
State: "MERGED",
Title: "The title of the PR",
}, ghrepo.New("OWNER", "REPO"))
http.Register(
httpmock.GraphQL(`mutation PullRequestRevert\b`),
httpmock.GraphQLMutation(`
{ "data": { "revertPullRequest": { "pullRequest": {
"ID": "SOME-ID"
}, "revertPullRequest": {
"ID": "NEW-ID",
"Number": 456,
"URL": "https://github.com/OWNER/REPO/pull/456"
} } } }
`,
func(inputs map[string]interface{}) {
assert.Equal(t, inputs["pullRequestId"], "SOME-ID")
}),
)
output, err := runCommand(http, true, "123")
// Revert PR is created and only its URL is printed.
assert.NoError(t, err)
assert.Equal(t, "https://github.com/OWNER/REPO/pull/456\n", output.String())
assert.Equal(t, "", output.Stderr())
// Invoke the same command, behavior depends solely on API response
shared.StubFinderForRunCommandStyleTests(t, "123", &api.PullRequest{
ID: "SOME-ID",
Number: 123,
State: "MERGED",
Title: "The title of the PR",
}, ghrepo.New("OWNER", "REPO"))
http.Register(
httpmock.GraphQL(`mutation PullRequestRevert\b`),
httpmock.GraphQLMutation(`
{ "data": { "revertPullRequest": { "pullRequest": {
"ID": "SOME-ID"
}, "revertPullRequest": {
"ID": "NEW-ID",
"Number": 456,
"URL": "https://github.com/OWNER/REPO/pull/456"
} } } }
`,
func(inputs map[string]interface{}) {
assert.Equal(t, inputs["pullRequestId"], "SOME-ID")
}),
)
output, err = runCommand(http, true, "123")
// Revert PR is created and only its URL is printed.
assert.NoError(t, err)
assert.Equal(t, "https://github.com/OWNER/REPO/pull/456\n", output.String())
assert.Equal(t, "", output.Stderr())
// Invoke the same command, behavior depends solely on API response.
shared.StubFinderForRunCommandStyleTests(t, "123", &api.PullRequest{
ID: "SOME-ID",
Number: 123,
State: "OPEN",
Title: "The title of the PR",
}, ghrepo.New("OWNER", "REPO"))
output, err = runCommand(http, true, "123")
// Revert PR is not created, API error, non-zero exit.
assert.EqualError(t, err, "SilentError")
assert.Equal(t, "X Pull request OWNER/REPO#123 (The title of the PR) can't be reverted because it has not been merged\n", output.Stderr())
// No URL printed.
assert.Equal(t, "", output.String())
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/reopen/reopen_test.go | pkg/cmd/pr/reopen/reopen_test.go | package reopen
import (
"bytes"
"io"
"net/http"
"testing"
"github.com/cli/cli/v2/api"
"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/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, 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
},
}
cmd := NewCmdReopen(factory, nil)
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 TestPRReopen(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t, "123", &api.PullRequest{
ID: "THE-ID",
Number: 123,
State: "CLOSED",
Title: "The title of the PR",
}, ghrepo.New("OWNER", "REPO"))
http.Register(
httpmock.GraphQL(`mutation PullRequestReopen\b`),
httpmock.GraphQLMutation(`{"id": "THE-ID"}`,
func(inputs map[string]interface{}) {
assert.Equal(t, inputs["pullRequestId"], "THE-ID")
}),
)
output, err := runCommand(http, true, "123")
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, "✓ Reopened pull request OWNER/REPO#123 (The title of the PR)\n", output.Stderr())
}
func TestPRReopen_alreadyOpen(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t, "123", &api.PullRequest{
ID: "THE-ID",
Number: 123,
State: "OPEN",
Title: "The title of the PR",
}, ghrepo.New("OWNER", "REPO"))
output, err := runCommand(http, true, "123")
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, "! Pull request OWNER/REPO#123 (The title of the PR) is already open\n", output.Stderr())
}
func TestPRReopen_alreadyMerged(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t, "123", &api.PullRequest{
ID: "THE-ID",
Number: 123,
State: "MERGED",
Title: "The title of the PR",
}, ghrepo.New("OWNER", "REPO"))
output, err := runCommand(http, true, "123")
assert.EqualError(t, err, "SilentError")
assert.Equal(t, "", output.String())
assert.Equal(t, "X Pull request OWNER/REPO#123 (The title of the PR) can't be reopened because it was already merged\n", output.Stderr())
}
func TestPRReopen_withComment(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t, "123", &api.PullRequest{
ID: "THE-ID",
Number: 123,
State: "CLOSED",
Title: "The title of the PR",
}, ghrepo.New("OWNER", "REPO"))
http.Register(
httpmock.GraphQL(`mutation CommentCreate\b`),
httpmock.GraphQLMutation(`
{ "data": { "addComment": { "commentEdge": { "node": {
"url": "https://github.com/OWNER/REPO/issues/123#issuecomment-456"
} } } } }`,
func(inputs map[string]interface{}) {
assert.Equal(t, "THE-ID", inputs["subjectId"])
assert.Equal(t, "reopening comment", inputs["body"])
}),
)
http.Register(
httpmock.GraphQL(`mutation PullRequestReopen\b`),
httpmock.GraphQLMutation(`{"id": "THE-ID"}`,
func(inputs map[string]interface{}) {
assert.Equal(t, inputs["pullRequestId"], "THE-ID")
}),
)
output, err := runCommand(http, true, "123 --comment 'reopening comment'")
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, "✓ Reopened pull request OWNER/REPO#123 (The title of the PR)\n", output.Stderr())
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/reopen/reopen.go | pkg/cmd/pr/reopen/reopen.go | package reopen
import (
"fmt"
"net/http"
"github.com/cli/cli/v2/api"
"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/spf13/cobra"
)
type ReopenOptions struct {
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
Finder shared.PRFinder
SelectorArg string
Comment string
}
func NewCmdReopen(f *cmdutil.Factory, runF func(*ReopenOptions) error) *cobra.Command {
opts := &ReopenOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
}
cmd := &cobra.Command{
Use: "reopen {<number> | <url> | <branch>}",
Short: "Reopen a pull request",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
opts.Finder = shared.NewFinder(f)
if len(args) > 0 {
opts.SelectorArg = args[0]
}
if runF != nil {
return runF(opts)
}
return reopenRun(opts)
},
}
cmd.Flags().StringVarP(&opts.Comment, "comment", "c", "", "Add a reopening comment")
return cmd
}
func reopenRun(opts *ReopenOptions) error {
cs := opts.IO.ColorScheme()
findOptions := shared.FindOptions{
Selector: opts.SelectorArg,
Fields: []string{"id", "number", "state", "title"},
}
pr, baseRepo, err := opts.Finder.Find(findOptions)
if err != nil {
return err
}
if pr.State == "MERGED" {
fmt.Fprintf(opts.IO.ErrOut, "%s Pull request %s#%d (%s) can't be reopened because it was already merged\n", cs.FailureIcon(), ghrepo.FullName(baseRepo), pr.Number, pr.Title)
return cmdutil.SilentError
}
if pr.IsOpen() {
fmt.Fprintf(opts.IO.ErrOut, "%s Pull request %s#%d (%s) is already open\n", cs.WarningIcon(), ghrepo.FullName(baseRepo), pr.Number, pr.Title)
return nil
}
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
if opts.Comment != "" {
commentOpts := &shared.CommentableOptions{
Body: opts.Comment,
HttpClient: opts.HttpClient,
InputType: shared.InputTypeInline,
Quiet: true,
RetrieveCommentable: func() (shared.Commentable, ghrepo.Interface, error) {
return pr, baseRepo, nil
},
}
err := shared.CommentableRun(commentOpts)
if err != nil {
return err
}
}
err = api.PullRequestReopen(httpClient, baseRepo, pr.ID)
if err != nil {
return fmt.Errorf("API call failed: %w", err)
}
fmt.Fprintf(opts.IO.ErrOut, "%s Reopened pull request %s#%d (%s)\n", cs.SuccessIconWithColor(cs.Green), ghrepo.FullName(baseRepo), pr.Number, pr.Title)
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/list/list_test.go | pkg/cmd/pr/list/list_test.go | package list
import (
"bytes"
"io"
"net/http"
"strings"
"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"
prShared "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 runCommand(rt http.RoundTripper, detector fd.Detector, isTTY bool, cli string) (*test.CmdOut, error) {
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdoutTTY(isTTY)
ios.SetStdinTTY(isTTY)
ios.SetStderrTTY(isTTY)
browser := &browser.Stub{}
factory := &cmdutil.Factory{
IOStreams: ios,
Browser: browser,
HttpClient: func() (*http.Client, error) {
return &http.Client{Transport: rt}, nil
},
BaseRepo: func() (ghrepo.Interface, error) {
return ghrepo.New("OWNER", "REPO"), nil
},
}
fakeNow := func() time.Time {
return time.Date(2022, time.August, 24, 23, 50, 0, 0, time.UTC)
}
cmd := NewCmdList(factory, func(opts *ListOptions) error {
opts.Now = fakeNow
opts.Detector = detector
return listRun(opts)
})
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,
BrowsedURL: browser.BrowsedURL(),
}, err
}
func initFakeHTTP() *httpmock.Registry {
return &httpmock.Registry{}
}
func TestPRList(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(httpmock.GraphQL(`query PullRequestList\b`), httpmock.FileResponse("./fixtures/prList.json"))
output, err := runCommand(http, nil, true, "")
if err != nil {
t.Fatal(err)
}
assert.Equal(t, heredoc.Doc(`
Showing 3 of 3 open pull requests in OWNER/REPO
ID TITLE BRANCH CREATED AT
#32 New feature feature about 3 hours ago
#29 Fixed bad bug hubot:bug-fix about 1 month ago
#28 Improve documentation docs about 2 years ago
`), output.String())
assert.Equal(t, ``, output.Stderr())
}
func TestPRList_nontty(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(httpmock.GraphQL(`query PullRequestList\b`), httpmock.FileResponse("./fixtures/prList.json"))
output, err := runCommand(http, nil, false, "")
if err != nil {
t.Fatal(err)
}
assert.Equal(t, "", output.Stderr())
assert.Equal(t, `32 New feature feature DRAFT 2022-08-24T20:01:12Z
29 Fixed bad bug hubot:bug-fix OPEN 2022-07-20T19:01:12Z
28 Improve documentation docs MERGED 2020-01-26T19:01:12Z
`, output.String())
}
func TestPRList_filtering(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(
httpmock.GraphQL(`query PullRequestList\b`),
httpmock.GraphQLQuery(`{}`, func(_ string, params map[string]interface{}) {
assert.Equal(t, []interface{}{"OPEN", "CLOSED", "MERGED"}, params["state"].([]interface{}))
}))
output, err := runCommand(http, nil, true, `-s all`)
assert.Error(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, "", output.Stderr())
}
func TestPRList_filteringRemoveDuplicate(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(
httpmock.GraphQL(`query PullRequestList\b`),
httpmock.FileResponse("./fixtures/prListWithDuplicates.json"))
output, err := runCommand(http, nil, true, "")
if err != nil {
t.Fatal(err)
}
out := output.String()
idx := strings.Index(out, "New feature")
if idx < 0 {
t.Fatalf("text %q not found in %q", "New feature", out)
}
assert.Equal(t, idx, strings.LastIndex(out, "New feature"))
}
func TestPRList_filteringClosed(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(
httpmock.GraphQL(`query PullRequestList\b`),
httpmock.GraphQLQuery(`{}`, func(_ string, params map[string]interface{}) {
assert.Equal(t, []interface{}{"CLOSED", "MERGED"}, params["state"].([]interface{}))
}))
_, err := runCommand(http, nil, true, `-s closed`)
assert.Error(t, err)
}
func TestPRList_filteringHeadBranch(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(
httpmock.GraphQL(`query PullRequestList\b`),
httpmock.GraphQLQuery(`{}`, func(_ string, params map[string]interface{}) {
assert.Equal(t, interface{}("bug-fix"), params["headBranch"])
}))
_, err := runCommand(http, nil, true, `-H bug-fix`)
assert.Error(t, err)
}
func TestPRList_filteringAssignee(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(
httpmock.GraphQL(`query PullRequestSearch\b`),
httpmock.GraphQLQuery(`{}`, func(_ string, params map[string]interface{}) {
assert.Equal(t, `assignee:hubot base:develop is:merged label:"needs tests" repo:OWNER/REPO type:pr`, params["q"].(string))
}))
// TODO advancedIssueSearchCleanup
// No need for feature detection once GHES 3.17 support ends.
_, err := runCommand(http, fd.AdvancedIssueSearchSupportedAsOptIn(), true, `-s merged -l "needs tests" -a hubot -B develop`)
assert.Error(t, err)
}
func TestPRList_filteringDraft(t *testing.T) {
tests := []struct {
name string
cli string
expectedQuery string
}{
{
name: "draft",
cli: "--draft",
expectedQuery: `draft:true repo:OWNER/REPO state:open type:pr`,
},
{
name: "non-draft",
cli: "--draft=false",
expectedQuery: `draft:false repo:OWNER/REPO state:open type:pr`,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(
httpmock.GraphQL(`query PullRequestSearch\b`),
httpmock.GraphQLQuery(`{}`, func(_ string, params map[string]interface{}) {
assert.Equal(t, test.expectedQuery, params["q"].(string))
}))
// TODO advancedIssueSearchCleanup
// No need for feature detection once GHES 3.17 support ends.
_, err := runCommand(http, fd.AdvancedIssueSearchSupportedAsOptIn(), true, test.cli)
assert.Error(t, err)
})
}
}
func TestPRList_filteringAuthor(t *testing.T) {
tests := []struct {
name string
cli string
expectedQuery string
}{
{
name: "author @me",
cli: `--author "@me"`,
expectedQuery: `author:@me repo:OWNER/REPO state:open type:pr`,
},
{
name: "author user",
cli: `--author "monalisa"`,
expectedQuery: `author:monalisa repo:OWNER/REPO state:open type:pr`,
},
{
name: "app author",
cli: `--author "app/dependabot"`,
expectedQuery: `author:app/dependabot repo:OWNER/REPO state:open type:pr`,
},
{
name: "app author with app option",
cli: `--app "dependabot"`,
expectedQuery: `author:app/dependabot repo:OWNER/REPO state:open type:pr`,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
http.Register(
httpmock.GraphQL(`query PullRequestSearch\b`),
httpmock.GraphQLQuery(`{}`, func(_ string, params map[string]interface{}) {
assert.Equal(t, test.expectedQuery, params["q"].(string))
}))
// TODO advancedIssueSearchCleanup
// No need for feature detection once GHES 3.17 support ends.
_, err := runCommand(http, fd.AdvancedIssueSearchSupportedAsOptIn(), true, test.cli)
assert.Error(t, err)
})
}
}
func TestPRList_withInvalidLimitFlag(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
_, err := runCommand(http, nil, true, `--limit=0`)
assert.EqualError(t, err, "invalid value for --limit: 0")
}
func TestPRList_web(t *testing.T) {
tests := []struct {
name string
cli string
expectedBrowserURL string
}{
{
name: "filters",
cli: "-a peter -l bug -l docs -L 10 -s merged -B trunk",
expectedBrowserURL: "https://github.com/OWNER/REPO/pulls?q=assignee%3Apeter+base%3Atrunk+is%3Amerged+label%3Abug+label%3Adocs+type%3Apr",
},
{
name: "draft",
cli: "--draft=true",
expectedBrowserURL: "https://github.com/OWNER/REPO/pulls?q=draft%3Atrue+state%3Aopen+type%3Apr",
},
{
name: "non-draft",
cli: "--draft=0",
expectedBrowserURL: "https://github.com/OWNER/REPO/pulls?q=draft%3Afalse+state%3Aopen+type%3Apr",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
http := initFakeHTTP()
defer http.Verify(t)
_, cmdTeardown := run.Stub()
defer cmdTeardown(t)
output, err := runCommand(http, nil, true, "--web "+test.cli)
if err != nil {
t.Errorf("error running command `pr list` with `--web` flag: %v", err)
}
assert.Equal(t, "", output.String())
assert.Equal(t, "Opening https://github.com/OWNER/REPO/pulls in your browser.\n", output.Stderr())
assert.Equal(t, test.expectedBrowserURL, output.BrowsedURL)
})
}
}
func TestPRList_withProjectItems(t *testing.T) {
reg := &httpmock.Registry{}
defer reg.Verify(t)
reg.Register(
httpmock.GraphQL(`query PullRequestList\b`),
httpmock.GraphQLQuery(`{
"data": {
"repository": {
"pullRequests": {
"totalCount": 1,
"nodes": [
{
"projectItems": {
"nodes": [
{
"id": "PVTI_lAHOAA3WC84AW6WNzgJ8rnQ",
"project": {
"id": "PVT_kwHOAA3WC84AW6WN",
"title": "Test Public Project"
},
"status": {
"optionId": "47fc9ee4",
"name": "In Progress"
}
}
],
"totalCount": 1
}
}
]
}
}
}
}`, func(_ string, params map[string]interface{}) {
require.Equal(t, map[string]interface{}{
"owner": "OWNER",
"repo": "REPO",
"limit": float64(30),
"state": []interface{}{"OPEN"},
}, params)
}))
client := &http.Client{Transport: reg}
prsAndTotalCount, err := listPullRequests(
client,
nil,
ghrepo.New("OWNER", "REPO"),
prShared.FilterOptions{
Entity: "pr",
State: "open",
},
30,
)
require.NoError(t, err)
require.Len(t, prsAndTotalCount.PullRequests, 1)
require.Len(t, prsAndTotalCount.PullRequests[0].ProjectItems.Nodes, 1)
require.Equal(t, prsAndTotalCount.PullRequests[0].ProjectItems.Nodes[0].ID, "PVTI_lAHOAA3WC84AW6WNzgJ8rnQ")
expectedProject := api.ProjectV2ItemProject{
ID: "PVT_kwHOAA3WC84AW6WN",
Title: "Test Public Project",
}
require.Equal(t, prsAndTotalCount.PullRequests[0].ProjectItems.Nodes[0].Project, expectedProject)
expectedStatus := api.ProjectV2ItemStatus{
OptionID: "47fc9ee4",
Name: "In Progress",
}
require.Equal(t, prsAndTotalCount.PullRequests[0].ProjectItems.Nodes[0].Status, expectedStatus)
}
func TestPRList_Search_withProjectItems(t *testing.T) {
reg := &httpmock.Registry{}
defer reg.Verify(t)
reg.Register(
httpmock.GraphQL(`query PullRequestSearch\b`),
httpmock.GraphQLQuery(`{
"data": {
"search": {
"issueCount": 1,
"nodes": [
{
"projectItems": {
"nodes": [
{
"id": "PVTI_lAHOAA3WC84AW6WNzgJ8rl0",
"project": {
"id": "PVT_kwHOAA3WC84AW6WN",
"title": "Test Public Project"
},
"status": {
"optionId": "47fc9ee4",
"name": "In Progress"
}
}
],
"totalCount": 1
}
}
]
}
}
}`, func(_ string, params map[string]interface{}) {
require.Equal(t, map[string]interface{}{
"limit": float64(30),
"q": "( just used to force the search API branch ) repo:OWNER/REPO state:open type:pr",
"type": "ISSUE_ADVANCED",
}, params)
}))
client := &http.Client{Transport: reg}
prsAndTotalCount, err := listPullRequests(
client,
// TODO advancedIssueSearchCleanup
// No need for feature detection once GHES 3.17 support ends.
fd.AdvancedIssueSearchSupportedAsOptIn(),
ghrepo.New("OWNER", "REPO"),
prShared.FilterOptions{
Entity: "pr",
State: "open",
Search: "just used to force the search API branch",
},
30,
)
require.NoError(t, err)
require.Len(t, prsAndTotalCount.PullRequests, 1)
require.Len(t, prsAndTotalCount.PullRequests[0].ProjectItems.Nodes, 1)
require.Equal(t, prsAndTotalCount.PullRequests[0].ProjectItems.Nodes[0].ID, "PVTI_lAHOAA3WC84AW6WNzgJ8rl0")
expectedProject := api.ProjectV2ItemProject{
ID: "PVT_kwHOAA3WC84AW6WN",
Title: "Test Public Project",
}
require.Equal(t, prsAndTotalCount.PullRequests[0].ProjectItems.Nodes[0].Project, expectedProject)
expectedStatus := api.ProjectV2ItemStatus{
OptionID: "47fc9ee4",
Name: "In Progress",
}
require.Equal(t, prsAndTotalCount.PullRequests[0].ProjectItems.Nodes[0].Status, expectedStatus)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/list/list.go | pkg/cmd/pr/list/list.go | package list
import (
"fmt"
"net/http"
"strconv"
"strings"
"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/tableprinter"
"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"
)
type ListOptions struct {
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
BaseRepo func() (ghrepo.Interface, error)
Browser browser.Browser
Detector fd.Detector
WebMode bool
LimitResults int
Exporter cmdutil.Exporter
State string
BaseBranch string
HeadBranch string
Labels []string
Author string
Assignee string
Search string
Draft *bool
Now func() time.Time
}
func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Command {
opts := &ListOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
Browser: f.Browser,
Now: time.Now,
}
var appAuthor string
cmd := &cobra.Command{
Use: "list",
Short: "List pull requests in a repository",
// TODO advancedIssueSearchCleanup
// Update the links and remove the mention at GHES 3.17 version.
Long: heredoc.Docf(`
List pull requests in a GitHub repository. By default, this only lists open PRs.
The search query syntax is documented here:
<https://docs.github.com/en/search-github/searching-on-github/searching-issues-and-pull-requests>
On supported GitHub hosts, advanced issue search syntax can be used in the
%[1]s--search%[1]s query. For more information about advanced issue search, see:
<https://docs.github.com/en/issues/tracking-your-work-with-issues/using-issues/filtering-and-searching-issues-and-pull-requests#building-advanced-filters-for-issues>
`, "`"),
Example: heredoc.Doc(`
# List PRs authored by you
$ gh pr list --author "@me"
# List PRs with a specific head branch name
$ gh pr list --head "typo"
# List only PRs with all of the given labels
$ gh pr list --label bug --label "priority 1"
# Filter PRs using search syntax
$ gh pr list --search "status:success review:required"
# Find a PR that introduced a given commit
$ gh pr list --search "<SHA>" --state merged
`),
Aliases: []string{"ls"},
Args: cmdutil.NoArgsQuoteReminder,
RunE: func(cmd *cobra.Command, args []string) error {
// support `-R, --repo` override
opts.BaseRepo = f.BaseRepo
if opts.LimitResults < 1 {
return cmdutil.FlagErrorf("invalid value for --limit: %v", opts.LimitResults)
}
if cmd.Flags().Changed("author") && cmd.Flags().Changed("app") {
return cmdutil.FlagErrorf("specify only `--author` or `--app`")
}
if cmd.Flags().Changed("app") {
opts.Author = fmt.Sprintf("app/%s", appAuthor)
}
if runF != nil {
return runF(opts)
}
return listRun(opts)
},
}
cmd.Flags().BoolVarP(&opts.WebMode, "web", "w", false, "List pull requests in the web browser")
cmd.Flags().IntVarP(&opts.LimitResults, "limit", "L", 30, "Maximum number of items to fetch")
cmdutil.StringEnumFlag(cmd, &opts.State, "state", "s", "open", []string{"open", "closed", "merged", "all"}, "Filter by state")
cmd.Flags().StringVarP(&opts.BaseBranch, "base", "B", "", "Filter by base branch")
cmd.Flags().StringVarP(&opts.HeadBranch, "head", "H", "", `Filter by head branch ("<owner>:<branch>" syntax not supported)`)
cmd.Flags().StringSliceVarP(&opts.Labels, "label", "l", nil, "Filter by label")
cmd.Flags().StringVarP(&opts.Author, "author", "A", "", "Filter by author")
cmd.Flags().StringVar(&appAuthor, "app", "", "Filter by GitHub App author")
cmd.Flags().StringVarP(&opts.Assignee, "assignee", "a", "", "Filter by assignee")
cmd.Flags().StringVarP(&opts.Search, "search", "S", "", "Search pull requests with `query`")
cmdutil.NilBoolFlag(cmd, &opts.Draft, "draft", "d", "Filter by draft state")
cmdutil.AddJSONFlags(cmd, &opts.Exporter, api.PullRequestFields)
_ = cmdutil.RegisterBranchCompletionFlags(f.GitClient, cmd, "base", "head")
return cmd
}
var defaultFields = []string{
"number",
"title",
"state",
"url",
"headRefName",
"headRepositoryOwner",
"isCrossRepository",
"isDraft",
"createdAt",
}
func listRun(opts *ListOptions) error {
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
baseRepo, err := opts.BaseRepo()
if err != nil {
return err
}
if opts.Detector == nil {
cachedClient := api.NewCachedHTTPClient(httpClient, time.Hour*24)
opts.Detector = fd.NewDetector(cachedClient, baseRepo.RepoHost())
}
prState := strings.ToLower(opts.State)
if prState == "open" && shared.QueryHasStateClause(opts.Search) {
prState = ""
}
filters := shared.FilterOptions{
Entity: "pr",
State: prState,
Author: opts.Author,
Assignee: opts.Assignee,
Labels: opts.Labels,
BaseBranch: opts.BaseBranch,
HeadBranch: opts.HeadBranch,
Search: opts.Search,
Draft: opts.Draft,
Fields: defaultFields,
}
if opts.Exporter != nil {
filters.Fields = opts.Exporter.Fields()
}
if opts.WebMode {
prListURL := ghrepo.GenerateRepoURL(baseRepo, "pulls")
// TODO advancedSearchFuture
// As of August 2025, the advanced issue search syntax is not supported
// in Pull Requests tab of repositories. When it's supported we can
// change the argument to true.
openURL, err := shared.ListURLWithQuery(prListURL, filters, false)
if err != nil {
return err
}
if opts.IO.IsStdoutTTY() {
fmt.Fprintf(opts.IO.ErrOut, "Opening %s in your browser.\n", text.DisplayURL(openURL))
}
return opts.Browser.Browse(openURL)
}
listResult, err := listPullRequests(httpClient, opts.Detector, baseRepo, filters, opts.LimitResults)
if err != nil {
return err
}
if len(listResult.PullRequests) == 0 && opts.Exporter == nil {
return shared.ListNoResults(ghrepo.FullName(baseRepo), "pull request", !filters.IsDefault())
}
err = opts.IO.StartPager()
if err != nil {
fmt.Fprintf(opts.IO.ErrOut, "error starting pager: %v\n", err)
}
defer opts.IO.StopPager()
if opts.Exporter != nil {
return opts.Exporter.Write(opts.IO, listResult.PullRequests)
}
if listResult.SearchCapped {
fmt.Fprintln(opts.IO.ErrOut, "warning: this query uses the Search API which is capped at 1000 results maximum")
}
if opts.IO.IsStdoutTTY() {
title := shared.ListHeader(ghrepo.FullName(baseRepo), "pull request", len(listResult.PullRequests), listResult.TotalCount, !filters.IsDefault())
fmt.Fprintf(opts.IO.Out, "\n%s\n\n", title)
}
cs := opts.IO.ColorScheme()
isTTY := opts.IO.IsStdoutTTY()
headers := []string{
"ID",
"TITLE",
"BRANCH",
}
if !isTTY {
headers = append(headers, "STATE")
}
headers = append(headers, "CREATED AT")
table := tableprinter.New(opts.IO, tableprinter.WithHeader(headers...))
for _, pr := range listResult.PullRequests {
prNum := strconv.Itoa(pr.Number)
if isTTY {
prNum = "#" + prNum
}
table.AddField(prNum, tableprinter.WithColor(cs.ColorFromString(shared.ColorForPRState(pr))))
table.AddField(text.RemoveExcessiveWhitespace(pr.Title))
table.AddField(pr.HeadLabel(), tableprinter.WithColor(cs.Cyan))
if !isTTY {
table.AddField(shared.PrStateWithDraft(&pr))
}
table.AddTimeField(opts.Now(), pr.CreatedAt, cs.Muted)
table.EndRow()
}
err = table.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/list/http_test.go | pkg/cmd/pr/list/http_test.go | package list
import (
"net/http"
"reflect"
"testing"
fd "github.com/cli/cli/v2/internal/featuredetection"
"github.com/cli/cli/v2/internal/ghrepo"
prShared "github.com/cli/cli/v2/pkg/cmd/pr/shared"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/stretchr/testify/assert"
)
func Test_ListPullRequests(t *testing.T) {
type args struct {
detector fd.Detector
repo ghrepo.Interface
filters prShared.FilterOptions
limit int
}
tests := []struct {
name string
args args
httpStub func(*testing.T, *httpmock.Registry)
wantErr bool
}{
{
name: "default",
args: args{
repo: ghrepo.New("OWNER", "REPO"),
limit: 30,
filters: prShared.FilterOptions{
State: "open",
},
},
httpStub: func(t *testing.T, r *httpmock.Registry) {
r.Register(
httpmock.GraphQL(`query PullRequestList\b`),
httpmock.GraphQLQuery(`{"data":{}}`, func(query string, vars map[string]interface{}) {
want := map[string]interface{}{
"owner": "OWNER",
"repo": "REPO",
"state": []interface{}{"OPEN"},
"limit": float64(30),
}
if !reflect.DeepEqual(vars, want) {
t.Errorf("got GraphQL variables %#v, want %#v", vars, want)
}
}))
},
},
{
name: "closed",
args: args{
repo: ghrepo.New("OWNER", "REPO"),
limit: 30,
filters: prShared.FilterOptions{
State: "closed",
},
},
httpStub: func(t *testing.T, r *httpmock.Registry) {
r.Register(
httpmock.GraphQL(`query PullRequestList\b`),
httpmock.GraphQLQuery(`{"data":{}}`, func(query string, vars map[string]interface{}) {
want := map[string]interface{}{
"owner": "OWNER",
"repo": "REPO",
"state": []interface{}{"CLOSED", "MERGED"},
"limit": float64(30),
}
if !reflect.DeepEqual(vars, want) {
t.Errorf("got GraphQL variables %#v, want %#v", vars, want)
}
}))
},
},
{
name: "with labels",
args: args{
// TODO advancedIssueSearchCleanup
// No need for feature detection once GHES 3.17 support ends.
detector: fd.AdvancedIssueSearchSupportedAsOptIn(),
repo: ghrepo.New("OWNER", "REPO"),
limit: 30,
filters: prShared.FilterOptions{
State: "open",
Labels: []string{"hello", "one world"},
},
},
httpStub: func(t *testing.T, r *httpmock.Registry) {
r.Register(
httpmock.GraphQL(`query PullRequestSearch\b`),
httpmock.GraphQLQuery(`{"data":{}}`, func(query string, vars map[string]interface{}) {
want := map[string]interface{}{
"q": `label:"one world" label:hello repo:OWNER/REPO state:open type:pr`,
"type": "ISSUE_ADVANCED",
"limit": float64(30),
}
if !reflect.DeepEqual(vars, want) {
t.Errorf("got GraphQL variables %#v, want %#v", vars, want)
}
}))
},
},
{
name: "with author",
args: args{
// TODO advancedIssueSearchCleanup
// No need for feature detection once GHES 3.17 support ends.
detector: fd.AdvancedIssueSearchSupportedAsOptIn(),
repo: ghrepo.New("OWNER", "REPO"),
limit: 30,
filters: prShared.FilterOptions{
State: "open",
Author: "monalisa",
},
},
httpStub: func(t *testing.T, r *httpmock.Registry) {
r.Register(
httpmock.GraphQL(`query PullRequestSearch\b`),
httpmock.GraphQLQuery(`{"data":{}}`, func(query string, vars map[string]interface{}) {
want := map[string]interface{}{
"q": "author:monalisa repo:OWNER/REPO state:open type:pr",
"type": "ISSUE_ADVANCED",
"limit": float64(30),
}
if !reflect.DeepEqual(vars, want) {
t.Errorf("got GraphQL variables %#v, want %#v", vars, want)
}
}))
},
},
{
name: "with search",
args: args{
// TODO advancedIssueSearchCleanup
// No need for feature detection once GHES 3.17 support ends.
detector: fd.AdvancedIssueSearchSupportedAsOptIn(),
repo: ghrepo.New("OWNER", "REPO"),
limit: 30,
filters: prShared.FilterOptions{
State: "open",
Search: "one world in:title",
},
},
httpStub: func(t *testing.T, r *httpmock.Registry) {
r.Register(
httpmock.GraphQL(`query PullRequestSearch\b`),
httpmock.GraphQLQuery(`{"data":{}}`, func(query string, vars map[string]interface{}) {
want := map[string]interface{}{
"q": "( one world in:title ) repo:OWNER/REPO state:open type:pr",
"type": "ISSUE_ADVANCED",
"limit": float64(30),
}
if !reflect.DeepEqual(vars, want) {
t.Errorf("got GraphQL variables %#v, want %#v", vars, want)
}
}))
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
if tt.httpStub != nil {
tt.httpStub(t, reg)
}
httpClient := &http.Client{Transport: reg}
_, err := listPullRequests(httpClient, tt.args.detector, tt.args.repo, tt.args.filters, tt.args.limit)
if (err != nil) != tt.wantErr {
t.Errorf("ListPullRequests() error = %v, wantErr %v", err, tt.wantErr)
return
}
})
}
}
// TODO advancedIssueSearchCleanup
// Remove this test once GHES 3.17 support ends.
func TestSearchPullRequestsAndAdvancedSearch(t *testing.T) {
tests := []struct {
name string
detector fd.Detector
wantSearchType string
}{
{
name: "advanced issue search not supported",
detector: fd.AdvancedIssueSearchUnsupported(),
wantSearchType: "ISSUE",
},
{
name: "advanced issue search supported as opt-in",
detector: fd.AdvancedIssueSearchSupportedAsOptIn(),
wantSearchType: "ISSUE_ADVANCED",
},
{
name: "advanced issue search supported as only backend",
detector: fd.AdvancedIssueSearchSupportedAsOnlyBackend(),
wantSearchType: "ISSUE",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reg := &httpmock.Registry{}
defer reg.Verify(t)
reg.Register(
httpmock.GraphQL(`query PullRequestSearch\b`),
httpmock.GraphQLQuery(`{"data":{}}`, func(query string, vars map[string]interface{}) {
assert.Equal(t, tt.wantSearchType, vars["type"])
// Since no repeated usage of special search qualifiers is possible
// with our current implementation, we can assert against the same
// query for both search backend (i.e. legacy and advanced issue search).
assert.Equal(t, "repo:OWNER/REPO state:open type:pr", vars["q"])
}))
httpClient := &http.Client{Transport: reg}
searchPullRequests(httpClient, tt.detector, ghrepo.New("OWNER", "REPO"), prShared.FilterOptions{State: "open"}, 30)
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/list/http.go | pkg/cmd/pr/list/http.go | package list
import (
"fmt"
"net/http"
"github.com/cli/cli/v2/api"
fd "github.com/cli/cli/v2/internal/featuredetection"
"github.com/cli/cli/v2/internal/ghrepo"
prShared "github.com/cli/cli/v2/pkg/cmd/pr/shared"
)
func shouldUseSearch(filters prShared.FilterOptions) bool {
return filters.Draft != nil || filters.Author != "" || filters.Assignee != "" || filters.Search != "" || len(filters.Labels) > 0
}
func listPullRequests(httpClient *http.Client, detector fd.Detector, repo ghrepo.Interface, filters prShared.FilterOptions, limit int) (*api.PullRequestAndTotalCount, error) {
if shouldUseSearch(filters) {
return searchPullRequests(httpClient, detector, repo, filters, limit)
}
return prShared.NewLister(httpClient).List(prShared.ListOptions{
BaseRepo: repo,
LimitResults: limit,
State: filters.State,
BaseBranch: filters.BaseBranch,
HeadBranch: filters.HeadBranch,
Fields: filters.Fields,
})
}
func searchPullRequests(httpClient *http.Client, detector fd.Detector, repo ghrepo.Interface, filters prShared.FilterOptions, limit int) (*api.PullRequestAndTotalCount, error) {
// TODO advancedIssueSearchCleanup
// We won't need feature detection when GHES 3.17 support ends, since
// the advanced issue search is the only available search backend for
// issues.
features, err := detector.SearchFeatures()
if err != nil {
return nil, err
}
type response struct {
Search struct {
Nodes []api.PullRequest
PageInfo struct {
HasNextPage bool
EndCursor string
}
IssueCount int
}
}
fragment := fmt.Sprintf("fragment pr on PullRequest{%s}", api.PullRequestGraphQL(filters.Fields))
query := fragment + `
query PullRequestSearch(
$q: String!,
$type: SearchType!,
$limit: Int!,
$endCursor: String,
) {
search(query: $q, type: $type, first: $limit, after: $endCursor) {
issueCount
nodes {
...pr
}
pageInfo {
hasNextPage
endCursor
}
}
}`
variables := map[string]interface{}{}
filters.Repo = ghrepo.FullName(repo)
filters.Entity = "pr"
if features.AdvancedIssueSearchAPI {
variables["q"] = prShared.SearchQueryBuild(filters, true)
if features.AdvancedIssueSearchAPIOptIn {
variables["type"] = "ISSUE_ADVANCED"
} else {
variables["type"] = "ISSUE"
}
} else {
variables["q"] = prShared.SearchQueryBuild(filters, false)
variables["type"] = "ISSUE"
}
pageLimit := min(limit, 100)
res := api.PullRequestAndTotalCount{SearchCapped: limit > 1000}
var check = make(map[int]struct{})
client := api.NewClientFromHTTP(httpClient)
loop:
for {
variables["limit"] = pageLimit
var data response
err := client.GraphQL(repo.RepoHost(), query, variables, &data)
if err != nil {
return nil, err
}
prData := data.Search
res.TotalCount = prData.IssueCount
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
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/close/close_test.go | pkg/cmd/pr/close/close_test.go | package close
import (
"bytes"
"io"
"net/http"
"strings"
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/git"
"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/cli/cli/v2/test"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
)
// repo: either "baseOwner/baseRepo" or "baseOwner/baseRepo:defaultBranch"
// prHead: "headOwner/headRepo:headBranch"
func stubPR(repo, prHead string) (ghrepo.Interface, *api.PullRequest) {
defaultBranch := ""
if idx := strings.IndexRune(repo, ':'); idx >= 0 {
defaultBranch = repo[idx+1:]
repo = repo[:idx]
}
baseRepo, err := ghrepo.FromFullName(repo)
if err != nil {
panic(err)
}
if defaultBranch != "" {
baseRepo = api.InitRepoHostname(&api.Repository{
Name: baseRepo.RepoName(),
Owner: api.RepositoryOwner{Login: baseRepo.RepoOwner()},
DefaultBranchRef: api.BranchRef{Name: defaultBranch},
}, baseRepo.RepoHost())
}
idx := strings.IndexRune(prHead, ':')
headRefName := prHead[idx+1:]
headRepo, err := ghrepo.FromFullName(prHead[:idx])
if err != nil {
panic(err)
}
return baseRepo, &api.PullRequest{
ID: "THE-ID",
Number: 96,
State: "OPEN",
HeadRefName: headRefName,
HeadRepositoryOwner: api.Owner{Login: headRepo.RepoOwner()},
HeadRepository: &api.PRRepository{Name: headRepo.RepoName()},
IsCrossRepository: !ghrepo.IsSame(baseRepo, headRepo),
}
}
func runCommand(rt http.RoundTripper, 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 "trunk", nil
},
GitClient: &git.Client{GitPath: "some/path/git"},
}
cmd := NewCmdClose(factory, nil)
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 TestNoArgs(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
_, err := runCommand(http, true, "")
assert.EqualError(t, err, "cannot close pull request: number, url, or branch required")
}
func TestPrClose(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
baseRepo, pr := stubPR("OWNER/REPO", "OWNER/REPO:feature")
pr.Title = "The title of the PR"
shared.StubFinderForRunCommandStyleTests(t, "96", pr, baseRepo)
http.Register(
httpmock.GraphQL(`mutation PullRequestClose\b`),
httpmock.GraphQLMutation(`{"id": "THE-ID"}`,
func(inputs map[string]interface{}) {
assert.Equal(t, inputs["pullRequestId"], "THE-ID")
}),
)
output, err := runCommand(http, true, "96")
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, "✓ Closed pull request OWNER/REPO#96 (The title of the PR)\n", output.Stderr())
}
func TestPrClose_alreadyClosed(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
baseRepo, pr := stubPR("OWNER/REPO", "OWNER/REPO:feature")
pr.State = "CLOSED"
pr.Title = "The title of the PR"
shared.StubFinderForRunCommandStyleTests(t, "96", pr, baseRepo)
output, err := runCommand(http, true, "96")
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, "! Pull request OWNER/REPO#96 (The title of the PR) is already closed\n", output.Stderr())
}
func TestPrClose_deleteBranch_sameRepo(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
baseRepo, pr := stubPR("OWNER/REPO", "OWNER/REPO:blueberries")
pr.Title = "The title of the PR"
shared.StubFinderForRunCommandStyleTests(t, "96", pr, baseRepo)
http.Register(
httpmock.GraphQL(`mutation PullRequestClose\b`),
httpmock.GraphQLMutation(`{"id": "THE-ID"}`,
func(inputs map[string]interface{}) {
assert.Equal(t, inputs["pullRequestId"], "THE-ID")
}),
)
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, true, `96 --delete-branch`)
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, heredoc.Doc(`
✓ Closed pull request OWNER/REPO#96 (The title of the PR)
✓ Deleted branch blueberries
`), output.Stderr())
}
func TestPrClose_deleteBranch_crossRepo(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
baseRepo, pr := stubPR("OWNER/REPO", "hubot/REPO:blueberries")
pr.Title = "The title of the PR"
shared.StubFinderForRunCommandStyleTests(t, "96", pr, baseRepo)
http.Register(
httpmock.GraphQL(`mutation PullRequestClose\b`),
httpmock.GraphQLMutation(`{"id": "THE-ID"}`,
func(inputs map[string]interface{}) {
assert.Equal(t, inputs["pullRequestId"], "THE-ID")
}),
)
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, true, `96 --delete-branch`)
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, heredoc.Doc(`
✓ Closed pull request OWNER/REPO#96 (The title of the PR)
! Skipped deleting the remote branch of a pull request from fork
✓ Deleted branch blueberries
`), output.Stderr())
}
func TestPrClose_deleteBranch_sameBranch(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
baseRepo, pr := stubPR("OWNER/REPO:main", "OWNER/REPO:trunk")
pr.Title = "The title of the PR"
shared.StubFinderForRunCommandStyleTests(t, "96", pr, baseRepo)
http.Register(
httpmock.GraphQL(`mutation PullRequestClose\b`),
httpmock.GraphQLMutation(`{"id": "THE-ID"}`,
func(inputs map[string]interface{}) {
assert.Equal(t, inputs["pullRequestId"], "THE-ID")
}),
)
http.Register(
httpmock.REST("DELETE", "repos/OWNER/REPO/git/refs/heads/trunk"),
httpmock.StringResponse(`{}`))
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git checkout main`, 0, "")
cs.Register(`git rev-parse --verify refs/heads/trunk`, 0, "")
cs.Register(`git branch -D trunk`, 0, "")
output, err := runCommand(http, true, `96 --delete-branch`)
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, heredoc.Doc(`
✓ Closed pull request OWNER/REPO#96 (The title of the PR)
✓ Deleted branch trunk and switched to branch main
`), output.Stderr())
}
func TestPrClose_deleteBranch_notInGitRepo(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
baseRepo, pr := stubPR("OWNER/REPO:main", "OWNER/REPO:trunk")
pr.Title = "The title of the PR"
shared.StubFinderForRunCommandStyleTests(t, "96", pr, baseRepo)
http.Register(
httpmock.GraphQL(`mutation PullRequestClose\b`),
httpmock.GraphQLMutation(`{"id": "THE-ID"}`,
func(inputs map[string]interface{}) {
assert.Equal(t, inputs["pullRequestId"], "THE-ID")
}),
)
http.Register(
httpmock.REST("DELETE", "repos/OWNER/REPO/git/refs/heads/trunk"),
httpmock.StringResponse(`{}`))
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git rev-parse --verify refs/heads/trunk`, 128, "could not determine current branch: fatal: not a git repository (or any of the parent directories): .git")
output, err := runCommand(http, true, `96 --delete-branch`)
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, heredoc.Doc(`
✓ Closed pull request OWNER/REPO#96 (The title of the PR)
! Skipped deleting the local branch since current directory is not a git repository
✓ Deleted branch trunk
`), output.Stderr())
}
func TestPrClose_withComment(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
baseRepo, pr := stubPR("OWNER/REPO", "OWNER/REPO:feature")
pr.Title = "The title of the PR"
shared.StubFinderForRunCommandStyleTests(t, "96", pr, baseRepo)
http.Register(
httpmock.GraphQL(`mutation CommentCreate\b`),
httpmock.GraphQLMutation(`
{ "data": { "addComment": { "commentEdge": { "node": {
"url": "https://github.com/OWNER/REPO/issues/123#issuecomment-456"
} } } } }`,
func(inputs map[string]interface{}) {
assert.Equal(t, "THE-ID", inputs["subjectId"])
assert.Equal(t, "closing comment", inputs["body"])
}),
)
http.Register(
httpmock.GraphQL(`mutation PullRequestClose\b`),
httpmock.GraphQLMutation(`{"id": "THE-ID"}`,
func(inputs map[string]interface{}) {
assert.Equal(t, inputs["pullRequestId"], "THE-ID")
}),
)
output, err := runCommand(http, true, "96 --comment 'closing comment'")
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, "✓ Closed pull request OWNER/REPO#96 (The title of the PR)\n", output.Stderr())
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/close/close.go | pkg/cmd/pr/close/close.go | package close
import (
"context"
"fmt"
"net/http"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/git"
"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/spf13/cobra"
)
type CloseOptions struct {
HttpClient func() (*http.Client, error)
GitClient *git.Client
IO *iostreams.IOStreams
Branch func() (string, error)
Finder shared.PRFinder
SelectorArg string
Comment string
DeleteBranch bool
DeleteLocalBranch bool
}
func NewCmdClose(f *cmdutil.Factory, runF func(*CloseOptions) error) *cobra.Command {
opts := &CloseOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
GitClient: f.GitClient,
Branch: f.Branch,
}
cmd := &cobra.Command{
Use: "close {<number> | <url> | <branch>}",
Short: "Close a pull request",
Args: cmdutil.ExactArgs(1, "cannot close pull request: number, url, or branch required"),
RunE: func(cmd *cobra.Command, args []string) error {
opts.Finder = shared.NewFinder(f)
if len(args) > 0 {
opts.SelectorArg = args[0]
}
opts.DeleteLocalBranch = !cmd.Flags().Changed("repo")
if runF != nil {
return runF(opts)
}
return closeRun(opts)
},
}
cmd.Flags().StringVarP(&opts.Comment, "comment", "c", "", "Leave a closing comment")
cmd.Flags().BoolVarP(&opts.DeleteBranch, "delete-branch", "d", false, "Delete the local and remote branch after close")
return cmd
}
func closeRun(opts *CloseOptions) error {
cs := opts.IO.ColorScheme()
findOptions := shared.FindOptions{
Selector: opts.SelectorArg,
Fields: []string{"state", "number", "title", "isCrossRepository", "headRefName"},
}
pr, baseRepo, err := opts.Finder.Find(findOptions)
if err != nil {
return err
}
if pr.State == "MERGED" {
fmt.Fprintf(opts.IO.ErrOut, "%s Pull request %s#%d (%s) can't be closed because it was already merged\n", cs.FailureIcon(), ghrepo.FullName(baseRepo), pr.Number, pr.Title)
return cmdutil.SilentError
} else if !pr.IsOpen() {
fmt.Fprintf(opts.IO.ErrOut, "%s Pull request %s#%d (%s) is already closed\n", cs.WarningIcon(), ghrepo.FullName(baseRepo), pr.Number, pr.Title)
return nil
}
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
if opts.Comment != "" {
commentOpts := &shared.CommentableOptions{
Body: opts.Comment,
HttpClient: opts.HttpClient,
InputType: shared.InputTypeInline,
Quiet: true,
RetrieveCommentable: func() (shared.Commentable, ghrepo.Interface, error) {
return pr, baseRepo, nil
},
}
err := shared.CommentableRun(commentOpts)
if err != nil {
return err
}
}
err = api.PullRequestClose(httpClient, baseRepo, pr.ID)
if err != nil {
return fmt.Errorf("API call failed: %w", err)
}
fmt.Fprintf(opts.IO.ErrOut, "%s Closed pull request %s#%d (%s)\n", cs.SuccessIconWithColor(cs.Red), ghrepo.FullName(baseRepo), pr.Number, pr.Title)
if opts.DeleteBranch {
ctx := context.Background()
branchSwitchString := ""
apiClient := api.NewClientFromHTTP(httpClient)
localBranchExists := opts.GitClient.HasLocalBranch(ctx, pr.HeadRefName)
if opts.DeleteLocalBranch {
if localBranchExists {
currentBranch, err := opts.Branch()
if err != nil {
return err
}
var branchToSwitchTo string
if currentBranch == pr.HeadRefName {
branchToSwitchTo, err = api.RepoDefaultBranch(apiClient, baseRepo)
if err != nil {
return err
}
err = opts.GitClient.CheckoutBranch(ctx, branchToSwitchTo)
if err != nil {
return err
}
}
if err := opts.GitClient.DeleteLocalBranch(ctx, pr.HeadRefName); err != nil {
return fmt.Errorf("failed to delete local branch %s: %w", cs.Cyan(pr.HeadRefName), err)
}
if branchToSwitchTo != "" {
branchSwitchString = fmt.Sprintf(" and switched to branch %s", cs.Cyan(branchToSwitchTo))
}
} else {
fmt.Fprintf(opts.IO.ErrOut, "%s Skipped deleting the local branch since current directory is not a git repository\n", cs.WarningIcon())
}
}
if pr.IsCrossRepository {
fmt.Fprintf(opts.IO.ErrOut, "%s Skipped deleting the remote branch of a pull request from fork\n", cs.WarningIcon())
if !opts.DeleteLocalBranch {
return nil
}
} else {
if err := api.BranchDeleteRemote(apiClient, baseRepo, pr.HeadRefName); err != nil {
return fmt.Errorf("failed to delete remote branch %s: %w", cs.Cyan(pr.HeadRefName), err)
}
}
fmt.Fprintf(opts.IO.ErrOut, "%s Deleted branch %s%s\n", cs.SuccessIconWithColor(cs.Red), cs.Cyan(pr.HeadRefName), branchSwitchString)
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/ready/ready.go | pkg/cmd/pr/ready/ready.go | package ready
import (
"fmt"
"net/http"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
"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/spf13/cobra"
)
type ReadyOptions struct {
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
Finder shared.PRFinder
SelectorArg string
Undo bool
}
func NewCmdReady(f *cmdutil.Factory, runF func(*ReadyOptions) error) *cobra.Command {
opts := &ReadyOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
}
cmd := &cobra.Command{
Use: "ready [<number> | <url> | <branch>]",
Short: "Mark a pull request as ready for review",
Long: heredoc.Docf(`
Mark a pull request as ready for review.
Without an argument, the pull request that belongs to the current branch
is marked as ready.
If supported by your plan, convert to draft with %[1]s--undo%[1]s
`, "`"),
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]
}
if runF != nil {
return runF(opts)
}
return readyRun(opts)
},
}
cmd.Flags().BoolVar(&opts.Undo, "undo", false, `Convert a pull request to "draft"`)
return cmd
}
func readyRun(opts *ReadyOptions) error {
cs := opts.IO.ColorScheme()
findOptions := shared.FindOptions{
Selector: opts.SelectorArg,
Fields: []string{"id", "number", "state", "isDraft"},
}
pr, baseRepo, err := opts.Finder.Find(findOptions)
if err != nil {
return err
}
if !pr.IsOpen() {
fmt.Fprintf(opts.IO.ErrOut, "%s Pull request %s#%d is closed. Only draft pull requests can be marked as \"ready for review\"\n", cs.FailureIcon(), ghrepo.FullName(baseRepo), pr.Number)
return cmdutil.SilentError
}
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
apiClient := api.NewClientFromHTTP(httpClient)
if opts.Undo { // convert to draft
if pr.IsDraft {
fmt.Fprintf(opts.IO.ErrOut, "%s Pull request %s#%d is already \"in draft\"\n", cs.WarningIcon(), ghrepo.FullName(baseRepo), pr.Number)
return nil
}
err = api.ConvertPullRequestToDraft(apiClient, baseRepo, pr)
if err != nil {
return fmt.Errorf("API call failed: %w", err)
}
fmt.Fprintf(opts.IO.ErrOut, "%s Pull request %s#%d is converted to \"draft\"\n", cs.SuccessIconWithColor(cs.Green), ghrepo.FullName(baseRepo), pr.Number)
} else { // mark as ready for review
if !pr.IsDraft {
fmt.Fprintf(opts.IO.ErrOut, "%s Pull request %s#%d is already \"ready for review\"\n", cs.WarningIcon(), ghrepo.FullName(baseRepo), pr.Number)
return nil
}
err = api.PullRequestReady(apiClient, baseRepo, pr)
if err != nil {
return fmt.Errorf("API call failed: %w", err)
}
fmt.Fprintf(opts.IO.ErrOut, "%s Pull request %s#%d is marked as \"ready for review\"\n", cs.SuccessIconWithColor(cs.Green), ghrepo.FullName(baseRepo), pr.Number)
}
return nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/ready/ready_test.go | pkg/cmd/pr/ready/ready_test.go | package ready
import (
"bytes"
"io"
"net/http"
"testing"
"github.com/cli/cli/v2/api"
"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/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 Test_NewCmdReady(t *testing.T) {
tests := []struct {
name string
args string
isTTY bool
want ReadyOptions
wantErr string
}{
{
name: "number argument",
args: "123",
isTTY: true,
want: ReadyOptions{
SelectorArg: "123",
},
},
{
name: "no argument",
args: "",
isTTY: true,
want: ReadyOptions{
SelectorArg: "",
},
},
{
name: "no argument with --repo override",
args: "-R owner/repo",
isTTY: true,
wantErr: "argument required when using the --repo flag",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
ios.SetStdoutTTY(tt.isTTY)
ios.SetStdinTTY(tt.isTTY)
ios.SetStderrTTY(tt.isTTY)
f := &cmdutil.Factory{
IOStreams: ios,
}
var opts *ReadyOptions
cmd := NewCmdReady(f, func(o *ReadyOptions) 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)
})
}
}
func runCommand(rt http.RoundTripper, 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
},
}
cmd := NewCmdReady(factory, nil)
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 TestPRReady(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t, "123", &api.PullRequest{
ID: "THE-ID",
Number: 123,
State: "OPEN",
IsDraft: true,
}, ghrepo.New("OWNER", "REPO"))
http.Register(
httpmock.GraphQL(`mutation PullRequestReadyForReview\b`),
httpmock.GraphQLMutation(`{"id": "THE-ID"}`,
func(inputs map[string]interface{}) {
assert.Equal(t, inputs["pullRequestId"], "THE-ID")
}),
)
output, err := runCommand(http, true, "123")
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, "✓ Pull request OWNER/REPO#123 is marked as \"ready for review\"\n", output.Stderr())
}
func TestPRReady_alreadyReady(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t, "123", &api.PullRequest{
ID: "THE-ID",
Number: 123,
State: "OPEN",
IsDraft: false,
}, ghrepo.New("OWNER", "REPO"))
output, err := runCommand(http, true, "123")
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, "! Pull request OWNER/REPO#123 is already \"ready for review\"\n", output.Stderr())
}
func TestPRReadyUndo(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t, "123", &api.PullRequest{
ID: "THE-ID",
Number: 123,
State: "OPEN",
IsDraft: false,
}, ghrepo.New("OWNER", "REPO"))
http.Register(
httpmock.GraphQL(`mutation ConvertPullRequestToDraft\b`),
httpmock.GraphQLMutation(`{"id": "THE-ID"}`,
func(inputs map[string]interface{}) {
assert.Equal(t, inputs["pullRequestId"], "THE-ID")
}),
)
output, err := runCommand(http, true, "123 --undo")
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, "✓ Pull request OWNER/REPO#123 is converted to \"draft\"\n", output.Stderr())
}
func TestPRReadyUndo_alreadyDraft(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t, "123", &api.PullRequest{
ID: "THE-ID",
Number: 123,
State: "OPEN",
IsDraft: true,
}, ghrepo.New("OWNER", "REPO"))
output, err := runCommand(http, true, "123 --undo")
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, "! Pull request OWNER/REPO#123 is already \"in draft\"\n", output.Stderr())
}
func TestPRReady_closed(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t, "123", &api.PullRequest{
ID: "THE-ID",
Number: 123,
State: "CLOSED",
IsDraft: true,
}, ghrepo.New("OWNER", "REPO"))
output, err := runCommand(http, true, "123")
assert.EqualError(t, err, "SilentError")
assert.Equal(t, "", output.String())
assert.Equal(t, "X Pull request OWNER/REPO#123 is closed. Only draft pull requests can be marked as \"ready for review\"\n", output.Stderr())
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/comment/comment.go | pkg/cmd/pr/comment/comment.go | package comment
import (
"github.com/MakeNowJust/heredoc"
"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/spf13/cobra"
)
func NewCmdComment(f *cmdutil.Factory, runF func(*shared.CommentableOptions) error) *cobra.Command {
opts := &shared.CommentableOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
EditSurvey: shared.CommentableEditSurvey(f.Config, f.IOStreams),
InteractiveEditSurvey: shared.CommentableInteractiveEditSurvey(f.Config, f.IOStreams),
ConfirmSubmitSurvey: shared.CommentableConfirmSubmitSurvey(f.Prompter),
ConfirmCreateIfNoneSurvey: shared.CommentableInteractiveCreateIfNoneSurvey(f.Prompter),
ConfirmDeleteLastComment: shared.CommentableConfirmDeleteLastComment(f.Prompter),
OpenInBrowser: f.Browser.Browse,
}
var bodyFile string
cmd := &cobra.Command{
Use: "comment [<number> | <url> | <branch>]",
Short: "Add a comment to a pull request",
Long: heredoc.Doc(`
Add a comment to a GitHub pull request.
Without the body text supplied through flags, the command will interactively
prompt for the comment text.
`),
Example: heredoc.Doc(`
$ gh pr comment 13 --body "Hi from GitHub CLI"
`),
Args: cobra.MaximumNArgs(1),
PreRunE: func(cmd *cobra.Command, args []string) error {
if repoOverride, _ := cmd.Flags().GetString("repo"); repoOverride != "" && len(args) == 0 {
return cmdutil.FlagErrorf("argument required when using the --repo flag")
}
var selector string
if len(args) > 0 {
selector = args[0]
}
fields := []string{"id", "url"}
if opts.EditLast || opts.DeleteLast {
fields = append(fields, "comments")
}
finder := shared.NewFinder(f)
opts.RetrieveCommentable = func() (shared.Commentable, ghrepo.Interface, error) {
return finder.Find(shared.FindOptions{
Selector: selector,
Fields: fields,
})
}
return shared.CommentablePreRun(cmd, opts)
},
RunE: func(cmd *cobra.Command, args []string) error {
if bodyFile != "" {
b, err := cmdutil.ReadFile(bodyFile, opts.IO.In)
if err != nil {
return err
}
opts.Body = string(b)
}
if runF != nil {
return runF(opts)
}
return shared.CommentableRun(opts)
},
}
cmd.Flags().StringVarP(&opts.Body, "body", "b", "", "The comment body `text`")
cmd.Flags().StringVarP(&bodyFile, "body-file", "F", "", "Read body text from `file` (use \"-\" to read from standard input)")
cmd.Flags().BoolP("editor", "e", false, "Skip prompts and open the text editor to write the body in")
cmd.Flags().BoolP("web", "w", false, "Open the web browser to write the comment")
cmd.Flags().BoolVar(&opts.EditLast, "edit-last", false, "Edit the last comment of the current user")
cmd.Flags().BoolVar(&opts.DeleteLast, "delete-last", false, "Delete the last comment of the current user")
cmd.Flags().BoolVar(&opts.DeleteLastConfirmed, "yes", false, "Skip the delete confirmation prompt when --delete-last is provided")
cmd.Flags().BoolVar(&opts.CreateIfNone, "create-if-none", false, "Create a new comment if no comments are found. Can be used only with --edit-last")
return cmd
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/comment/comment_test.go | pkg/cmd/pr/comment/comment_test.go | package comment
import (
"bytes"
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
"testing"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/browser"
"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/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewCmdComment(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
input string
stdin string
output shared.CommentableOptions
wantsErr bool
isTTY bool
}{
{
name: "no arguments",
input: "",
output: shared.CommentableOptions{
Interactive: true,
InputType: 0,
Body: "",
},
isTTY: true,
wantsErr: false,
},
{
name: "two arguments",
input: "1 2",
output: shared.CommentableOptions{},
isTTY: true,
wantsErr: true,
},
{
name: "pr number",
input: "1",
output: shared.CommentableOptions{
Interactive: true,
InputType: 0,
Body: "",
},
isTTY: true,
wantsErr: false,
},
{
name: "pr url",
input: "https://github.com/OWNER/REPO/pull/12",
output: shared.CommentableOptions{
Interactive: true,
InputType: 0,
Body: "",
},
isTTY: true,
wantsErr: false,
},
{
name: "pr branch",
input: "branch-name",
output: shared.CommentableOptions{
Interactive: true,
InputType: 0,
Body: "",
},
isTTY: true,
wantsErr: false,
},
{
name: "body flag",
input: "1 --body test",
output: shared.CommentableOptions{
Interactive: false,
InputType: shared.InputTypeInline,
Body: "test",
},
isTTY: true,
wantsErr: false,
},
{
name: "body from stdin",
input: "1 --body-file -",
stdin: "this is on standard input",
output: shared.CommentableOptions{
Interactive: false,
InputType: shared.InputTypeInline,
Body: "this is on standard input",
},
isTTY: true,
wantsErr: false,
},
{
name: "body from file",
input: fmt.Sprintf("1 --body-file '%s'", tmpFile),
output: shared.CommentableOptions{
Interactive: false,
InputType: shared.InputTypeInline,
Body: "a body from file",
},
isTTY: true,
wantsErr: false,
},
{
name: "editor flag",
input: "1 --editor",
output: shared.CommentableOptions{
Interactive: false,
InputType: shared.InputTypeEditor,
Body: "",
},
isTTY: true,
wantsErr: false,
},
{
name: "web flag",
input: "1 --web",
output: shared.CommentableOptions{
Interactive: false,
InputType: shared.InputTypeWeb,
Body: "",
},
isTTY: true,
wantsErr: false,
},
{
name: "edit last flag",
input: "1 --edit-last",
output: shared.CommentableOptions{
Interactive: true,
InputType: shared.InputTypeEditor,
Body: "",
EditLast: true,
},
isTTY: true,
wantsErr: false,
},
{
name: "edit last flag with create if none",
input: "1 --edit-last --create-if-none",
output: shared.CommentableOptions{
Interactive: true,
InputType: shared.InputTypeEditor,
Body: "",
EditLast: true,
CreateIfNone: true,
},
isTTY: true,
wantsErr: false,
},
{
name: "delete last flag non-interactive",
input: "1 --delete-last",
isTTY: false,
wantsErr: true,
},
{
name: "delete last flag and pre-confirmation non-interactive",
input: "1 --delete-last --yes",
output: shared.CommentableOptions{
DeleteLast: true,
DeleteLastConfirmed: true,
},
isTTY: false,
wantsErr: false,
},
{
name: "delete last flag interactive",
input: "1 --delete-last",
output: shared.CommentableOptions{
Interactive: true,
DeleteLast: true,
},
isTTY: true,
wantsErr: false,
},
{
name: "delete last flag and pre-confirmation interactive",
input: "1 --delete-last --yes",
output: shared.CommentableOptions{
Interactive: true,
DeleteLast: true,
DeleteLastConfirmed: true,
},
isTTY: true,
wantsErr: false,
},
{
name: "delete last flag and pre-confirmation with web flag",
input: "1 --delete-last --yes --web",
isTTY: true,
wantsErr: true,
},
{
name: "delete last flag and pre-confirmation with editor flag",
input: "1 --delete-last --yes --editor",
isTTY: true,
wantsErr: true,
},
{
name: "delete last flag and pre-confirmation with body flag",
input: "1 --delete-last --yes --body",
isTTY: true,
wantsErr: true,
},
{
name: "delete pre-confirmation without delete last flag",
input: "1 --yes",
isTTY: true,
wantsErr: true,
},
{
name: "body and body-file flags",
input: "1 --body 'test' --body-file 'test-file.txt'",
output: shared.CommentableOptions{},
isTTY: true,
wantsErr: true,
},
{
name: "editor and web flags",
input: "1 --editor --web",
output: shared.CommentableOptions{},
isTTY: true,
wantsErr: true,
},
{
name: "editor and body flags",
input: "1 --editor --body test",
output: shared.CommentableOptions{},
isTTY: true,
wantsErr: true,
},
{
name: "web and body flags",
input: "1 --web --body test",
output: shared.CommentableOptions{},
isTTY: true,
wantsErr: true,
},
{
name: "editor, web, and body flags",
input: "1 --editor --web --body test",
output: shared.CommentableOptions{},
isTTY: true,
wantsErr: true,
},
{
name: "create-if-none flag without edit-last",
input: "1 --create-if-none",
output: shared.CommentableOptions{},
isTTY: true,
wantsErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, stdin, _, _ := iostreams.Test()
isTTY := tt.isTTY
ios.SetStdoutTTY(isTTY)
ios.SetStdinTTY(isTTY)
ios.SetStderrTTY(isTTY)
if tt.stdin != "" {
_, _ = stdin.WriteString(tt.stdin)
}
f := &cmdutil.Factory{
IOStreams: ios,
Browser: &browser.Stub{},
}
argv, err := shlex.Split(tt.input)
assert.NoError(t, err)
var gotOpts *shared.CommentableOptions
cmd := NewCmdComment(f, func(opts *shared.CommentableOptions) error {
gotOpts = opts
return nil
})
cmd.Flags().BoolP("help", "x", false, "")
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
_, err = cmd.ExecuteC()
if tt.wantsErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.output.Interactive, gotOpts.Interactive)
assert.Equal(t, tt.output.InputType, gotOpts.InputType)
assert.Equal(t, tt.output.Body, gotOpts.Body)
assert.Equal(t, tt.output.DeleteLast, gotOpts.DeleteLast)
assert.Equal(t, tt.output.DeleteLastConfirmed, gotOpts.DeleteLastConfirmed)
})
}
}
func Test_commentRun(t *testing.T) {
tests := []struct {
name string
input *shared.CommentableOptions
emptyComments bool
comments api.Comments
httpStubs func(*testing.T, *httpmock.Registry)
stdout string
stderr string
wantsErr bool
}{
{
name: "creating new comment with interactive editor succeeds",
input: &shared.CommentableOptions{
Interactive: true,
InputType: 0,
Body: "",
InteractiveEditSurvey: func(string) (string, error) { return "comment body", nil },
ConfirmSubmitSurvey: func() (bool, error) { return true, nil },
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockCommentCreate(t, reg)
},
stdout: "https://github.com/OWNER/REPO/pull/123#issuecomment-456\n",
},
{
name: "updating last comment with interactive editor fails if there are no comments and decline prompt to create",
input: &shared.CommentableOptions{
Interactive: true,
InputType: 0,
Body: "",
EditLast: true,
InteractiveEditSurvey: func(string) (string, error) { return "comment body", nil },
ConfirmSubmitSurvey: func() (bool, error) { return true, nil },
ConfirmCreateIfNoneSurvey: func() (bool, error) { return false, nil },
},
emptyComments: true,
wantsErr: true,
stdout: "no comments found for current user",
},
{
name: "updating last comment with interactive editor succeeds if there are comments",
input: &shared.CommentableOptions{
Interactive: true,
InputType: 0,
Body: "",
EditLast: true,
InteractiveEditSurvey: func(string) (string, error) { return "comment body", nil },
ConfirmSubmitSurvey: func() (bool, error) { return true, nil },
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockCommentUpdate(t, reg)
},
emptyComments: false,
stdout: "https://github.com/OWNER/REPO/pull/123#issuecomment-111\n",
},
{
name: "updating last comment with interactive editor creates new comment if there are no comments but --create-if-none",
input: &shared.CommentableOptions{
Interactive: true,
InputType: 0,
Body: "",
EditLast: true,
CreateIfNone: true,
InteractiveEditSurvey: func(string) (string, error) { return "comment body", nil },
ConfirmCreateIfNoneSurvey: func() (bool, error) { return true, nil },
ConfirmSubmitSurvey: func() (bool, error) { return true, nil },
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockCommentCreate(t, reg)
},
emptyComments: true,
stderr: "No comments found. Creating a new comment.\n",
stdout: "https://github.com/OWNER/REPO/pull/123#issuecomment-456\n",
},
{
name: "creating new comment with non-interactive web opens pull request in browser focusing on new comment",
input: &shared.CommentableOptions{
Interactive: false,
InputType: shared.InputTypeWeb,
Body: "",
OpenInBrowser: func(string) error { return nil },
},
emptyComments: true,
stderr: "Opening https://github.com/OWNER/REPO/pull/123 in your browser.\n",
},
{
name: "updating last comment with non-interactive web opens pull request in browser focusing on the last comment",
input: &shared.CommentableOptions{
Interactive: false,
InputType: shared.InputTypeWeb,
Body: "",
EditLast: true,
OpenInBrowser: func(u string) error {
assert.Contains(t, u, "#issuecomment-111")
return nil
},
},
emptyComments: false,
stderr: "Opening https://github.com/OWNER/REPO/pull/123 in your browser.\n",
},
{
name: "updating last comment with non-interactive web errors because there are no comments",
input: &shared.CommentableOptions{
Interactive: false,
InputType: shared.InputTypeWeb,
Body: "",
EditLast: true,
},
emptyComments: true,
wantsErr: true,
stdout: "no comments found for current user",
},
{
name: "creating new comment with non-interactive editor succeeds",
input: &shared.CommentableOptions{
Interactive: false,
InputType: shared.InputTypeEditor,
Body: "",
EditSurvey: func(string) (string, error) { return "comment body", nil },
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockCommentCreate(t, reg)
},
stdout: "https://github.com/OWNER/REPO/pull/123#issuecomment-456\n",
},
{
name: "updating last comment with non-interactive editor fails if there are no comments",
input: &shared.CommentableOptions{
Interactive: false,
InputType: shared.InputTypeEditor,
Body: "",
EditLast: true,
EditSurvey: func(string) (string, error) { return "comment body", nil },
},
emptyComments: true,
wantsErr: true,
stdout: "no comments found for current user",
},
{
name: "updating last comment with non-interactive editor succeeds if there are comments",
input: &shared.CommentableOptions{
Interactive: false,
InputType: shared.InputTypeEditor,
Body: "",
EditLast: true,
EditSurvey: func(string) (string, error) { return "comment body", nil },
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockCommentUpdate(t, reg)
},
stdout: "https://github.com/OWNER/REPO/pull/123#issuecomment-111\n",
},
{
name: "updating last comment with non-interactive editor creates new comment if there are no comments but --create-if-none",
input: &shared.CommentableOptions{
Interactive: false,
InputType: shared.InputTypeEditor,
Body: "",
EditLast: true,
CreateIfNone: true,
EditSurvey: func(string) (string, error) { return "comment body", nil },
},
emptyComments: true,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockCommentCreate(t, reg)
},
stdout: "https://github.com/OWNER/REPO/pull/123#issuecomment-456\n",
},
{
name: "creating new comment with non-interactive inline succeeds if comment body is provided",
input: &shared.CommentableOptions{
Interactive: false,
InputType: shared.InputTypeInline,
Body: "comment body",
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockCommentCreate(t, reg)
},
stdout: "https://github.com/OWNER/REPO/pull/123#issuecomment-456\n",
},
{
name: "updating last comment with non-interactive inline succeeds if there are comments and comment body is provided",
input: &shared.CommentableOptions{
Interactive: false,
InputType: shared.InputTypeInline,
Body: "comment body",
EditLast: true,
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockCommentUpdate(t, reg)
},
emptyComments: false,
stdout: "https://github.com/OWNER/REPO/pull/123#issuecomment-111\n",
},
{
name: "updating last comment with non-interactive inline creates new comment if there are no comments but --create-if-none",
input: &shared.CommentableOptions{
Interactive: false,
InputType: shared.InputTypeInline,
Body: "comment body",
EditLast: true,
CreateIfNone: true,
},
emptyComments: true,
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockCommentCreate(t, reg)
},
stdout: "https://github.com/OWNER/REPO/pull/123#issuecomment-456\n",
},
{
name: "deleting last comment non-interactively without any comment",
input: &shared.CommentableOptions{
Interactive: false,
DeleteLast: true,
},
emptyComments: true,
wantsErr: true,
stdout: "no comments found for current user",
},
{
name: "deleting last comment interactively without any comment",
input: &shared.CommentableOptions{
Interactive: true,
DeleteLast: true,
},
emptyComments: true,
wantsErr: true,
stdout: "no comments found for current user",
},
{
name: "deleting last comment non-interactively and pre-confirmed",
input: &shared.CommentableOptions{
Interactive: false,
DeleteLast: true,
DeleteLastConfirmed: true,
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockCommentDelete(t, reg)
},
stderr: "Comment deleted\n",
},
{
name: "deleting last comment interactively and pre-confirmed",
input: &shared.CommentableOptions{
Interactive: true,
DeleteLast: true,
DeleteLastConfirmed: true,
},
comments: api.Comments{Nodes: []api.Comment{
{ID: "id1", Author: api.CommentAuthor{Login: "octocat"}, URL: "https://github.com/OWNER/REPO/pull/123#issuecomment-111", ViewerDidAuthor: true, Body: "comment body"},
}},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockCommentDelete(t, reg)
},
stderr: "Comment deleted\n",
},
{
name: "deleting last comment interactively and confirmed",
input: &shared.CommentableOptions{
Interactive: true,
DeleteLast: true,
ConfirmDeleteLastComment: func(body string) (bool, error) {
if body != "comment body" {
return false, errors.New("unexpected comment body")
}
return true, nil
},
},
comments: api.Comments{Nodes: []api.Comment{
{ID: "id1", Author: api.CommentAuthor{Login: "octocat"}, URL: "https://github.com/OWNER/REPO/pull/123#issuecomment-111", ViewerDidAuthor: true, Body: "comment body"},
}},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockCommentDelete(t, reg)
},
stdout: "! Deleted comments cannot be recovered.\n",
stderr: "Comment deleted\n",
},
{
name: "deleting last comment interactively and confirmation declined",
input: &shared.CommentableOptions{
Interactive: true,
DeleteLast: true,
ConfirmDeleteLastComment: func(body string) (bool, error) {
if body != "comment body" {
return false, errors.New("unexpected comment body")
}
return true, nil
},
},
comments: api.Comments{Nodes: []api.Comment{
{ID: "id1", Author: api.CommentAuthor{Login: "octocat"}, URL: "https://github.com/OWNER/REPO/pull/123#issuecomment-111", ViewerDidAuthor: true, Body: "comment body"},
}},
wantsErr: true,
stdout: "deletion not confirmed",
},
{
name: "deleting last comment interactively and confirmed with long comment body",
input: &shared.CommentableOptions{
Interactive: true,
DeleteLast: true,
ConfirmDeleteLastComment: func(body string) (bool, error) {
if body != "Lorem ipsum dolor sit amet, consectet lo..." {
return false, errors.New("unexpected comment body")
}
return true, nil
},
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockCommentDelete(t, reg)
},
comments: api.Comments{Nodes: []api.Comment{
{ID: "id1", Author: api.CommentAuthor{Login: "octocat"}, URL: "https://github.com/OWNER/REPO/pull/123#issuecomment-111", ViewerDidAuthor: true, Body: "Lorem ipsum dolor sit amet, consectet lorem ipsum again"},
}},
wantsErr: false,
stdout: "! Deleted comments cannot be recovered.\n",
stderr: "Comment deleted\n",
},
}
for _, tt := range tests {
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdoutTTY(true)
ios.SetStdinTTY(true)
ios.SetStderrTTY(true)
reg := &httpmock.Registry{}
defer reg.Verify(t)
if tt.httpStubs != nil {
tt.httpStubs(t, reg)
}
httpClient := func() (*http.Client, error) { return &http.Client{Transport: reg}, nil }
tt.input.IO = ios
tt.input.HttpClient = httpClient
comments := api.Comments{Nodes: []api.Comment{
{ID: "id1", Author: api.CommentAuthor{Login: "octocat"}, URL: "https://github.com/OWNER/REPO/pull/123#issuecomment-111", ViewerDidAuthor: true},
{ID: "id2", Author: api.CommentAuthor{Login: "monalisa"}, URL: "https://github.com/OWNER/REPO/pull/123#issuecomment-222"},
}}
if tt.emptyComments {
comments.Nodes = []api.Comment{}
} else if len(tt.comments.Nodes) > 0 {
comments = tt.comments
}
tt.input.RetrieveCommentable = func() (shared.Commentable, ghrepo.Interface, error) {
return &api.PullRequest{
Number: 123,
URL: "https://github.com/OWNER/REPO/pull/123",
Comments: comments,
}, ghrepo.New("OWNER", "REPO"), nil
}
t.Run(tt.name, func(t *testing.T) {
err := shared.CommentableRun(tt.input)
if tt.wantsErr {
assert.Error(t, err)
assert.Equal(t, tt.stderr, stderr.String())
return
}
assert.NoError(t, err)
assert.Equal(t, tt.stdout, stdout.String())
assert.Equal(t, tt.stderr, stderr.String())
})
}
}
func mockCommentCreate(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`mutation CommentCreate\b`),
httpmock.GraphQLMutation(`
{ "data": { "addComment": { "commentEdge": { "node": {
"url": "https://github.com/OWNER/REPO/pull/123#issuecomment-456"
} } } } }`,
func(inputs map[string]interface{}) {
assert.Equal(t, "comment body", inputs["body"])
}),
)
}
func mockCommentUpdate(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`mutation CommentUpdate\b`),
httpmock.GraphQLMutation(`
{ "data": { "updateIssueComment": { "issueComment": {
"url": "https://github.com/OWNER/REPO/pull/123#issuecomment-111"
} } } }`,
func(inputs map[string]interface{}) {
assert.Equal(t, "id1", inputs["id"])
assert.Equal(t, "comment body", inputs["body"])
}),
)
}
func mockCommentDelete(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`mutation CommentDelete\b`),
httpmock.GraphQLMutation(`
{ "data": { "deleteIssueComment": {} } }`,
func(inputs map[string]interface{}) {
assert.Equal(t, "id1", inputs["id"])
},
),
)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/update-branch/update_branch_test.go | pkg/cmd/pr/update-branch/update_branch_test.go | package update_branch
import (
"bytes"
"net/http"
"testing"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/ghrepo"
shared "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 TestNewCmdUpdateBranch(t *testing.T) {
tests := []struct {
name string
input string
output UpdateBranchOptions
wantsErr string
}{
{
name: "no argument",
input: "",
output: UpdateBranchOptions{},
},
{
name: "with argument",
input: "23",
output: UpdateBranchOptions{
SelectorArg: "23",
},
},
{
name: "no argument, --rebase",
input: "--rebase",
output: UpdateBranchOptions{
Rebase: true,
},
},
{
name: "with argument, --rebase",
input: "23 --rebase",
output: UpdateBranchOptions{
SelectorArg: "23",
Rebase: true,
},
},
{
name: "no argument, --repo",
input: "--repo owner/repo",
wantsErr: "argument required when using the --repo flag",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
ios.SetStdoutTTY(true)
ios.SetStdinTTY(true)
ios.SetStderrTTY(true)
f := &cmdutil.Factory{
IOStreams: ios,
}
var gotOpts *UpdateBranchOptions
cmd := NewCmdUpdateBranch(f, func(opts *UpdateBranchOptions) error {
gotOpts = opts
return nil
})
cmd.PersistentFlags().StringP("repo", "R", "", "")
argv, err := shlex.Split(tt.input)
assert.NoError(t, err)
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
_, err = cmd.ExecuteC()
if tt.wantsErr != "" {
assert.EqualError(t, err, tt.wantsErr)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.output.SelectorArg, gotOpts.SelectorArg)
assert.Equal(t, tt.output.Rebase, gotOpts.Rebase)
})
}
}
func Test_updateBranchRun(t *testing.T) {
defaultInput := func() UpdateBranchOptions {
return UpdateBranchOptions{
Finder: shared.NewMockFinder("123", &api.PullRequest{
ID: "123",
Number: 123,
HeadRefOid: "head-ref-oid",
HeadRefName: "head-ref-name",
HeadRepositoryOwner: api.Owner{Login: "head-repository-owner"},
Mergeable: api.PullRequestMergeableMergeable,
}, ghrepo.New("OWNER", "REPO")),
}
}
tests := []struct {
name string
input *UpdateBranchOptions
httpStubs func(*testing.T, *httpmock.Registry)
stdout string
stderr string
wantsErr string
}{
{
name: "failure, pr not found",
input: &UpdateBranchOptions{
Finder: shared.NewMockFinder("", nil, nil),
SelectorArg: "123",
},
wantsErr: "no pull requests found",
},
{
name: "success, already up-to-date",
input: &UpdateBranchOptions{
SelectorArg: "123",
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query ComparePullRequestBaseBranchWith\b`),
httpmock.GraphQLQuery(`{
"data": {
"repository": {
"pullRequest": {
"baseRef": {
"compare": {
"aheadBy": 999,
"behindBy": 0,
"Status": "AHEAD"
}
}
}
}
}
}`, func(_ string, inputs map[string]interface{}) {
assert.Equal(t, float64(123), inputs["pullRequestNumber"])
assert.Equal(t, "head-repository-owner:head-ref-name", inputs["headRef"])
}))
},
stdout: "✓ PR branch already up-to-date\n",
},
{
name: "success, already up-to-date, PR branch on the same repo as base",
input: &UpdateBranchOptions{
SelectorArg: "123",
Finder: shared.NewMockFinder("123", &api.PullRequest{
ID: "123",
Number: 123,
HeadRefOid: "head-ref-oid",
HeadRefName: "head-ref-name",
HeadRepositoryOwner: api.Owner{Login: "OWNER"},
Mergeable: api.PullRequestMergeableMergeable,
}, ghrepo.New("OWNER", "REPO")),
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query ComparePullRequestBaseBranchWith\b`),
httpmock.GraphQLQuery(`{
"data": {
"repository": {
"pullRequest": {
"baseRef": {
"compare": {
"aheadBy": 999,
"behindBy": 0,
"Status": "AHEAD"
}
}
}
}
}
}`, func(_ string, inputs map[string]interface{}) {
assert.Equal(t, float64(123), inputs["pullRequestNumber"])
assert.Equal(t, "head-ref-name", inputs["headRef"])
}))
},
stdout: "✓ PR branch already up-to-date\n",
},
{
name: "failure, not mergeable due to conflicts",
input: &UpdateBranchOptions{
SelectorArg: "123",
Finder: shared.NewMockFinder("123", &api.PullRequest{
ID: "123",
Number: 123,
HeadRefOid: "head-ref-oid",
HeadRefName: "head-ref-name",
HeadRepositoryOwner: api.Owner{Login: "OWNER"},
Mergeable: api.PullRequestMergeableConflicting,
}, ghrepo.New("OWNER", "REPO")),
},
stderr: "X Cannot update PR branch due to conflicts\n",
wantsErr: cmdutil.SilentError.Error(),
},
{
name: "success, merge",
input: &UpdateBranchOptions{
SelectorArg: "123",
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query ComparePullRequestBaseBranchWith\b`),
httpmock.GraphQLQuery(`{
"data": {
"repository": {
"pullRequest": {
"baseRef": {
"compare": {
"aheadBy": 0,
"behindBy": 999,
"Status": "BEHIND"
}
}
}
}
}
}`, func(_ string, inputs map[string]interface{}) {
assert.Equal(t, float64(123), inputs["pullRequestNumber"])
assert.Equal(t, "head-repository-owner:head-ref-name", inputs["headRef"])
}))
reg.Register(
httpmock.GraphQL(`mutation PullRequestUpdateBranch\b`),
httpmock.GraphQLMutation(`{
"data": {
"updatePullRequestBranch": {
"pullRequest": {}
}
}
}`, func(inputs map[string]interface{}) {
assert.Equal(t, "123", inputs["pullRequestId"])
assert.Equal(t, "head-ref-oid", inputs["expectedHeadOid"])
assert.Equal(t, "MERGE", inputs["updateMethod"])
}))
},
stdout: "✓ PR branch updated\n",
},
{
name: "success, rebase",
input: &UpdateBranchOptions{
SelectorArg: "123",
Rebase: true,
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query ComparePullRequestBaseBranchWith\b`),
httpmock.GraphQLQuery(`{
"data": {
"repository": {
"pullRequest": {
"baseRef": {
"compare": {
"aheadBy": 0,
"behindBy": 999,
"Status": "BEHIND"
}
}
}
}
}
}`, func(_ string, inputs map[string]interface{}) {
assert.Equal(t, float64(123), inputs["pullRequestNumber"])
assert.Equal(t, "head-repository-owner:head-ref-name", inputs["headRef"])
}))
reg.Register(
httpmock.GraphQL(`mutation PullRequestUpdateBranch\b`),
httpmock.GraphQLMutation(`{
"data": {
"updatePullRequestBranch": {
"pullRequest": {}
}
}
}`, func(inputs map[string]interface{}) {
assert.Equal(t, "123", inputs["pullRequestId"])
assert.Equal(t, "head-ref-oid", inputs["expectedHeadOid"])
assert.Equal(t, "REBASE", inputs["updateMethod"])
}))
},
stdout: "✓ PR branch updated\n",
},
{
name: "failure, API error on ref comparison request",
input: &UpdateBranchOptions{
SelectorArg: "123",
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query ComparePullRequestBaseBranchWith\b`),
httpmock.GraphQLQuery(`{
"data": {},
"errors": [
{
"message": "some error"
}
]
}`, func(_ string, inputs map[string]interface{}) {
assert.Equal(t, float64(123), inputs["pullRequestNumber"])
assert.Equal(t, "head-repository-owner:head-ref-name", inputs["headRef"])
}))
},
wantsErr: "GraphQL: some error",
},
{
name: "failure, merge conflict error on update request",
input: &UpdateBranchOptions{
SelectorArg: "123",
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query ComparePullRequestBaseBranchWith\b`),
httpmock.GraphQLQuery(`{
"data": {
"repository": {
"pullRequest": {
"baseRef": {
"compare": {
"aheadBy": 999,
"behindBy": 999,
"Status": "BEHIND"
}
}
}
}
}
}`, func(_ string, inputs map[string]interface{}) {
assert.Equal(t, float64(123), inputs["pullRequestNumber"])
assert.Equal(t, "head-repository-owner:head-ref-name", inputs["headRef"])
}))
reg.Register(
httpmock.GraphQL(`mutation PullRequestUpdateBranch\b`),
httpmock.GraphQLMutation(`{
"data": {},
"errors": [
{
"message": "merge conflict between base and head (updatePullRequestBranch)"
}
]
}`, func(inputs map[string]interface{}) {
assert.Equal(t, "123", inputs["pullRequestId"])
assert.Equal(t, "head-ref-oid", inputs["expectedHeadOid"])
assert.Equal(t, "MERGE", inputs["updateMethod"])
}))
},
stderr: "X Cannot update PR branch due to conflicts\n",
wantsErr: cmdutil.SilentError.Error(),
},
{
name: "failure, API error on update request",
input: &UpdateBranchOptions{
SelectorArg: "123",
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query ComparePullRequestBaseBranchWith\b`),
httpmock.GraphQLQuery(`{
"data": {
"repository": {
"pullRequest": {
"baseRef": {
"compare": {
"aheadBy": 0,
"behindBy": 999,
"Status": "BEHIND"
}
}
}
}
}
}`, func(_ string, inputs map[string]interface{}) {
assert.Equal(t, float64(123), inputs["pullRequestNumber"])
assert.Equal(t, "head-repository-owner:head-ref-name", inputs["headRef"])
}))
reg.Register(
httpmock.GraphQL(`mutation PullRequestUpdateBranch\b`),
httpmock.GraphQLMutation(`{
"data": {},
"errors": [
{
"message": "some error"
}
]
}`, func(inputs map[string]interface{}) {
assert.Equal(t, "123", inputs["pullRequestId"])
assert.Equal(t, "head-ref-oid", inputs["expectedHeadOid"])
assert.Equal(t, "MERGE", inputs["updateMethod"])
}))
},
wantsErr: "GraphQL: some error",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdoutTTY(true)
ios.SetStdinTTY(true)
ios.SetStderrTTY(true)
reg := &httpmock.Registry{}
defer reg.Verify(t)
if tt.httpStubs != nil {
tt.httpStubs(t, reg)
}
tt.input.GitClient = &git.Client{
GhPath: "some/path/gh",
GitPath: "some/path/git",
}
if tt.input.Finder == nil {
tt.input.Finder = defaultInput().Finder
}
httpClient := func() (*http.Client, error) { return &http.Client{Transport: reg}, nil }
tt.input.IO = ios
tt.input.HttpClient = httpClient
err := updateBranchRun(tt.input)
if tt.wantsErr != "" {
assert.EqualError(t, err, tt.wantsErr)
return
} else {
assert.NoError(t, err)
}
assert.Equal(t, tt.stdout, stdout.String())
assert.Equal(t, tt.stderr, stderr.String())
})
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/update-branch/update_branch.go | pkg/cmd/pr/update-branch/update_branch.go | package update_branch
import (
"fmt"
"net/http"
"strings"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/ghrepo"
shared "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/shurcooL/githubv4"
"github.com/spf13/cobra"
)
type UpdateBranchOptions struct {
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
GitClient *git.Client
Finder shared.PRFinder
SelectorArg string
Rebase bool
}
func NewCmdUpdateBranch(f *cmdutil.Factory, runF func(*UpdateBranchOptions) error) *cobra.Command {
opts := &UpdateBranchOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
GitClient: f.GitClient,
}
cmd := &cobra.Command{
Use: "update-branch [<number> | <url> | <branch>]",
Short: "Update a pull request branch",
Long: heredoc.Docf(`
Update a pull request branch with latest changes of the base branch.
Without an argument, the pull request that belongs to the current branch is selected.
The default behavior is to update with a merge commit (i.e., merging the base branch
into the PR's branch). To reconcile the changes with rebasing on top of the base
branch, the %[1]s--rebase%[1]s option should be provided.
`, "`"),
Example: heredoc.Doc(`
$ gh pr update-branch 23
$ gh pr update-branch 23 --rebase
$ gh pr update-branch 23 --repo owner/repo
`),
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]
}
if runF != nil {
return runF(opts)
}
return updateBranchRun(opts)
},
}
cmd.Flags().BoolVar(&opts.Rebase, "rebase", false, "Update PR branch by rebasing on top of latest base branch")
return cmd
}
func updateBranchRun(opts *UpdateBranchOptions) error {
findOptions := shared.FindOptions{
Selector: opts.SelectorArg,
Fields: []string{"id", "number", "headRefName", "headRefOid", "headRepositoryOwner", "mergeable"},
}
pr, repo, err := opts.Finder.Find(findOptions)
if err != nil {
return err
}
cs := opts.IO.ColorScheme()
if pr.Mergeable == api.PullRequestMergeableConflicting {
fmt.Fprintf(opts.IO.ErrOut, "%s Cannot update PR branch due to conflicts\n", cs.FailureIcon())
return cmdutil.SilentError
}
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
apiClient := api.NewClientFromHTTP(httpClient)
headRef := pr.HeadRefName
if pr.HeadRepositoryOwner.Login != repo.RepoOwner() {
// Only prepend the `owner:` to comparison head ref if the PR head
// branch is on another repo (e.g., a fork).
headRef = pr.HeadRepositoryOwner.Login + ":" + headRef
}
opts.IO.StartProgressIndicator()
comparison, err := api.ComparePullRequestBaseBranchWith(apiClient, repo, pr.Number, headRef)
opts.IO.StopProgressIndicator()
if err != nil {
return err
}
if comparison.BehindBy == 0 {
// The PR branch is not behind the base branch, so it'a already up-to-date.
fmt.Fprintf(opts.IO.Out, "%s PR branch already up-to-date\n", cs.SuccessIcon())
return nil
}
opts.IO.StartProgressIndicator()
err = updatePullRequestBranch(apiClient, repo, pr.ID, pr.HeadRefOid, opts.Rebase)
opts.IO.StopProgressIndicator()
if err != nil {
// TODO: this is a best effort approach and not a resilient way of handling API errors.
if strings.Contains(err.Error(), "GraphQL: merge conflict between base and head (updatePullRequestBranch)") {
fmt.Fprintf(opts.IO.ErrOut, "%s Cannot update PR branch due to conflicts\n", cs.FailureIcon())
return cmdutil.SilentError
}
return err
}
fmt.Fprintf(opts.IO.Out, "%s PR branch updated\n", cs.SuccessIcon())
return nil
}
// updatePullRequestBranch calls the GraphQL API endpoint to update the given PR
// branch with latest changes of its base.
func updatePullRequestBranch(apiClient *api.Client, repo ghrepo.Interface, pullRequestID string, expectedHeadOid string, rebase bool) error {
updateMethod := githubv4.PullRequestBranchUpdateMethodMerge
if rebase {
updateMethod = githubv4.PullRequestBranchUpdateMethodRebase
}
params := githubv4.UpdatePullRequestBranchInput{
PullRequestID: pullRequestID,
ExpectedHeadOid: (*githubv4.GitObjectID)(&expectedHeadOid),
UpdateMethod: &updateMethod,
}
return api.UpdatePullRequestBranch(apiClient, repo, params)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/edit/edit.go | pkg/cmd/pr/edit/edit.go | package edit
import (
"fmt"
"net/http"
"slices"
"strings"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
fd "github.com/cli/cli/v2/internal/featuredetection"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/ghrepo"
shared "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/set"
"github.com/spf13/cobra"
"golang.org/x/sync/errgroup"
)
type EditOptions struct {
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
Finder shared.PRFinder
Surveyor Surveyor
Fetcher EditableOptionsFetcher
EditorRetriever EditorRetriever
Prompter shared.EditPrompter
Detector fd.Detector
BaseRepo func() (ghrepo.Interface, error)
SelectorArg string
Interactive bool
shared.Editable
}
func NewCmdEdit(f *cmdutil.Factory, runF func(*EditOptions) error) *cobra.Command {
opts := &EditOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
Surveyor: surveyor{P: f.Prompter},
Fetcher: fetcher{},
EditorRetriever: editorRetriever{config: f.Config},
Prompter: f.Prompter,
}
var bodyFile string
var removeMilestone bool
cmd := &cobra.Command{
Use: "edit [<number> | <url> | <branch>]",
Short: "Edit a pull request",
Long: heredoc.Docf(`
Edit a pull request.
Without an argument, the pull request that belongs to the current branch
is selected.
Editing a pull request's projects requires authorization with the %[1]sproject%[1]s scope.
To authorize, run %[1]sgh auth refresh -s project%[1]s.
The %[1]s--add-assignee%[1]s and %[1]s--remove-assignee%[1]s flags both support
the following special values:
- %[1]s@me%[1]s: assign or unassign yourself
- %[1]s@copilot%[1]s: assign or unassign Copilot (not supported on GitHub Enterprise Server)
The %[1]s--add-reviewer%[1]s and %[1]s--remove-reviewer%[1]s flags do not support
these special values.
`, "`"),
Example: heredoc.Doc(`
$ gh pr edit 23 --title "I found a bug" --body "Nothing works"
$ gh pr edit 23 --add-label "bug,help wanted" --remove-label "core"
$ gh pr edit 23 --add-reviewer monalisa,hubot --remove-reviewer myorg/team-name
$ gh pr edit 23 --add-assignee "@me" --remove-assignee monalisa,hubot
$ gh pr edit 23 --add-assignee "@copilot"
$ gh pr edit 23 --add-project "Roadmap" --remove-project v1,v2
$ gh pr edit 23 --milestone "Version 1"
$ gh pr edit 23 --remove-milestone
`),
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
opts.Finder = shared.NewFinder(f)
// support `-R, --repo` override
opts.BaseRepo = f.BaseRepo
if len(args) > 0 {
opts.SelectorArg = args[0]
}
if opts.SelectorArg != "" {
// If a URL is provided, we need to parse it to override the
// base repository, especially the hostname part. That's because
// we need a feature detector down in this command, and that
// needs to know the API host. If the command is run outside of
// a git repo, we cannot instantiate the detector unless we have
// already parsed the URL.
if baseRepo, _, _, err := shared.ParseURL(opts.SelectorArg); err == nil {
opts.BaseRepo = func() (ghrepo.Interface, error) {
return baseRepo, nil
}
}
}
flags := cmd.Flags()
bodyProvided := flags.Changed("body")
bodyFileProvided := bodyFile != ""
if err := cmdutil.MutuallyExclusive(
"specify only one of `--body` or `--body-file`",
bodyProvided,
bodyFileProvided,
); err != nil {
return err
}
if bodyProvided || bodyFileProvided {
opts.Editable.Body.Edited = true
if bodyFileProvided {
b, err := cmdutil.ReadFile(bodyFile, opts.IO.In)
if err != nil {
return err
}
opts.Editable.Body.Value = string(b)
}
}
if err := cmdutil.MutuallyExclusive(
"specify only one of `--milestone` or `--remove-milestone`",
flags.Changed("milestone"),
removeMilestone,
); err != nil {
return err
}
if flags.Changed("title") {
opts.Editable.Title.Edited = true
}
if flags.Changed("body") {
opts.Editable.Body.Edited = true
}
if flags.Changed("base") {
opts.Editable.Base.Edited = true
}
if flags.Changed("add-reviewer") || flags.Changed("remove-reviewer") {
opts.Editable.Reviewers.Edited = true
}
if flags.Changed("add-assignee") || flags.Changed("remove-assignee") {
opts.Editable.Assignees.Edited = true
}
if flags.Changed("add-label") || flags.Changed("remove-label") {
opts.Editable.Labels.Edited = true
}
if flags.Changed("add-project") || flags.Changed("remove-project") {
opts.Editable.Projects.Edited = true
}
if flags.Changed("milestone") || removeMilestone {
opts.Editable.Milestone.Edited = true
// Note that when `--remove-milestone` is provided, the value of
// `opts.Editable.Milestone.Value` will automatically be empty,
// which results in milestone association removal. For reference,
// see the `Editable.MilestoneId` method.
}
if !opts.Editable.Dirty() {
opts.Interactive = true
}
if opts.Interactive && !opts.IO.CanPrompt() {
return cmdutil.FlagErrorf("--title, --body, --reviewer, --assignee, --label, --project, or --milestone required when not running interactively")
}
if runF != nil {
return runF(opts)
}
return editRun(opts)
},
}
cmd.Flags().StringVarP(&opts.Editable.Title.Value, "title", "t", "", "Set the new title.")
cmd.Flags().StringVarP(&opts.Editable.Body.Value, "body", "b", "", "Set the new body.")
cmd.Flags().StringVarP(&bodyFile, "body-file", "F", "", "Read body text from `file` (use \"-\" to read from standard input)")
cmd.Flags().StringVarP(&opts.Editable.Base.Value, "base", "B", "", "Change the base `branch` for this pull request")
cmd.Flags().StringSliceVar(&opts.Editable.Reviewers.Add, "add-reviewer", nil, "Add reviewers by their `login`.")
cmd.Flags().StringSliceVar(&opts.Editable.Reviewers.Remove, "remove-reviewer", nil, "Remove reviewers by their `login`.")
cmd.Flags().StringSliceVar(&opts.Editable.Assignees.Add, "add-assignee", nil, "Add assigned users by their `login`. Use \"@me\" to assign yourself, or \"@copilot\" to assign Copilot.")
cmd.Flags().StringSliceVar(&opts.Editable.Assignees.Remove, "remove-assignee", nil, "Remove assigned users by their `login`. Use \"@me\" to unassign yourself, or \"@copilot\" to unassign Copilot.")
cmd.Flags().StringSliceVar(&opts.Editable.Labels.Add, "add-label", nil, "Add labels by `name`")
cmd.Flags().StringSliceVar(&opts.Editable.Labels.Remove, "remove-label", nil, "Remove labels by `name`")
cmd.Flags().StringSliceVar(&opts.Editable.Projects.Add, "add-project", nil, "Add the pull request to projects by `title`")
cmd.Flags().StringSliceVar(&opts.Editable.Projects.Remove, "remove-project", nil, "Remove the pull request from projects by `title`")
cmd.Flags().StringVarP(&opts.Editable.Milestone.Value, "milestone", "m", "", "Edit the milestone the pull request belongs to by `name`")
cmd.Flags().BoolVar(&removeMilestone, "remove-milestone", false, "Remove the milestone association from the pull request")
_ = cmdutil.RegisterBranchCompletionFlags(f.GitClient, cmd, "base")
for _, flagName := range []string{"add-reviewer", "remove-reviewer"} {
_ = cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
baseRepo, err := f.BaseRepo()
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
httpClient, err := f.HttpClient()
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
results, err := shared.RequestableReviewersForCompletion(httpClient, baseRepo)
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
return results, cobra.ShellCompDirectiveNoFileComp
})
}
return cmd
}
func editRun(opts *EditOptions) error {
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
if opts.Detector == nil {
baseRepo, err := opts.BaseRepo()
if err != nil {
return err
}
cachedClient := api.NewCachedHTTPClient(httpClient, time.Hour*24)
opts.Detector = fd.NewDetector(cachedClient, baseRepo.RepoHost())
}
findOptions := shared.FindOptions{
Selector: opts.SelectorArg,
Fields: []string{"id", "author", "url", "title", "body", "baseRefName", "reviewRequests", "labels", "projectCards", "projectItems", "milestone"},
Detector: opts.Detector,
}
issueFeatures, err := opts.Detector.IssueFeatures()
if err != nil {
return err
}
if issueFeatures.ActorIsAssignable {
findOptions.Fields = append(findOptions.Fields, "assignedActors")
} else {
findOptions.Fields = append(findOptions.Fields, "assignees")
}
pr, repo, err := opts.Finder.Find(findOptions)
if err != nil {
return err
}
editable := opts.Editable
editable.Reviewers.Allowed = true
editable.Title.Default = pr.Title
editable.Body.Default = pr.Body
editable.Base.Default = pr.BaseRefName
editable.Reviewers.Default = pr.ReviewRequests.Logins()
if issueFeatures.ActorIsAssignable {
editable.Assignees.ActorAssignees = true
editable.Assignees.Default = pr.AssignedActors.DisplayNames()
editable.Assignees.DefaultLogins = pr.AssignedActors.Logins()
} else {
editable.Assignees.Default = pr.Assignees.Logins()
}
editable.Labels.Default = pr.Labels.Names()
editable.Projects.Default = append(pr.ProjectCards.ProjectNames(), pr.ProjectItems.ProjectTitles()...)
projectItems := map[string]string{}
for _, n := range pr.ProjectItems.Nodes {
projectItems[n.Project.ID] = n.ID
}
editable.Projects.ProjectItems = projectItems
if pr.Milestone != nil {
editable.Milestone.Default = pr.Milestone.Title
}
if opts.Interactive {
err = opts.Surveyor.FieldsToEdit(&editable)
if err != nil {
return err
}
}
apiClient := api.NewClientFromHTTP(httpClient)
opts.IO.StartProgressIndicator()
err = opts.Fetcher.EditableOptionsFetch(apiClient, repo, &editable, opts.Detector.ProjectsV1())
opts.IO.StopProgressIndicator()
if err != nil {
return err
}
if opts.Interactive {
// Remove PR author from reviewer options;
// REST API errors if author is included (GraphQL silently ignores).
if editable.Reviewers.Edited {
s := set.NewStringSet()
s.AddValues(editable.Reviewers.Options)
s.Remove(pr.Author.Login)
editable.Reviewers.Options = s.ToSlice()
}
editorCommand, err := opts.EditorRetriever.Retrieve()
if err != nil {
return err
}
err = opts.Surveyor.EditFields(&editable, editorCommand)
if err != nil {
return err
}
}
opts.IO.StartProgressIndicator()
err = updatePullRequest(httpClient, repo, pr.ID, pr.Number, editable)
opts.IO.StopProgressIndicator()
if err != nil {
return err
}
fmt.Fprintln(opts.IO.Out, pr.URL)
return nil
}
func updatePullRequest(httpClient *http.Client, repo ghrepo.Interface, id string, number int, editable shared.Editable) error {
var wg errgroup.Group
wg.Go(func() error {
return shared.UpdateIssue(httpClient, repo, id, true, editable)
})
if editable.Reviewers.Edited {
wg.Go(func() error {
return updatePullRequestReviews(httpClient, repo, number, editable)
})
}
return wg.Wait()
}
func updatePullRequestReviews(httpClient *http.Client, repo ghrepo.Interface, number int, editable shared.Editable) error {
if !editable.Reviewers.Edited {
return nil
}
// Rebuild the Value slice from non-interactive flag input.
if len(editable.Reviewers.Add) != 0 || len(editable.Reviewers.Remove) != 0 {
s := set.NewStringSet()
s.AddValues(editable.Reviewers.Add)
s.AddValues(editable.Reviewers.Default)
s.RemoveValues(editable.Reviewers.Remove)
editable.Reviewers.Value = s.ToSlice()
}
addUsers, addTeams := partitionUsersAndTeams(editable.Reviewers.Value)
// Reviewers in Default but not in the Value have been removed interactively.
var toRemove []string
for _, r := range editable.Reviewers.Default {
if !slices.Contains(editable.Reviewers.Value, r) {
toRemove = append(toRemove, r)
}
}
removeUsers, removeTeams := partitionUsersAndTeams(toRemove)
client := api.NewClientFromHTTP(httpClient)
wg := errgroup.Group{}
wg.Go(func() error {
return api.AddPullRequestReviews(client, repo, number, addUsers, addTeams)
})
wg.Go(func() error {
return api.RemovePullRequestReviews(client, repo, number, removeUsers, removeTeams)
})
return wg.Wait()
}
type Surveyor interface {
FieldsToEdit(*shared.Editable) error
EditFields(*shared.Editable, string) error
}
type surveyor struct {
P shared.EditPrompter
}
func (s surveyor) FieldsToEdit(editable *shared.Editable) error {
return shared.FieldsToEditSurvey(s.P, editable)
}
func (s surveyor) EditFields(editable *shared.Editable, editorCmd string) error {
return shared.EditFieldsSurvey(s.P, editable, editorCmd)
}
type EditableOptionsFetcher interface {
EditableOptionsFetch(*api.Client, ghrepo.Interface, *shared.Editable, gh.ProjectsV1Support) error
}
type fetcher struct{}
func (f fetcher) EditableOptionsFetch(client *api.Client, repo ghrepo.Interface, opts *shared.Editable, projectsV1Support gh.ProjectsV1Support) error {
return shared.FetchOptions(client, repo, opts, projectsV1Support)
}
type EditorRetriever interface {
Retrieve() (string, error)
}
type editorRetriever struct {
config func() (gh.Config, error)
}
func (e editorRetriever) Retrieve() (string, error) {
return cmdutil.DetermineEditor(e.config)
}
// partitionUsersAndTeams splits reviewer identifiers into user logins and team slugs.
// Team identifiers are in the form "org/slug"; only the slug portion is returned for teams.
func partitionUsersAndTeams(values []string) (users []string, teams []string) {
for _, v := range values {
if strings.ContainsRune(v, '/') {
parts := strings.SplitN(v, "/", 2)
if len(parts) == 2 && parts[1] != "" {
teams = append(teams, parts[1])
}
} else if v != "" {
users = append(users, v)
}
}
return
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/edit/edit_test.go | pkg/cmd/pr/edit/edit_test.go | package edit
import (
"bytes"
"fmt"
"net/http"
"os"
"path/filepath"
"testing"
"github.com/cli/cli/v2/api"
fd "github.com/cli/cli/v2/internal/featuredetection"
"github.com/cli/cli/v2/internal/gh"
"github.com/cli/cli/v2/internal/ghrepo"
shared "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"
"github.com/stretchr/testify/require"
)
func TestNewCmdEdit(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
input string
stdin string
output EditOptions
expectedBaseRepo ghrepo.Interface
wantsErr bool
}{
{
name: "no argument",
input: "",
output: EditOptions{
SelectorArg: "",
Interactive: true,
},
wantsErr: false,
},
{
name: "two arguments",
input: "1 2",
output: EditOptions{},
wantsErr: true,
},
{
name: "URL argument",
input: "https://example.com/cli/cli/pull/23",
output: EditOptions{
SelectorArg: "https://example.com/cli/cli/pull/23",
Interactive: true,
},
expectedBaseRepo: ghrepo.NewWithHost("cli", "cli", "example.com"),
wantsErr: false,
},
{
name: "pull request number argument",
input: "23",
output: EditOptions{
SelectorArg: "23",
Interactive: true,
},
wantsErr: false,
},
{
name: "title flag",
input: "23 --title test",
output: EditOptions{
SelectorArg: "23",
Editable: shared.Editable{
Title: shared.EditableString{
Value: "test",
Edited: true,
},
},
},
wantsErr: false,
},
{
name: "body flag",
input: "23 --body test",
output: EditOptions{
SelectorArg: "23",
Editable: shared.Editable{
Body: shared.EditableString{
Value: "test",
Edited: true,
},
},
},
wantsErr: false,
},
{
name: "body from stdin",
input: "23 --body-file -",
stdin: "this is on standard input",
output: EditOptions{
SelectorArg: "23",
Editable: shared.Editable{
Body: shared.EditableString{
Value: "this is on standard input",
Edited: true,
},
},
},
wantsErr: false,
},
{
name: "body from file",
input: fmt.Sprintf("23 --body-file '%s'", tmpFile),
output: EditOptions{
SelectorArg: "23",
Editable: shared.Editable{
Body: shared.EditableString{
Value: "a body from file",
Edited: true,
},
},
},
wantsErr: false,
},
{
name: "both body and body-file flags",
input: "23 --body foo --body-file bar",
wantsErr: true,
},
{
name: "base flag",
input: "23 --base base-branch-name",
output: EditOptions{
SelectorArg: "23",
Editable: shared.Editable{
Base: shared.EditableString{
Value: "base-branch-name",
Edited: true,
},
},
},
wantsErr: false,
},
{
name: "add-reviewer flag",
input: "23 --add-reviewer monalisa,owner/core",
output: EditOptions{
SelectorArg: "23",
Editable: shared.Editable{
Reviewers: shared.EditableSlice{
Add: []string{"monalisa", "owner/core"},
Edited: true,
},
},
},
wantsErr: false,
},
{
name: "remove-reviewer flag",
input: "23 --remove-reviewer monalisa,owner/core",
output: EditOptions{
SelectorArg: "23",
Editable: shared.Editable{
Reviewers: shared.EditableSlice{
Remove: []string{"monalisa", "owner/core"},
Edited: true,
},
},
},
wantsErr: false,
},
{
name: "add-assignee flag",
input: "23 --add-assignee monalisa,hubot",
output: EditOptions{
SelectorArg: "23",
Editable: shared.Editable{
Assignees: shared.EditableAssignees{
EditableSlice: shared.EditableSlice{
Add: []string{"monalisa", "hubot"},
Edited: true,
},
},
},
},
wantsErr: false,
},
{
name: "remove-assignee flag",
input: "23 --remove-assignee monalisa,hubot",
output: EditOptions{
SelectorArg: "23",
Editable: shared.Editable{
Assignees: shared.EditableAssignees{
EditableSlice: shared.EditableSlice{
Remove: []string{"monalisa", "hubot"},
Edited: true,
},
},
},
},
wantsErr: false,
},
{
name: "add-label flag",
input: "23 --add-label feature,TODO,bug",
output: EditOptions{
SelectorArg: "23",
Editable: shared.Editable{
Labels: shared.EditableSlice{
Add: []string{"feature", "TODO", "bug"},
Edited: true,
},
},
},
wantsErr: false,
},
{
name: "remove-label flag",
input: "23 --remove-label feature,TODO,bug",
output: EditOptions{
SelectorArg: "23",
Editable: shared.Editable{
Labels: shared.EditableSlice{
Remove: []string{"feature", "TODO", "bug"},
Edited: true,
},
},
},
wantsErr: false,
},
{
name: "add-project flag",
input: "23 --add-project Cleanup,Roadmap",
output: EditOptions{
SelectorArg: "23",
Editable: shared.Editable{
Projects: shared.EditableProjects{
EditableSlice: shared.EditableSlice{
Add: []string{"Cleanup", "Roadmap"},
Edited: true,
},
},
},
},
wantsErr: false,
},
{
name: "remove-project flag",
input: "23 --remove-project Cleanup,Roadmap",
output: EditOptions{
SelectorArg: "23",
Editable: shared.Editable{
Projects: shared.EditableProjects{
EditableSlice: shared.EditableSlice{
Remove: []string{"Cleanup", "Roadmap"},
Edited: true,
},
},
},
},
wantsErr: false,
},
{
name: "milestone flag",
input: "23 --milestone GA",
output: EditOptions{
SelectorArg: "23",
Editable: shared.Editable{
Milestone: shared.EditableString{
Value: "GA",
Edited: true,
},
},
},
wantsErr: false,
},
{
name: "remove-milestone flag",
input: "23 --remove-milestone",
output: EditOptions{
SelectorArg: "23",
Editable: shared.Editable{
Milestone: shared.EditableString{
Value: "",
Edited: true,
},
},
},
wantsErr: false,
},
{
name: "both milestone and remove-milestone flags",
input: "23 --milestone foo --remove-milestone",
wantsErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, stdin, _, _ := iostreams.Test()
ios.SetStdoutTTY(true)
ios.SetStdinTTY(true)
ios.SetStderrTTY(true)
if tt.stdin != "" {
_, _ = stdin.WriteString(tt.stdin)
}
f := &cmdutil.Factory{
IOStreams: ios,
}
argv, err := shlex.Split(tt.input)
assert.NoError(t, err)
var gotOpts *EditOptions
cmd := NewCmdEdit(f, func(opts *EditOptions) error {
gotOpts = opts
return nil
})
cmd.Flags().BoolP("help", "x", false, "")
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
_, err = cmd.ExecuteC()
if tt.wantsErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.output.SelectorArg, gotOpts.SelectorArg)
assert.Equal(t, tt.output.Interactive, gotOpts.Interactive)
assert.Equal(t, tt.output.Editable, gotOpts.Editable)
if tt.expectedBaseRepo != nil {
baseRepo, err := gotOpts.BaseRepo()
require.NoError(t, err)
require.True(
t,
ghrepo.IsSame(tt.expectedBaseRepo, baseRepo),
"expected base repo %+v, got %+v", tt.expectedBaseRepo, baseRepo,
)
}
})
}
}
func Test_editRun(t *testing.T) {
tests := []struct {
name string
input *EditOptions
httpStubs func(*testing.T, *httpmock.Registry)
stdout string
stderr string
}{
{
name: "non-interactive",
input: &EditOptions{
Detector: &fd.EnabledDetectorMock{},
SelectorArg: "123",
Finder: shared.NewMockFinder("123", &api.PullRequest{
URL: "https://github.com/OWNER/REPO/pull/123",
}, ghrepo.New("OWNER", "REPO")),
Interactive: false,
Editable: shared.Editable{
Title: shared.EditableString{
Value: "new title",
Edited: true,
},
Body: shared.EditableString{
Value: "new body",
Edited: true,
},
Base: shared.EditableString{
Value: "base-branch-name",
Edited: true,
},
Reviewers: shared.EditableSlice{
Add: []string{"OWNER/core", "OWNER/external", "monalisa", "hubot"},
Remove: []string{"dependabot"},
Edited: true,
},
Assignees: shared.EditableAssignees{
EditableSlice: shared.EditableSlice{
Add: []string{"monalisa", "hubot"},
Remove: []string{"octocat"},
Edited: true,
},
},
Labels: shared.EditableSlice{
Add: []string{"feature", "TODO", "bug"},
Remove: []string{"docs"},
Edited: true,
},
Projects: shared.EditableProjects{
EditableSlice: shared.EditableSlice{
Add: []string{"Cleanup", "CleanupV2"},
Remove: []string{"Roadmap", "RoadmapV2"},
Edited: true,
},
},
Milestone: shared.EditableString{
Value: "GA",
Edited: true,
},
},
Fetcher: testFetcher{},
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockRepoMetadata(reg, mockRepoMetadataOptions{reviewers: true, teamReviewers: false, assignees: true, labels: true, projects: true, milestones: true})
mockPullRequestUpdate(reg)
mockPullRequestUpdateActorAssignees(reg)
mockPullRequestAddReviewers(reg)
mockPullRequestUpdateLabels(reg)
mockProjectV2ItemUpdate(reg)
},
stdout: "https://github.com/OWNER/REPO/pull/123\n",
},
{
name: "non-interactive skip reviewers",
input: &EditOptions{
Detector: &fd.EnabledDetectorMock{},
SelectorArg: "123",
Finder: shared.NewMockFinder("123", &api.PullRequest{
URL: "https://github.com/OWNER/REPO/pull/123",
}, ghrepo.New("OWNER", "REPO")),
Interactive: false,
Editable: shared.Editable{
Title: shared.EditableString{
Value: "new title",
Edited: true,
},
Body: shared.EditableString{
Value: "new body",
Edited: true,
},
Base: shared.EditableString{
Value: "base-branch-name",
Edited: true,
},
Assignees: shared.EditableAssignees{
EditableSlice: shared.EditableSlice{
Add: []string{"monalisa", "hubot"},
Remove: []string{"octocat"},
Edited: true,
},
},
Labels: shared.EditableSlice{
Add: []string{"feature", "TODO", "bug"},
Remove: []string{"docs"},
Edited: true,
},
Projects: shared.EditableProjects{
EditableSlice: shared.EditableSlice{
Add: []string{"Cleanup", "CleanupV2"},
Remove: []string{"Roadmap", "RoadmapV2"},
Edited: true,
},
},
Milestone: shared.EditableString{
Value: "GA",
Edited: true,
},
},
Fetcher: testFetcher{},
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockRepoMetadata(reg, mockRepoMetadataOptions{assignees: true, labels: true, projects: true, milestones: true})
mockPullRequestUpdate(reg)
mockPullRequestUpdateActorAssignees(reg)
mockPullRequestUpdateLabels(reg)
mockProjectV2ItemUpdate(reg)
},
stdout: "https://github.com/OWNER/REPO/pull/123\n",
},
{
name: "non-interactive remove all reviewers",
input: &EditOptions{
Detector: &fd.EnabledDetectorMock{},
SelectorArg: "123",
Finder: shared.NewMockFinder("123", &api.PullRequest{ // include existing reviewers so removal logic triggers
URL: "https://github.com/OWNER/REPO/pull/123",
ReviewRequests: api.ReviewRequests{Nodes: []struct{ RequestedReviewer api.RequestedReviewer }{
{RequestedReviewer: api.RequestedReviewer{TypeName: "Team", Slug: "core", Organization: struct {
Login string `json:"login"`
}{Login: "OWNER"}}},
{RequestedReviewer: api.RequestedReviewer{TypeName: "Team", Slug: "external", Organization: struct {
Login string `json:"login"`
}{Login: "OWNER"}}},
{RequestedReviewer: api.RequestedReviewer{TypeName: "User", Login: "monalisa"}},
{RequestedReviewer: api.RequestedReviewer{TypeName: "User", Login: "hubot"}},
{RequestedReviewer: api.RequestedReviewer{TypeName: "User", Login: "dependabot"}},
}},
}, ghrepo.New("OWNER", "REPO")),
Interactive: false,
Editable: shared.Editable{
Title: shared.EditableString{
Value: "new title",
Edited: true,
},
Body: shared.EditableString{
Value: "new body",
Edited: true,
},
Base: shared.EditableString{
Value: "base-branch-name",
Edited: true,
},
Reviewers: shared.EditableSlice{
Default: []string{"OWNER/core", "OWNER/external", "monalisa", "hubot", "dependabot"},
Remove: []string{"OWNER/core", "OWNER/external", "monalisa", "hubot", "dependabot"},
Edited: true,
},
Assignees: shared.EditableAssignees{
EditableSlice: shared.EditableSlice{
Add: []string{"monalisa", "hubot"},
Remove: []string{"octocat"},
Edited: true,
},
},
Labels: shared.EditableSlice{
Add: []string{"feature", "TODO", "bug"},
Remove: []string{"docs"},
Edited: true,
},
Projects: shared.EditableProjects{
EditableSlice: shared.EditableSlice{
Add: []string{"Cleanup", "CleanupV2"},
Remove: []string{"Roadmap", "RoadmapV2"},
Edited: true,
},
},
Milestone: shared.EditableString{
Value: "GA",
Edited: true,
},
},
Fetcher: testFetcher{},
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockRepoMetadata(reg, mockRepoMetadataOptions{reviewers: true, teamReviewers: false, assignees: true, labels: true, projects: true, milestones: true})
mockPullRequestUpdate(reg)
mockPullRequestRemoveReviewers(reg)
mockPullRequestUpdateLabels(reg)
mockPullRequestUpdateActorAssignees(reg)
mockProjectV2ItemUpdate(reg)
},
stdout: "https://github.com/OWNER/REPO/pull/123\n",
},
// Conditional team fetching cases
{
name: "non-interactive add only user reviewers skips team fetch",
input: &EditOptions{
Detector: &fd.EnabledDetectorMock{},
SelectorArg: "123",
Finder: shared.NewMockFinder("123", &api.PullRequest{URL: "https://github.com/OWNER/REPO/pull/123"}, ghrepo.New("OWNER", "REPO")),
Interactive: false,
Editable: shared.Editable{
Reviewers: shared.EditableSlice{Add: []string{"monalisa", "hubot"}, Edited: true},
},
Fetcher: testFetcher{},
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
// reviewers only (users), no team reviewers fetched
mockRepoMetadata(reg, mockRepoMetadataOptions{reviewers: true})
// explicitly assert that no OrganizationTeamList query occurs
reg.Exclude(t, httpmock.GraphQL(`query OrganizationTeamList\b`))
mockPullRequestUpdate(reg)
mockPullRequestAddReviewers(reg)
},
stdout: "https://github.com/OWNER/REPO/pull/123\n",
},
{
name: "non-interactive add contains team reviewers skips team fetch",
input: &EditOptions{
Detector: &fd.EnabledDetectorMock{},
SelectorArg: "123",
Finder: shared.NewMockFinder("123", &api.PullRequest{URL: "https://github.com/OWNER/REPO/pull/123"}, ghrepo.New("OWNER", "REPO")),
Interactive: false,
Editable: shared.Editable{
Reviewers: shared.EditableSlice{Add: []string{"monalisa", "OWNER/core"}, Edited: true},
},
Fetcher: testFetcher{},
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
// reviewer add includes team but non-interactive Add/Remove provided -> no team fetch
mockRepoMetadata(reg, mockRepoMetadataOptions{reviewers: true})
// explicitly assert that no OrganizationTeamList query occurs
reg.Exclude(t, httpmock.GraphQL(`query OrganizationTeamList\b`))
mockPullRequestUpdate(reg)
mockPullRequestAddReviewers(reg)
},
stdout: "https://github.com/OWNER/REPO/pull/123\n",
},
{
name: "non-interactive reviewers remove contains team skips team fetch",
input: &EditOptions{
Detector: &fd.EnabledDetectorMock{},
SelectorArg: "123",
Finder: shared.NewMockFinder("123", &api.PullRequest{URL: "https://github.com/OWNER/REPO/pull/123", ReviewRequests: api.ReviewRequests{Nodes: []struct{ RequestedReviewer api.RequestedReviewer }{
{RequestedReviewer: api.RequestedReviewer{TypeName: "Team", Slug: "core", Organization: struct {
Login string `json:"login"`
}{Login: "OWNER"}}},
{RequestedReviewer: api.RequestedReviewer{TypeName: "User", Login: "monalisa"}},
}}}, ghrepo.New("OWNER", "REPO")),
Interactive: false,
Editable: shared.Editable{
Reviewers: shared.EditableSlice{Remove: []string{"monalisa", "OWNER/core"}, Edited: true},
},
Fetcher: testFetcher{},
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockRepoMetadata(reg, mockRepoMetadataOptions{reviewers: true})
// explicitly assert that no OrganizationTeamList query occurs
reg.Exclude(t, httpmock.GraphQL(`query OrganizationTeamList\b`))
mockPullRequestUpdate(reg)
mockPullRequestRemoveReviewers(reg)
},
stdout: "https://github.com/OWNER/REPO/pull/123\n",
},
{
name: "non-interactive mutate reviewers with no change to existing team reviewers skips team fetch",
input: &EditOptions{
Detector: &fd.EnabledDetectorMock{},
SelectorArg: "123",
Finder: shared.NewMockFinder("123", &api.PullRequest{URL: "https://github.com/OWNER/REPO/pull/123"}, ghrepo.New("OWNER", "REPO")),
Interactive: false,
Editable: shared.Editable{
Reviewers: shared.EditableSlice{Add: []string{"monalisa"}, Remove: []string{"hubot"}, Default: []string{"OWNER/core"}, Edited: true},
},
Fetcher: testFetcher{},
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
// reviewers only (users), no team reviewers fetched
mockRepoMetadata(reg, mockRepoMetadataOptions{reviewers: true})
// explicitly assert that no OrganizationTeamList query occurs
reg.Exclude(t, httpmock.GraphQL(`query OrganizationTeamList\b`))
mockPullRequestUpdate(reg)
mockPullRequestAddReviewers(reg)
},
stdout: "https://github.com/OWNER/REPO/pull/123\n",
},
{
name: "interactive",
input: &EditOptions{
Detector: &fd.EnabledDetectorMock{},
SelectorArg: "123",
Finder: shared.NewMockFinder("123", &api.PullRequest{
URL: "https://github.com/OWNER/REPO/pull/123",
}, ghrepo.New("OWNER", "REPO")),
Interactive: true,
Surveyor: testSurveyor{
fieldsToEdit: func(e *shared.Editable) error {
e.Title.Edited = true
e.Body.Edited = true
e.Reviewers.Edited = true
e.Assignees.Edited = true
e.Labels.Edited = true
e.Projects.Edited = true
e.Milestone.Edited = true
return nil
},
editFields: func(e *shared.Editable, _ string) error {
e.Title.Value = "new title"
e.Body.Value = "new body"
e.Reviewers.Value = []string{"monalisa", "hubot", "OWNER/core", "OWNER/external"}
e.Assignees.Value = []string{"monalisa", "hubot"}
e.Labels.Value = []string{"feature", "TODO", "bug"}
e.Labels.Add = []string{"feature", "TODO", "bug"}
e.Labels.Remove = []string{"docs"}
e.Projects.Value = []string{"Cleanup", "CleanupV2"}
e.Milestone.Value = "GA"
return nil
},
},
Fetcher: testFetcher{},
EditorRetriever: testEditorRetriever{},
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockRepoMetadata(reg, mockRepoMetadataOptions{reviewers: true, teamReviewers: true, assignees: true, labels: true, projects: true, milestones: true})
mockPullRequestUpdate(reg)
mockPullRequestUpdateActorAssignees(reg)
mockPullRequestAddReviewers(reg)
mockPullRequestUpdateLabels(reg)
mockProjectV2ItemUpdate(reg)
},
stdout: "https://github.com/OWNER/REPO/pull/123\n",
},
{
name: "interactive skip reviewers",
input: &EditOptions{
Detector: &fd.EnabledDetectorMock{},
SelectorArg: "123",
Finder: shared.NewMockFinder("123", &api.PullRequest{
URL: "https://github.com/OWNER/REPO/pull/123",
}, ghrepo.New("OWNER", "REPO")),
Interactive: true,
Surveyor: testSurveyor{
fieldsToEdit: func(e *shared.Editable) error {
e.Title.Edited = true
e.Body.Edited = true
e.Assignees.Edited = true
e.Labels.Edited = true
e.Projects.Edited = true
e.Milestone.Edited = true
return nil
},
editFields: func(e *shared.Editable, _ string) error {
e.Title.Value = "new title"
e.Body.Value = "new body"
e.Assignees.Value = []string{"monalisa", "hubot"}
e.Labels.Value = []string{"feature", "TODO", "bug"}
e.Labels.Add = []string{"feature", "TODO", "bug"}
e.Labels.Remove = []string{"docs"}
e.Projects.Value = []string{"Cleanup", "CleanupV2"}
e.Milestone.Value = "GA"
return nil
},
},
Fetcher: testFetcher{},
EditorRetriever: testEditorRetriever{},
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
// interactive but reviewers not chosen; need everything except reviewers/teams
mockRepoMetadata(reg, mockRepoMetadataOptions{assignees: true, labels: true, projects: true, milestones: true})
mockPullRequestUpdate(reg)
mockPullRequestUpdateActorAssignees(reg)
mockPullRequestUpdateLabels(reg)
mockProjectV2ItemUpdate(reg)
},
stdout: "https://github.com/OWNER/REPO/pull/123\n",
},
{
name: "interactive remove all reviewers",
input: &EditOptions{
Detector: &fd.EnabledDetectorMock{},
SelectorArg: "123",
Finder: shared.NewMockFinder("123", &api.PullRequest{ // include existing reviewers
URL: "https://github.com/OWNER/REPO/pull/123",
ReviewRequests: api.ReviewRequests{Nodes: []struct{ RequestedReviewer api.RequestedReviewer }{
{RequestedReviewer: api.RequestedReviewer{TypeName: "Team", Slug: "core", Organization: struct {
Login string `json:"login"`
}{Login: "OWNER"}}},
{RequestedReviewer: api.RequestedReviewer{TypeName: "Team", Slug: "external", Organization: struct {
Login string `json:"login"`
}{Login: "OWNER"}}},
{RequestedReviewer: api.RequestedReviewer{TypeName: "User", Login: "monalisa"}},
{RequestedReviewer: api.RequestedReviewer{TypeName: "User", Login: "hubot"}},
{RequestedReviewer: api.RequestedReviewer{TypeName: "User", Login: "dependabot"}},
}},
}, ghrepo.New("OWNER", "REPO")),
Interactive: true,
Surveyor: testSurveyor{
fieldsToEdit: func(e *shared.Editable) error {
e.Title.Edited = true
e.Body.Edited = true
e.Reviewers.Edited = true
e.Assignees.Edited = true
e.Labels.Edited = true
e.Projects.Edited = true
e.Milestone.Edited = true
return nil
},
editFields: func(e *shared.Editable, _ string) error {
e.Title.Value = "new title"
e.Body.Value = "new body"
e.Reviewers.Remove = []string{"monalisa", "hubot", "OWNER/core", "OWNER/external", "dependabot"}
e.Assignees.Value = []string{"monalisa", "hubot"}
e.Labels.Value = []string{"feature", "TODO", "bug"}
e.Labels.Add = []string{"feature", "TODO", "bug"}
e.Labels.Remove = []string{"docs"}
e.Projects.Value = []string{"Cleanup", "CleanupV2"}
e.Milestone.Value = "GA"
return nil
},
},
Fetcher: testFetcher{},
EditorRetriever: testEditorRetriever{},
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
mockRepoMetadata(reg, mockRepoMetadataOptions{reviewers: true, teamReviewers: true, assignees: true, labels: true, projects: true, milestones: true})
mockPullRequestUpdate(reg)
mockPullRequestRemoveReviewers(reg)
mockPullRequestUpdateActorAssignees(reg)
mockPullRequestUpdateLabels(reg)
mockProjectV2ItemUpdate(reg)
},
stdout: "https://github.com/OWNER/REPO/pull/123\n",
},
{
name: "interactive prompts with actor assignee display names when actors available",
input: &EditOptions{
Detector: &fd.EnabledDetectorMock{},
SelectorArg: "123",
Finder: shared.NewMockFinder("123", &api.PullRequest{
URL: "https://github.com/OWNER/REPO/pull/123",
AssignedActors: api.AssignedActors{
Nodes: []api.Actor{
{
ID: "HUBOTID",
Login: "hubot",
TypeName: "Bot",
},
},
TotalCount: 1,
},
}, ghrepo.New("OWNER", "REPO")),
Interactive: true,
Surveyor: testSurveyor{
fieldsToEdit: func(e *shared.Editable) error {
e.Assignees.Edited = true
return nil
},
editFields: func(e *shared.Editable, _ string) error {
// Checking that the display name is being used in the prompt.
require.Equal(t, []string{"hubot"}, e.Assignees.Default)
require.Equal(t, []string{"hubot"}, e.Assignees.DefaultLogins)
// Adding MonaLisa as PR assignee, should preserve hubot.
e.Assignees.Value = []string{"hubot", "MonaLisa (Mona Display Name)"}
return nil
},
},
Fetcher: testFetcher{},
EditorRetriever: testEditorRetriever{},
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
reg.Register(
httpmock.GraphQL(`query RepositoryAssignableActors\b`),
httpmock.StringResponse(`
{ "data": { "repository": { "suggestedActors": {
"nodes": [
{ "login": "hubot", "id": "HUBOTID", "__typename": "Bot" },
{ "login": "MonaLisa", "id": "MONAID", "name": "Mona Display Name", "__typename": "User" }
],
"pageInfo": { "hasNextPage": false }
} } } }
`))
mockPullRequestUpdate(reg)
reg.Register(
httpmock.GraphQL(`mutation ReplaceActorsForAssignable\b`),
httpmock.GraphQLMutation(`
{ "data": { "replaceActorsForAssignable": { "__typename": "" } } }`,
func(inputs map[string]interface{}) {
// Checking that despite the display name being returned
// from the EditFieldsSurvey, the ID is still
// used in the mutation.
require.Subset(t, inputs["actorIds"], []string{"MONAID", "HUBOTID"})
}),
)
},
stdout: "https://github.com/OWNER/REPO/pull/123\n",
},
{
name: "Legacy assignee users are fetched and updated on unsupported GitHub Hosts",
input: &EditOptions{
Detector: &fd.DisabledDetectorMock{},
SelectorArg: "123",
Finder: shared.NewMockFinder("123", &api.PullRequest{
URL: "https://github.com/OWNER/REPO/pull/123",
}, ghrepo.New("OWNER", "REPO")),
Interactive: false,
Editable: shared.Editable{
Assignees: shared.EditableAssignees{
EditableSlice: shared.EditableSlice{
Add: []string{"monalisa", "hubot"},
Remove: []string{"octocat"},
Edited: true,
},
},
},
Fetcher: testFetcher{},
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
// Notice there is no call to mockReplaceActorsForAssignable()
// and no GraphQL call to RepositoryAssignableActors below.
reg.Register(
httpmock.GraphQL(`query RepositoryAssignableUsers\b`),
httpmock.StringResponse(`
{ "data": { "repository": { "assignableUsers": {
"nodes": [
{ "login": "hubot", "id": "HUBOTID" },
{ "login": "MonaLisa", "id": "MONAID" }
],
"pageInfo": { "hasNextPage": false }
} } } }
`))
mockPullRequestUpdate(reg)
},
stdout: "https://github.com/OWNER/REPO/pull/123\n",
},
{
name: "non-interactive projects v1 unsupported doesn't fetch v1 metadata",
input: &EditOptions{
Detector: &fd.DisabledDetectorMock{},
SelectorArg: "123",
Finder: shared.NewMockFinder("123", &api.PullRequest{
URL: "https://github.com/OWNER/REPO/pull/123",
}, ghrepo.New("OWNER", "REPO")),
Interactive: false,
Editable: shared.Editable{
Projects: shared.EditableProjects{
EditableSlice: shared.EditableSlice{
Add: []string{"CleanupV2"},
Remove: []string{"RoadmapV2"},
Edited: true,
},
},
},
Fetcher: testFetcher{},
},
httpStubs: func(t *testing.T, reg *httpmock.Registry) {
// Ensure v1 project queries are NOT made.
reg.Exclude(t, httpmock.GraphQL(`query RepositoryProjectList\b`))
reg.Exclude(t, httpmock.GraphQL(`query OrganizationProjectList\b`))
// Provide only v2 project metadata queries.
reg.Register(
httpmock.GraphQL(`query RepositoryProjectV2List\b`),
httpmock.StringResponse(`
{ "data": { "repository": { "projectsV2": {
"nodes": [
{ "title": "CleanupV2", "id": "CLEANUPV2ID" },
{ "title": "RoadmapV2", "id": "ROADMAPV2ID" }
],
"pageInfo": { "hasNextPage": false }
} } } }
`))
reg.Register(
httpmock.GraphQL(`query OrganizationProjectV2List\b`),
httpmock.StringResponse(`
{ "data": { "organization": { "projectsV2": {
"nodes": [
{ "title": "TriageV2", "id": "TRIAGEV2ID" }
],
"pageInfo": { "hasNextPage": false }
} } } }
`))
reg.Register(
httpmock.GraphQL(`query UserProjectV2List\b`),
httpmock.StringResponse(`
{ "data": { "viewer": { "projectsV2": {
"nodes": [
{ "title": "MonalisaV2", "id": "MONALISAV2ID" }
],
"pageInfo": { "hasNextPage": false }
} } } }
`))
mockProjectV2ItemUpdate(reg)
mockPullRequestUpdate(reg)
},
stdout: "https://github.com/OWNER/REPO/pull/123\n",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdoutTTY(true)
ios.SetStdinTTY(true)
ios.SetStderrTTY(true)
reg := &httpmock.Registry{}
defer reg.Verify(t)
tt.httpStubs(t, reg)
httpClient := func() (*http.Client, error) { return &http.Client{Transport: reg}, nil }
baseRepo := func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil }
tt.input.IO = ios
tt.input.HttpClient = httpClient
tt.input.BaseRepo = baseRepo
err := editRun(tt.input)
assert.NoError(t, err)
assert.Equal(t, tt.stdout, stdout.String())
assert.Equal(t, tt.stderr, stderr.String())
})
}
}
type mockRepoMetadataOptions struct {
reviewers bool
teamReviewers bool // reviewers must also be true for this to have an effect.
assignees bool
labels bool
projects bool // includes both legacy (v1) and v2
milestones bool
}
func mockRepoMetadata(reg *httpmock.Registry, opt mockRepoMetadataOptions) {
// Assignable actors (users/bots) are fetched when reviewers OR assignees edited with ActorAssignees enabled.
if opt.reviewers || opt.assignees {
reg.Register(
httpmock.GraphQL(`query RepositoryAssignableActors\b`),
httpmock.StringResponse(`
{ "data": { "repository": { "suggestedActors": {
"nodes": [
{ "login": "hubot", "id": "HUBOTID", "__typename": "Bot" },
{ "login": "MonaLisa", "id": "MONAID", "name": "Mona Display Name", "__typename": "User" }
],
"pageInfo": { "hasNextPage": false }
} } } }
`))
}
if opt.labels {
reg.Register(
httpmock.GraphQL(`query RepositoryLabelList\b`),
httpmock.StringResponse(`
{ "data": { "repository": { "labels": {
"nodes": [
{ "name": "feature", "id": "FEATUREID" },
{ "name": "TODO", "id": "TODOID" },
{ "name": "bug", "id": "BUGID" },
{ "name": "docs", "id": "DOCSID" }
],
"pageInfo": { "hasNextPage": false }
} } } }
`))
}
if opt.milestones {
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 }
} } } }
`))
}
if opt.projects {
reg.Register(
httpmock.GraphQL(`query RepositoryProjectList\b`),
httpmock.StringResponse(`
{ "data": { "repository": { "projects": {
"nodes": [
{ "name": "Cleanup", "id": "CLEANUPID" },
{ "name": "Roadmap", "id": "ROADMAPID" }
],
"pageInfo": { "hasNextPage": false }
} } } }
`))
reg.Register(
httpmock.GraphQL(`query OrganizationProjectList\b`),
httpmock.StringResponse(`
{ "data": { "organization": { "projects": {
"nodes": [
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | true |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/diff/diff.go | pkg/cmd/pr/diff/diff.go | package diff
import (
"bufio"
"errors"
"fmt"
"io"
"net/http"
"regexp"
"strings"
"unicode"
"unicode/utf8"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/browser"
"github.com/cli/cli/v2/internal/ghinstance"
"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"
"golang.org/x/text/transform"
)
type DiffOptions struct {
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
Browser browser.Browser
Finder shared.PRFinder
SelectorArg string
UseColor bool
Patch bool
NameOnly bool
BrowserMode bool
}
func NewCmdDiff(f *cmdutil.Factory, runF func(*DiffOptions) error) *cobra.Command {
opts := &DiffOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
Browser: f.Browser,
}
var colorFlag string
cmd := &cobra.Command{
Use: "diff [<number> | <url> | <branch>]",
Short: "View changes in a pull request",
Long: heredoc.Docf(`
View changes in a pull request.
Without an argument, the pull request that belongs to the current branch
is selected.
With %[1]s--web%[1]s flag, open the pull request diff in a web browser instead.
`, "`"),
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]
}
switch colorFlag {
case "always":
opts.UseColor = true
case "auto":
opts.UseColor = opts.IO.ColorEnabled()
case "never":
opts.UseColor = false
default:
return fmt.Errorf("unsupported color %q", colorFlag)
}
if runF != nil {
return runF(opts)
}
return diffRun(opts)
},
}
cmdutil.StringEnumFlag(cmd, &colorFlag, "color", "", "auto", []string{"always", "never", "auto"}, "Use color in diff output")
cmd.Flags().BoolVar(&opts.Patch, "patch", false, "Display diff in patch format")
cmd.Flags().BoolVar(&opts.NameOnly, "name-only", false, "Display only names of changed files")
cmd.Flags().BoolVarP(&opts.BrowserMode, "web", "w", false, "Open the pull request diff in the browser")
return cmd
}
func diffRun(opts *DiffOptions) error {
findOptions := shared.FindOptions{
Selector: opts.SelectorArg,
Fields: []string{"number"},
}
if opts.BrowserMode {
findOptions.Fields = []string{"url"}
}
pr, baseRepo, err := opts.Finder.Find(findOptions)
if err != nil {
return err
}
if opts.BrowserMode {
openUrl := fmt.Sprintf("%s/files", pr.URL)
if opts.IO.IsStdoutTTY() {
fmt.Fprintf(opts.IO.ErrOut, "Opening %s in your browser.\n", text.DisplayURL(openUrl))
}
return opts.Browser.Browse(openUrl)
}
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
if opts.NameOnly {
opts.Patch = false
}
diffReadCloser, err := fetchDiff(httpClient, baseRepo, pr.Number, opts.Patch)
if err != nil {
return fmt.Errorf("could not find pull request diff: %w", err)
}
defer diffReadCloser.Close()
var diff io.Reader = diffReadCloser
if opts.IO.IsStdoutTTY() {
diff = sanitizedReader(diff)
}
if err := opts.IO.StartPager(); err == nil {
defer opts.IO.StopPager()
} else {
fmt.Fprintf(opts.IO.ErrOut, "failed to start pager: %v\n", err)
}
if opts.NameOnly {
return changedFilesNames(opts.IO.Out, diff)
}
if !opts.UseColor {
_, err = io.Copy(opts.IO.Out, diff)
return err
}
return colorDiffLines(opts.IO.Out, diff)
}
func fetchDiff(httpClient *http.Client, baseRepo ghrepo.Interface, prNumber int, asPatch bool) (io.ReadCloser, error) {
url := fmt.Sprintf(
"%srepos/%s/pulls/%d",
ghinstance.RESTPrefix(baseRepo.RepoHost()),
ghrepo.FullName(baseRepo),
prNumber,
)
acceptType := "application/vnd.github.v3.diff"
if asPatch {
acceptType = "application/vnd.github.v3.patch"
}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", acceptType)
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, api.HandleHTTPError(resp)
}
return resp.Body, nil
}
const lineBufferSize = 4096
var (
colorHeader = []byte("\x1b[1;38m")
colorAddition = []byte("\x1b[32m")
colorRemoval = []byte("\x1b[31m")
colorReset = []byte("\x1b[m")
)
func colorDiffLines(w io.Writer, r io.Reader) error {
diffLines := bufio.NewReaderSize(r, lineBufferSize)
wasPrefix := false
needsReset := false
for {
diffLine, isPrefix, err := diffLines.ReadLine()
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return fmt.Errorf("error reading pull request diff: %w", err)
}
var color []byte
if !wasPrefix {
if isHeaderLine(diffLine) {
color = colorHeader
} else if isAdditionLine(diffLine) {
color = colorAddition
} else if isRemovalLine(diffLine) {
color = colorRemoval
}
}
if color != nil {
if _, err := w.Write(color); err != nil {
return err
}
needsReset = true
}
if _, err := w.Write(diffLine); err != nil {
return err
}
if !isPrefix {
if needsReset {
if _, err := w.Write(colorReset); err != nil {
return err
}
needsReset = false
}
if _, err := w.Write([]byte{'\n'}); err != nil {
return err
}
}
wasPrefix = isPrefix
}
return nil
}
var diffHeaderPrefixes = []string{"+++", "---", "diff", "index"}
func isHeaderLine(l []byte) bool {
dl := string(l)
for _, p := range diffHeaderPrefixes {
if strings.HasPrefix(dl, p) {
return true
}
}
return false
}
func isAdditionLine(l []byte) bool {
return len(l) > 0 && l[0] == '+'
}
func isRemovalLine(l []byte) bool {
return len(l) > 0 && l[0] == '-'
}
func changedFilesNames(w io.Writer, r io.Reader) error {
diff, err := io.ReadAll(r)
if err != nil {
return err
}
// This is kind of a gnarly regex. We're looking lines of the format:
// diff --git a/9114-triage b/9114-triage
// diff --git "a/hello-\360\237\230\200-world" "b/hello-\360\237\230\200-world"
//
// From these lines we would look to extract:
// 9114-triage
// "hello-\360\237\230\200-world"
//
// Note that the b/ is removed but in the second case the preceeding quote remains.
// This is important for how git handles filenames that would be quoted with core.quotePath.
// https://git-scm.com/docs/git-config#Documentation/git-config.txt-corequotePath
//
// Thus we capture the quote if it exists, and everything that follows the b/
// We then concatenate those two capture groups together which for the examples above would be:
// `` + 9114-triage
// `"`` + hello-\360\237\230\200-world"
//
// Where I'm using the `` to indicate a string to avoid confusion with the " character.
pattern := regexp.MustCompile(`(?:^|\n)diff\s--git.*\s(["]?)b/(.*)`)
matches := pattern.FindAllStringSubmatch(string(diff), -1)
for _, val := range matches {
name := strings.TrimSpace(val[1] + val[2])
if _, err := w.Write([]byte(name + "\n")); err != nil {
return err
}
}
return nil
}
func sanitizedReader(r io.Reader) io.Reader {
return transform.NewReader(r, sanitizer{})
}
// sanitizer replaces non-printable characters with their printable representations
type sanitizer struct{ transform.NopResetter }
// Transform implements transform.Transformer.
func (t sanitizer) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) {
for r, size := rune(0), 0; nSrc < len(src); {
if r = rune(src[nSrc]); r < utf8.RuneSelf {
size = 1
} else if r, size = utf8.DecodeRune(src[nSrc:]); size == 1 && !atEOF && !utf8.FullRune(src[nSrc:]) {
// Invalid rune.
err = transform.ErrShortSrc
break
}
if isPrint(r) {
if nDst+size > len(dst) {
err = transform.ErrShortDst
break
}
for i := 0; i < size; i++ {
dst[nDst] = src[nSrc]
nDst++
nSrc++
}
continue
} else {
nSrc += size
}
replacement := fmt.Sprintf("\\u{%02x}", r)
if nDst+len(replacement) > len(dst) {
err = transform.ErrShortDst
break
}
for _, c := range replacement {
dst[nDst] = byte(c)
nDst++
}
}
return
}
// isPrint reports if a rune is safe to be printed to a terminal
func isPrint(r rune) bool {
return r == '\n' || r == '\r' || r == '\t' || unicode.IsPrint(r)
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/diff/diff_test.go | pkg/cmd/pr/diff/diff_test.go | package diff
import (
"bytes"
"fmt"
"io"
"net/http"
"strings"
"testing"
"testing/iotest"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/browser"
"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/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_NewCmdDiff(t *testing.T) {
tests := []struct {
name string
args string
isTTY bool
want DiffOptions
wantErr string
}{
{
name: "name only",
args: "--name-only",
want: DiffOptions{
NameOnly: true,
},
},
{
name: "number argument",
args: "123",
isTTY: true,
want: DiffOptions{
SelectorArg: "123",
UseColor: true,
},
},
{
name: "no argument",
args: "",
isTTY: true,
want: DiffOptions{
SelectorArg: "",
UseColor: true,
},
},
{
name: "no color when redirected",
args: "",
isTTY: false,
want: DiffOptions{
SelectorArg: "",
UseColor: false,
},
},
{
name: "force color",
args: "--color always",
isTTY: false,
want: DiffOptions{
SelectorArg: "",
UseColor: true,
},
},
{
name: "disable color",
args: "--color never",
isTTY: true,
want: DiffOptions{
SelectorArg: "",
UseColor: false,
},
},
{
name: "no argument with --repo override",
args: "-R owner/repo",
isTTY: true,
wantErr: "argument required when using the `--repo` flag",
},
{
name: "invalid --color argument",
args: "--color doublerainbow",
isTTY: true,
wantErr: "invalid argument \"doublerainbow\" for \"--color\" flag: valid values are {always|never|auto}",
},
{
name: "web mode",
args: "123 --web",
isTTY: true,
want: DiffOptions{
SelectorArg: "123",
UseColor: true,
BrowserMode: true,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
ios.SetStdoutTTY(tt.isTTY)
ios.SetStdinTTY(tt.isTTY)
ios.SetStderrTTY(tt.isTTY)
ios.SetColorEnabled(tt.isTTY)
f := &cmdutil.Factory{
IOStreams: ios,
}
var opts *DiffOptions
cmd := NewCmdDiff(f, func(o *DiffOptions) 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.UseColor, opts.UseColor)
assert.Equal(t, tt.want.BrowserMode, opts.BrowserMode)
})
}
}
func Test_diffRun(t *testing.T) {
pr := &api.PullRequest{Number: 123, URL: "https://github.com/OWNER/REPO/pull/123"}
tests := []struct {
name string
opts DiffOptions
wantFields []string
wantStdout string
wantStderr string
wantBrowsedURL string
httpStubs func(*httpmock.Registry)
}{
{
name: "no color",
opts: DiffOptions{
SelectorArg: "123",
UseColor: false,
Patch: false,
},
wantFields: []string{"number"},
wantStdout: fmt.Sprintf(testDiff, "", "", "", ""),
httpStubs: func(reg *httpmock.Registry) {
stubDiffRequest(reg, "application/vnd.github.v3.diff", fmt.Sprintf(testDiff, "", "", "", ""))
},
},
{
name: "with color",
opts: DiffOptions{
SelectorArg: "123",
UseColor: true,
Patch: false,
},
wantFields: []string{"number"},
wantStdout: fmt.Sprintf(testDiff, "\x1b[m", "\x1b[1;38m", "\x1b[32m", "\x1b[31m"),
httpStubs: func(reg *httpmock.Registry) {
stubDiffRequest(reg, "application/vnd.github.v3.diff", fmt.Sprintf(testDiff, "", "", "", ""))
},
},
{
name: "patch format",
opts: DiffOptions{
SelectorArg: "123",
UseColor: false,
Patch: true,
},
wantFields: []string{"number"},
wantStdout: fmt.Sprintf(testDiff, "", "", "", ""),
httpStubs: func(reg *httpmock.Registry) {
stubDiffRequest(reg, "application/vnd.github.v3.patch", fmt.Sprintf(testDiff, "", "", "", ""))
},
},
{
name: "name only",
opts: DiffOptions{
SelectorArg: "123",
UseColor: false,
Patch: false,
NameOnly: true,
},
wantFields: []string{"number"},
wantStdout: ".github/workflows/releases.yml\nMakefile\n",
httpStubs: func(reg *httpmock.Registry) {
stubDiffRequest(reg, "application/vnd.github.v3.diff", fmt.Sprintf(testDiff, "", "", "", ""))
},
},
{
name: "web mode",
opts: DiffOptions{
SelectorArg: "123",
BrowserMode: true,
},
wantFields: []string{"url"},
wantStderr: "Opening https://github.com/OWNER/REPO/pull/123/files in your browser.\n",
wantBrowsedURL: "https://github.com/OWNER/REPO/pull/123/files",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
httpReg := &httpmock.Registry{}
defer httpReg.Verify(t)
if tt.httpStubs != nil {
tt.httpStubs(httpReg)
}
tt.opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: httpReg}, nil
}
browser := &browser.Stub{}
tt.opts.Browser = browser
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdoutTTY(true)
tt.opts.IO = ios
finder := shared.NewMockFinder("123", pr, ghrepo.New("OWNER", "REPO"))
finder.ExpectFields(tt.wantFields)
tt.opts.Finder = finder
err := diffRun(&tt.opts)
assert.NoError(t, err)
assert.Equal(t, tt.wantStdout, stdout.String())
assert.Equal(t, tt.wantStderr, stderr.String())
assert.Equal(t, tt.wantBrowsedURL, browser.BrowsedURL())
})
}
}
const testDiff = `%[2]sdiff --git a/.github/workflows/releases.yml b/.github/workflows/releases.yml%[1]s
%[2]sindex 73974448..b7fc0154 100644%[1]s
%[2]s--- a/.github/workflows/releases.yml%[1]s
%[2]s+++ b/.github/workflows/releases.yml%[1]s
@@ -44,6 +44,11 @@ jobs:
token: ${{secrets.SITE_GITHUB_TOKEN}}
- name: Publish documentation site
if: "!contains(github.ref, '-')" # skip prereleases
%[3]s+ env:%[1]s
%[3]s+ GIT_COMMITTER_NAME: cli automation%[1]s
%[3]s+ GIT_AUTHOR_NAME: cli automation%[1]s
%[3]s+ GIT_COMMITTER_EMAIL: noreply@github.com%[1]s
%[3]s+ GIT_AUTHOR_EMAIL: noreply@github.com%[1]s
run: make site-publish
- name: Move project cards
if: "!contains(github.ref, '-')" # skip prereleases
%[2]sdiff --git a/Makefile b/Makefile%[1]s
%[2]sindex f2b4805c..3d7bd0f9 100644%[1]s
%[2]s--- a/Makefile%[1]s
%[2]s+++ b/Makefile%[1]s
@@ -22,8 +22,8 @@ test:
go test ./...
.PHONY: test
%[4]s-site:%[1]s
%[4]s- git clone https://github.com/github/cli.github.com.git "$@"%[1]s
%[3]s+site: bin/gh%[1]s
%[3]s+ bin/gh repo clone github/cli.github.com "$@"%[1]s
site-docs: site
git -C site pull
`
func Test_colorDiffLines(t *testing.T) {
inputs := []struct {
input, output string
}{
{
input: "",
output: "",
},
{
input: "\n",
output: "\n",
},
{
input: "foo\nbar\nbaz\n",
output: "foo\nbar\nbaz\n",
},
{
input: "foo\nbar\nbaz",
output: "foo\nbar\nbaz\n",
},
{
input: fmt.Sprintf("+foo\n-b%sr\n+++ baz\n", strings.Repeat("a", 2*lineBufferSize)),
output: fmt.Sprintf(
"%[4]s+foo%[2]s\n%[5]s-b%[1]sr%[2]s\n%[3]s+++ baz%[2]s\n",
strings.Repeat("a", 2*lineBufferSize),
"\x1b[m",
"\x1b[1;38m",
"\x1b[32m",
"\x1b[31m",
),
},
}
for _, tt := range inputs {
buf := bytes.Buffer{}
if err := colorDiffLines(&buf, strings.NewReader(tt.input)); err != nil {
t.Fatalf("unexpected error: %s", err)
}
if got := buf.String(); got != tt.output {
t.Errorf("expected: %q, got: %q", tt.output, got)
}
}
}
func Test_changedFileNames(t *testing.T) {
inputs := []struct {
input, output string
}{
{
input: "",
output: "",
},
{
input: "\n",
output: "",
},
{
input: "diff --git a/cmd.go b/cmd.go\n--- /dev/null\n+++ b/cmd.go\n@@ -0,0 +1,313 @@",
output: "cmd.go\n",
},
{
input: "diff --git a/cmd.go b/cmd.go\n--- a/cmd.go\n+++ /dev/null\n@@ -0,0 +1,313 @@",
output: "cmd.go\n",
},
{
input: fmt.Sprintf("diff --git a/baz.go b/rename.go\n--- a/baz.go\n+++ b/rename.go\n+foo\n-b%sr", strings.Repeat("a", 2*lineBufferSize)),
output: "rename.go\n",
},
{
input: fmt.Sprintf("diff --git a/baz.go b/baz.go\n--- a/baz.go\n+++ b/baz.go\n+foo\n-b%sr", strings.Repeat("a", 2*lineBufferSize)),
output: "baz.go\n",
},
{
input: "diff --git \"a/\343\202\212\343\203\274\343\201\251\343\201\277\343\203\274.md\" \"b/\343\202\212\343\203\274\343\201\251\343\201\277\343\203\274.md\"",
output: "\"\343\202\212\343\203\274\343\201\251\343\201\277\343\203\274.md\"\n",
},
}
for _, tt := range inputs {
buf := bytes.Buffer{}
if err := changedFilesNames(&buf, strings.NewReader(tt.input)); err != nil {
t.Fatalf("unexpected error: %s", err)
}
if got := buf.String(); got != tt.output {
t.Errorf("expected: %q, got: %q", tt.output, got)
}
}
}
func stubDiffRequest(reg *httpmock.Registry, accept, diff string) {
reg.Register(
func(req *http.Request) bool {
if !strings.EqualFold(req.Method, "GET") {
return false
}
if req.URL.EscapedPath() != "/repos/OWNER/REPO/pulls/123" {
return false
}
return req.Header.Get("Accept") == accept
},
func(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: 200,
Request: req,
Body: io.NopCloser(strings.NewReader(diff)),
}, nil
})
}
func Test_sanitizedReader(t *testing.T) {
input := strings.NewReader("\t hello \x1B[m world! ăѣ𝔠ծề\r\n")
expected := "\t hello \\u{1b}[m world! ăѣ𝔠ծề\r\n"
err := iotest.TestReader(sanitizedReader(input), []byte(expected))
if err != nil {
t.Error(err)
}
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/checkout/checkout_test.go | pkg/cmd/pr/checkout/checkout_test.go | package checkout
import (
"bytes"
"errors"
"io"
"net/http"
"strings"
"testing"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/context"
"github.com/cli/cli/v2/git"
"github.com/cli/cli/v2/internal/config"
"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 TestNewCmdCheckout(t *testing.T) {
tests := []struct {
name string
args string
wantsOpts CheckoutOptions
wantErr error
}{
{
name: "recurse submodules",
args: "--recurse-submodules 123",
wantsOpts: CheckoutOptions{
RecurseSubmodules: true,
},
},
{
name: "force",
args: "--force 123",
wantsOpts: CheckoutOptions{
Force: true,
},
},
{
name: "detach",
args: "--detach 123",
wantsOpts: CheckoutOptions{
Detach: true,
},
},
{
name: "branch",
args: "--branch test-branch 123",
wantsOpts: CheckoutOptions{
BranchName: "test-branch",
},
},
{
name: "when there is no selector and no TTY, returns an error",
args: "",
wantErr: cmdutil.FlagErrorf("pull request number, URL, or branch required when not running interactively"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
f := &cmdutil.Factory{
IOStreams: ios,
}
ios.SetStdinTTY(false)
argv, err := shlex.Split(tt.args)
assert.NoError(t, err)
var spiedOpts *CheckoutOptions
cmd := NewCmdCheckout(f, func(opts *CheckoutOptions) error {
spiedOpts = opts
return nil
})
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
_, err = cmd.ExecuteC()
if tt.wantErr != nil {
require.Equal(t, tt.wantErr, err)
return
}
require.NoError(t, err)
require.Equal(t, tt.wantsOpts.RecurseSubmodules, spiedOpts.RecurseSubmodules)
require.Equal(t, tt.wantsOpts.Force, spiedOpts.Force)
require.Equal(t, tt.wantsOpts.Detach, spiedOpts.Detach)
require.Equal(t, tt.wantsOpts.BranchName, spiedOpts.BranchName)
})
}
}
// repo: either "baseOwner/baseRepo" or "baseOwner/baseRepo:defaultBranch"
// prHead: "headOwner/headRepo:headBranch"
func stubPR(repo, prHead string) (ghrepo.Interface, *api.PullRequest) {
return _stubPR(repo, prHead, 123, "PR title", "OPEN", false)
}
func _stubPR(repo, prHead string, number int, title string, state string, isDraft bool) (ghrepo.Interface, *api.PullRequest) {
defaultBranch := ""
if idx := strings.IndexRune(repo, ':'); idx >= 0 {
defaultBranch = repo[idx+1:]
repo = repo[:idx]
}
baseRepo, err := ghrepo.FromFullName(repo)
if err != nil {
panic(err)
}
if defaultBranch != "" {
baseRepo = api.InitRepoHostname(&api.Repository{
Name: baseRepo.RepoName(),
Owner: api.RepositoryOwner{Login: baseRepo.RepoOwner()},
DefaultBranchRef: api.BranchRef{Name: defaultBranch},
}, baseRepo.RepoHost())
}
idx := strings.IndexRune(prHead, ':')
headRefName := prHead[idx+1:]
headRepo, err := ghrepo.FromFullName(prHead[:idx])
if err != nil {
panic(err)
}
return baseRepo, &api.PullRequest{
Number: number,
HeadRefName: headRefName,
HeadRepositoryOwner: api.Owner{Login: headRepo.RepoOwner()},
HeadRepository: &api.PRRepository{Name: headRepo.RepoName()},
IsCrossRepository: !ghrepo.IsSame(baseRepo, headRepo),
MaintainerCanModify: false,
Title: title,
State: state,
IsDraft: isDraft,
}
}
type stubPRResolver struct {
pr *api.PullRequest
baseRepo ghrepo.Interface
err error
}
func (s *stubPRResolver) Resolve() (*api.PullRequest, ghrepo.Interface, error) {
if s.err != nil {
return nil, nil, s.err
}
return s.pr, s.baseRepo, nil
}
func Test_checkoutRun(t *testing.T) {
tests := []struct {
name string
opts *CheckoutOptions
httpStubs func(*httpmock.Registry)
runStubs func(*run.CommandStubber)
promptStubs func(*prompter.MockPrompter)
remotes map[string]string
wantStdout string
wantStderr string
wantErr bool
errMsg string
}{
{
name: "checkout with ssh remote URL",
opts: &CheckoutOptions{
PRResolver: func() PRResolver {
baseRepo, pr := stubPR("OWNER/REPO:master", "OWNER/REPO:feature")
return &stubPRResolver{
pr: pr,
baseRepo: baseRepo,
}
}(),
Config: func() (gh.Config, error) {
return config.NewBlankConfig(), nil
},
Branch: func() (string, error) {
return "main", nil
},
},
remotes: map[string]string{
"origin": "OWNER/REPO",
},
runStubs: func(cs *run.CommandStubber) {
cs.Register(`git show-ref --verify -- refs/heads/feature`, 1, "")
cs.Register(`git fetch origin \+refs/heads/feature:refs/remotes/origin/feature --no-tags`, 0, "")
cs.Register(`git checkout -b feature --track origin/feature`, 0, "")
},
},
{
name: "fork repo was deleted",
opts: &CheckoutOptions{
PRResolver: func() PRResolver {
baseRepo, pr := stubPR("OWNER/REPO:master", "OWNER/REPO:feature")
pr.MaintainerCanModify = true
pr.HeadRepository = nil
return &stubPRResolver{
pr: pr,
baseRepo: baseRepo,
}
}(),
Config: func() (gh.Config, error) {
return config.NewBlankConfig(), nil
},
Branch: func() (string, error) {
return "main", nil
},
},
remotes: map[string]string{
"origin": "OWNER/REPO",
},
runStubs: func(cs *run.CommandStubber) {
cs.Register(`git fetch origin refs/pull/123/head:feature --no-tags`, 0, "")
cs.Register(`git config branch\.feature\.merge`, 1, "")
cs.Register(`git checkout feature`, 0, "")
cs.Register(`git config branch\.feature\.remote origin`, 0, "")
cs.Register(`git config branch\.feature\.pushRemote origin`, 0, "")
cs.Register(`git config branch\.feature\.merge refs/pull/123/head`, 0, "")
},
},
{
name: "with local branch rename and existing git remote",
opts: &CheckoutOptions{
BranchName: "foobar",
PRResolver: func() PRResolver {
baseRepo, pr := stubPR("OWNER/REPO:master", "OWNER/REPO:feature")
return &stubPRResolver{
pr: pr,
baseRepo: baseRepo,
}
}(),
Config: func() (gh.Config, error) {
return config.NewBlankConfig(), nil
},
Branch: func() (string, error) {
return "main", nil
},
},
remotes: map[string]string{
"origin": "OWNER/REPO",
},
runStubs: func(cs *run.CommandStubber) {
cs.Register(`git show-ref --verify -- refs/heads/foobar`, 1, "")
cs.Register(`git fetch origin \+refs/heads/feature:refs/remotes/origin/feature --no-tags`, 0, "")
cs.Register(`git checkout -b foobar --track origin/feature`, 0, "")
},
},
{
name: "with local branch name, no existing git remote",
opts: &CheckoutOptions{
BranchName: "foobar",
PRResolver: func() PRResolver {
baseRepo, pr := stubPR("OWNER/REPO:master", "hubot/REPO:feature")
pr.MaintainerCanModify = true
return &stubPRResolver{
pr: pr,
baseRepo: baseRepo,
}
}(),
Config: func() (gh.Config, error) {
return config.NewBlankConfig(), nil
},
Branch: func() (string, error) {
return "main", nil
},
},
remotes: map[string]string{
"origin": "OWNER/REPO",
},
runStubs: func(cs *run.CommandStubber) {
cs.Register(`git config branch\.foobar\.merge`, 1, "")
cs.Register(`git fetch origin refs/pull/123/head:foobar --no-tags`, 0, "")
cs.Register(`git checkout foobar`, 0, "")
cs.Register(`git config branch\.foobar\.remote https://github.com/hubot/REPO.git`, 0, "")
cs.Register(`git config branch\.foobar\.pushRemote https://github.com/hubot/REPO.git`, 0, "")
cs.Register(`git config branch\.foobar\.merge refs/heads/feature`, 0, "")
},
},
{
name: "when the PR resolver errors, then that error is bubbled up",
opts: &CheckoutOptions{
PRResolver: &stubPRResolver{
err: errors.New("expected test error"),
},
},
wantErr: true,
errMsg: "expected test error",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
opts := tt.opts
ios, _, stdout, stderr := iostreams.Test()
opts.IO = ios
httpReg := &httpmock.Registry{}
defer httpReg.Verify(t)
if tt.httpStubs != nil {
tt.httpStubs(httpReg)
}
opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: httpReg}, nil
}
cmdStubs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
if tt.runStubs != nil {
tt.runStubs(cmdStubs)
}
opts.Remotes = func() (context.Remotes, error) {
if len(tt.remotes) == 0 {
return nil, errors.New("no remotes")
}
var remotes context.Remotes
for name, repo := range tt.remotes {
r, err := ghrepo.FromFullName(repo)
if err != nil {
return remotes, err
}
remotes = append(remotes, &context.Remote{
Remote: &git.Remote{Name: name},
Repo: r,
})
}
return remotes, nil
}
opts.GitClient = &git.Client{
GhPath: "some/path/gh",
GitPath: "some/path/git",
}
err := checkoutRun(opts)
if (err != nil) != tt.wantErr {
t.Errorf("want error: %v, got: %v", tt.wantErr, err)
}
if err != nil {
assert.Equal(t, tt.errMsg, err.Error())
}
assert.Equal(t, tt.wantStdout, stdout.String())
assert.Equal(t, tt.wantStderr, stderr.String())
})
}
}
func TestSpecificPRResolver(t *testing.T) {
t.Run("when the PR Finder returns results, those are returned", func(t *testing.T) {
t.Parallel()
baseRepo, pr := stubPR("OWNER/REPO:master", "OWNER/REPO:feature")
mockFinder := shared.NewMockFinder("123", pr, baseRepo)
mockFinder.ExpectFields([]string{"number", "headRefName", "headRepository", "headRepositoryOwner", "isCrossRepository", "maintainerCanModify"})
resolver := &specificPRResolver{
prFinder: mockFinder,
selector: "123",
}
resolvedPR, resolvedBaseRepo, err := resolver.Resolve()
require.NoError(t, err)
require.Equal(t, pr, resolvedPR)
require.True(t, ghrepo.IsSame(baseRepo, resolvedBaseRepo), "expected repos to be the same")
})
t.Run("when the PR Finder errors, that error is returned", func(t *testing.T) {
t.Parallel()
mockFinder := shared.NewMockFinder("123", nil, nil)
resolver := &specificPRResolver{
prFinder: mockFinder,
selector: "123",
}
_, _, err := resolver.Resolve()
var notFoundErr *shared.NotFoundError
require.ErrorAs(t, err, ¬FoundErr)
})
}
func TestPromptingPRResolver(t *testing.T) {
t.Run("when the PR Lister has results, then we prompt for a choice", func(t *testing.T) {
t.Parallel()
ios, _, _, _ := iostreams.Test()
baseRepo, pr1 := _stubPR("OWNER/REPO:master", "OWNER/REPO:feature", 32, "New feature", "OPEN", false)
_, pr2 := _stubPR("OWNER/REPO:master", "OWNER/REPO:bug-fix", 29, "Fixed bad bug", "OPEN", false)
_, pr3 := _stubPR("OWNER/REPO:master", "OWNER/REPO:docs", 28, "Improve documentation", "OPEN", true)
lister := shared.NewMockLister(&api.PullRequestAndTotalCount{
TotalCount: 3,
PullRequests: []api.PullRequest{
*pr1, *pr2, *pr3,
}, SearchCapped: false}, nil)
lister.ExpectFields([]string{"number", "title", "state", "isDraft", "headRefName", "headRepository", "headRepositoryOwner", "isCrossRepository", "maintainerCanModify"})
pm := prompter.NewMockPrompter(t)
pm.RegisterSelect("Select a pull request",
[]string{"32\tOPEN New feature [feature]", "29\tOPEN Fixed bad bug [bug-fix]", "28\tDRAFT Improve documentation [docs]"},
func(_, _ string, opts []string) (int, error) {
return prompter.IndexFor(opts, "32\tOPEN New feature [feature]")
})
resolver := &promptingPRResolver{
io: ios,
prompter: pm,
prLister: lister,
baseRepo: baseRepo,
}
resolvedPR, resolvedBaseRepo, err := resolver.Resolve()
require.NoError(t, err)
require.Equal(t, pr1, resolvedPR)
require.True(t, ghrepo.IsSame(baseRepo, resolvedBaseRepo), "expected repos to be the same")
})
t.Run("when the PR lister has no results, then we return an error", func(t *testing.T) {
t.Parallel()
ios, _, _, _ := iostreams.Test()
lister := shared.NewMockLister(&api.PullRequestAndTotalCount{
TotalCount: 0,
PullRequests: []api.PullRequest{},
}, nil)
resolver := &promptingPRResolver{
io: ios,
prLister: lister,
baseRepo: ghrepo.New("OWNER", "REPO"),
}
_, _, err := resolver.Resolve()
var noResultsErr cmdutil.NoResultsError
require.ErrorAs(t, err, &noResultsErr)
require.Equal(t, "no open pull requests in OWNER/REPO", noResultsErr.Error())
})
}
/** LEGACY TESTS **/
func runCommand(rt http.RoundTripper, remotes context.Remotes, branch string, cli string, baseRepo ghrepo.Interface) (*test.CmdOut, error) {
ios, _, stdout, stderr := iostreams.Test()
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
},
Remotes: func() (context.Remotes, error) {
if remotes == nil {
return context.Remotes{
{
Remote: &git.Remote{Name: "origin"},
Repo: ghrepo.New("OWNER", "REPO"),
},
}, nil
}
return remotes, nil
},
Branch: func() (string, error) {
return branch, nil
},
GitClient: &git.Client{
GhPath: "some/path/gh",
GitPath: "some/path/git",
},
BaseRepo: func() (ghrepo.Interface, error) {
return baseRepo, nil
},
}
cmd := NewCmdCheckout(factory, nil)
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 TestPRCheckout_sameRepo(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
baseRepo, pr := stubPR("OWNER/REPO", "OWNER/REPO:feature")
finder := shared.StubFinderForRunCommandStyleTests(t, "123", pr, baseRepo)
finder.ExpectFields([]string{"number", "headRefName", "headRepository", "headRepositoryOwner", "isCrossRepository", "maintainerCanModify"})
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git fetch origin \+refs/heads/feature:refs/remotes/origin/feature --no-tags`, 0, "")
cs.Register(`git show-ref --verify -- refs/heads/feature`, 1, "")
cs.Register(`git checkout -b feature --track origin/feature`, 0, "")
output, err := runCommand(http, nil, "master", `123`, baseRepo)
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, "", output.Stderr())
}
func TestPRCheckout_existingBranch(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
baseRepo, pr := stubPR("OWNER/REPO", "OWNER/REPO:feature")
shared.StubFinderForRunCommandStyleTests(t, "123", pr, baseRepo)
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git fetch origin \+refs/heads/feature:refs/remotes/origin/feature --no-tags`, 0, "")
cs.Register(`git show-ref --verify -- refs/heads/feature`, 0, "")
cs.Register(`git checkout feature`, 0, "")
cs.Register(`git merge --ff-only refs/remotes/origin/feature`, 0, "")
output, err := runCommand(http, nil, "master", `123`, baseRepo)
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, "", output.Stderr())
}
func TestPRCheckout_differentRepo_remoteExists(t *testing.T) {
remotes := context.Remotes{
{
Remote: &git.Remote{Name: "origin"},
Repo: ghrepo.New("OWNER", "REPO"),
},
{
Remote: &git.Remote{Name: "robot-fork"},
Repo: ghrepo.New("hubot", "REPO"),
},
}
http := &httpmock.Registry{}
defer http.Verify(t)
baseRepo, pr := stubPR("OWNER/REPO", "hubot/REPO:feature")
finder := shared.StubFinderForRunCommandStyleTests(t, "123", pr, baseRepo)
finder.ExpectFields([]string{"number", "headRefName", "headRepository", "headRepositoryOwner", "isCrossRepository", "maintainerCanModify"})
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git fetch robot-fork \+refs/heads/feature:refs/remotes/robot-fork/feature --no-tags`, 0, "")
cs.Register(`git show-ref --verify -- refs/heads/feature`, 1, "")
cs.Register(`git checkout -b feature --track robot-fork/feature`, 0, "")
output, err := runCommand(http, remotes, "master", `123`, baseRepo)
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, "", output.Stderr())
}
func TestPRCheckout_differentRepo(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
baseRepo, pr := stubPR("OWNER/REPO:master", "hubot/REPO:feature")
finder := shared.StubFinderForRunCommandStyleTests(t, "123", pr, baseRepo)
finder.ExpectFields([]string{"number", "headRefName", "headRepository", "headRepositoryOwner", "isCrossRepository", "maintainerCanModify"})
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git fetch origin refs/pull/123/head:feature --no-tags`, 0, "")
cs.Register(`git config branch\.feature\.merge`, 1, "")
cs.Register(`git checkout feature`, 0, "")
cs.Register(`git config branch\.feature\.remote origin`, 0, "")
cs.Register(`git config branch\.feature\.pushRemote origin`, 0, "")
cs.Register(`git config branch\.feature\.merge refs/pull/123/head`, 0, "")
output, err := runCommand(http, nil, "master", `123`, baseRepo)
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, "", output.Stderr())
}
func TestPRCheckout_differentRepoForce(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
baseRepo, pr := stubPR("OWNER/REPO:master", "hubot/REPO:feature")
finder := shared.StubFinderForRunCommandStyleTests(t, "123", pr, baseRepo)
finder.ExpectFields([]string{"number", "headRefName", "headRepository", "headRepositoryOwner", "isCrossRepository", "maintainerCanModify"})
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git fetch origin refs/pull/123/head:feature --no-tags --force`, 0, "")
cs.Register(`git config branch\.feature\.merge`, 1, "")
cs.Register(`git checkout feature`, 0, "")
cs.Register(`git config branch\.feature\.remote origin`, 0, "")
cs.Register(`git config branch\.feature\.pushRemote origin`, 0, "")
cs.Register(`git config branch\.feature\.merge refs/pull/123/head`, 0, "")
output, err := runCommand(http, nil, "master", `123 --force`, baseRepo)
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, "", output.Stderr())
}
func TestPRCheckout_differentRepo_existingBranch(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
baseRepo, pr := stubPR("OWNER/REPO:master", "hubot/REPO:feature")
shared.StubFinderForRunCommandStyleTests(t, "123", pr, baseRepo)
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git fetch origin refs/pull/123/head:feature --no-tags`, 0, "")
cs.Register(`git config branch\.feature\.merge`, 0, "refs/heads/feature\n")
cs.Register(`git checkout feature`, 0, "")
output, err := runCommand(http, nil, "master", `123`, baseRepo)
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, "", output.Stderr())
}
func TestPRCheckout_detachedHead(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
baseRepo, pr := stubPR("OWNER/REPO:master", "hubot/REPO:feature")
shared.StubFinderForRunCommandStyleTests(t, "123", pr, baseRepo)
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git fetch origin refs/pull/123/head:feature --no-tags`, 0, "")
cs.Register(`git config branch\.feature\.merge`, 0, "refs/heads/feature\n")
cs.Register(`git checkout feature`, 0, "")
output, err := runCommand(http, nil, "", `123`, baseRepo)
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, "", output.Stderr())
}
func TestPRCheckout_differentRepo_currentBranch(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
baseRepo, pr := stubPR("OWNER/REPO:master", "hubot/REPO:feature")
shared.StubFinderForRunCommandStyleTests(t, "123", pr, baseRepo)
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git fetch origin refs/pull/123/head --no-tags`, 0, "")
cs.Register(`git config branch\.feature\.merge`, 0, "refs/heads/feature\n")
cs.Register(`git merge --ff-only FETCH_HEAD`, 0, "")
output, err := runCommand(http, nil, "feature", `123`, baseRepo)
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, "", output.Stderr())
}
func TestPRCheckout_differentRepo_invalidBranchName(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
baseRepo, pr := stubPR("OWNER/REPO", "hubot/REPO:-foo")
shared.StubFinderForRunCommandStyleTests(t, "123", pr, baseRepo)
_, cmdTeardown := run.Stub()
defer cmdTeardown(t)
output, err := runCommand(http, nil, "master", `123`, baseRepo)
assert.EqualError(t, err, `invalid branch name: "-foo"`)
assert.Equal(t, "", output.Stderr())
assert.Equal(t, "", output.Stderr())
}
func TestPRCheckout_maintainerCanModify(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
baseRepo, pr := stubPR("OWNER/REPO:master", "hubot/REPO:feature")
pr.MaintainerCanModify = true
shared.StubFinderForRunCommandStyleTests(t, "123", pr, baseRepo)
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git fetch origin refs/pull/123/head:feature --no-tags`, 0, "")
cs.Register(`git config branch\.feature\.merge`, 1, "")
cs.Register(`git checkout feature`, 0, "")
cs.Register(`git config branch\.feature\.remote https://github\.com/hubot/REPO\.git`, 0, "")
cs.Register(`git config branch\.feature\.pushRemote https://github\.com/hubot/REPO\.git`, 0, "")
cs.Register(`git config branch\.feature\.merge refs/heads/feature`, 0, "")
output, err := runCommand(http, nil, "master", `123`, baseRepo)
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, "", output.Stderr())
}
func TestPRCheckout_recurseSubmodules(t *testing.T) {
http := &httpmock.Registry{}
baseRepo, pr := stubPR("OWNER/REPO", "OWNER/REPO:feature")
shared.StubFinderForRunCommandStyleTests(t, "123", pr, baseRepo)
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git fetch origin \+refs/heads/feature:refs/remotes/origin/feature --no-tags`, 0, "")
cs.Register(`git show-ref --verify -- refs/heads/feature`, 0, "")
cs.Register(`git checkout feature`, 0, "")
cs.Register(`git merge --ff-only refs/remotes/origin/feature`, 0, "")
cs.Register(`git submodule sync --recursive`, 0, "")
cs.Register(`git submodule update --init --recursive`, 0, "")
output, err := runCommand(http, nil, "master", `123 --recurse-submodules`, baseRepo)
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, "", output.Stderr())
}
func TestPRCheckout_force(t *testing.T) {
http := &httpmock.Registry{}
baseRepo, pr := stubPR("OWNER/REPO", "OWNER/REPO:feature")
shared.StubFinderForRunCommandStyleTests(t, "123", pr, baseRepo)
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git fetch origin \+refs/heads/feature:refs/remotes/origin/feature --no-tags`, 0, "")
cs.Register(`git show-ref --verify -- refs/heads/feature`, 0, "")
cs.Register(`git checkout feature`, 0, "")
cs.Register(`git reset --hard refs/remotes/origin/feature`, 0, "")
output, err := runCommand(http, nil, "master", `123 --force`, baseRepo)
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, "", output.Stderr())
}
func TestPRCheckout_detach(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
baseRepo, pr := stubPR("OWNER/REPO:master", "hubot/REPO:feature")
shared.StubFinderForRunCommandStyleTests(t, "123", pr, baseRepo)
cs, cmdTeardown := run.Stub()
defer cmdTeardown(t)
cs.Register(`git checkout --detach FETCH_HEAD`, 0, "")
cs.Register(`git fetch origin refs/pull/123/head --no-tags`, 0, "")
output, err := runCommand(http, nil, "", `123 --detach`, baseRepo)
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, "", output.Stderr())
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/checkout/checkout.go | pkg/cmd/pr/checkout/checkout.go | package checkout
import (
"context"
"fmt"
"net/http"
"strings"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
cliContext "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/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"
)
type CheckoutOptions struct {
HttpClient func() (*http.Client, error)
GitClient *git.Client
Config func() (gh.Config, error)
IO *iostreams.IOStreams
Remotes func() (cliContext.Remotes, error)
Branch func() (string, error)
PRResolver PRResolver
RecurseSubmodules bool
Force bool
Detach bool
BranchName string
}
func NewCmdCheckout(f *cmdutil.Factory, runF func(*CheckoutOptions) error) *cobra.Command {
opts := &CheckoutOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
GitClient: f.GitClient,
Config: f.Config,
Remotes: f.Remotes,
Branch: f.Branch,
}
cmd := &cobra.Command{
Use: "checkout [<number> | <url> | <branch>]",
Short: "Check out a pull request in git",
Example: heredoc.Doc(`
# Interactively select a PR from the 10 most recent to check out
$ gh pr checkout
# Checkout a specific PR
$ gh pr checkout 32
$ gh pr checkout https://github.com/OWNER/REPO/pull/32
$ gh pr checkout feature
`),
Args: cobra.MaximumNArgs(1),
Aliases: []string{"co"},
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) > 0 {
opts.PRResolver = &specificPRResolver{
prFinder: shared.NewFinder(f),
selector: args[0],
}
} else if opts.IO.CanPrompt() {
baseRepo, err := f.BaseRepo()
if err != nil {
return err
}
httpClient, err := f.HttpClient()
if err != nil {
return err
}
opts.PRResolver = &promptingPRResolver{
io: opts.IO,
prompter: f.Prompter,
prLister: shared.NewLister(httpClient),
baseRepo: baseRepo,
}
} else {
return cmdutil.FlagErrorf("pull request number, URL, or branch required when not running interactively")
}
if runF != nil {
return runF(opts)
}
return checkoutRun(opts)
},
}
cmd.Flags().BoolVarP(&opts.RecurseSubmodules, "recurse-submodules", "", false, "Update all submodules after checkout")
cmd.Flags().BoolVarP(&opts.Force, "force", "f", false, "Reset the existing local branch to the latest state of the pull request")
cmd.Flags().BoolVarP(&opts.Detach, "detach", "", false, "Checkout PR with a detached HEAD")
cmd.Flags().StringVarP(&opts.BranchName, "branch", "b", "", "Local branch name to use (default [the name of the head branch])")
return cmd
}
func checkoutRun(opts *CheckoutOptions) error {
pr, baseRepo, err := opts.PRResolver.Resolve()
if err != nil {
return err
}
cfg, err := opts.Config()
if err != nil {
return err
}
protocol := cfg.GitProtocol(baseRepo.RepoHost()).Value
remotes, err := opts.Remotes()
if err != nil {
return err
}
baseRemote, _ := remotes.FindByRepo(baseRepo.RepoOwner(), baseRepo.RepoName())
baseURLOrName := ghrepo.FormatRemoteURL(baseRepo, protocol)
if baseRemote != nil {
baseURLOrName = baseRemote.Name
}
headRemote := baseRemote
if pr.HeadRepository == nil {
headRemote = nil
} else if pr.IsCrossRepository {
headRemote, _ = remotes.FindByRepo(pr.HeadRepositoryOwner.Login, pr.HeadRepository.Name)
}
if strings.HasPrefix(pr.HeadRefName, "-") {
return fmt.Errorf("invalid branch name: %q", pr.HeadRefName)
}
var cmdQueue [][]string
if headRemote != nil {
cmdQueue = append(cmdQueue, cmdsForExistingRemote(headRemote, pr, opts)...)
} else {
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
apiClient := api.NewClientFromHTTP(httpClient)
defaultBranch, err := api.RepoDefaultBranch(apiClient, baseRepo)
if err != nil {
return err
}
cmdQueue = append(cmdQueue, cmdsForMissingRemote(pr, baseURLOrName, baseRepo.RepoHost(), defaultBranch, protocol, opts)...)
}
if opts.RecurseSubmodules {
cmdQueue = append(cmdQueue, []string{"submodule", "sync", "--recursive"})
cmdQueue = append(cmdQueue, []string{"submodule", "update", "--init", "--recursive"})
}
// Note that although we will probably be fetching from the head, in practice, PR checkout can only
// ever point to one host, and we know baseRepo must be populated.
err = executeCmds(opts.GitClient, git.CredentialPatternFromHost(baseRepo.RepoHost()), cmdQueue)
if err != nil {
return err
}
return nil
}
func cmdsForExistingRemote(remote *cliContext.Remote, pr *api.PullRequest, opts *CheckoutOptions) [][]string {
var cmds [][]string
remoteBranch := fmt.Sprintf("%s/%s", remote.Name, pr.HeadRefName)
refSpec := fmt.Sprintf("+refs/heads/%s", pr.HeadRefName)
if !opts.Detach {
refSpec += fmt.Sprintf(":refs/remotes/%s", remoteBranch)
}
cmds = append(cmds, []string{"fetch", remote.Name, refSpec, "--no-tags"})
localBranch := pr.HeadRefName
if opts.BranchName != "" {
localBranch = opts.BranchName
}
switch {
case opts.Detach:
cmds = append(cmds, []string{"checkout", "--detach", "FETCH_HEAD"})
case localBranchExists(opts.GitClient, localBranch):
cmds = append(cmds, []string{"checkout", localBranch})
if opts.Force {
cmds = append(cmds, []string{"reset", "--hard", fmt.Sprintf("refs/remotes/%s", remoteBranch)})
} else {
// TODO: check if non-fast-forward and suggest to use `--force`
cmds = append(cmds, []string{"merge", "--ff-only", fmt.Sprintf("refs/remotes/%s", remoteBranch)})
}
default:
cmds = append(cmds, []string{"checkout", "-b", localBranch, "--track", remoteBranch})
}
return cmds
}
func cmdsForMissingRemote(pr *api.PullRequest, baseURLOrName, repoHost, defaultBranch, protocol string, opts *CheckoutOptions) [][]string {
var cmds [][]string
ref := fmt.Sprintf("refs/pull/%d/head", pr.Number)
if opts.Detach {
cmds = append(cmds, []string{"fetch", baseURLOrName, ref, "--no-tags"})
cmds = append(cmds, []string{"checkout", "--detach", "FETCH_HEAD"})
return cmds
}
localBranch := pr.HeadRefName
if opts.BranchName != "" {
localBranch = opts.BranchName
} else if pr.HeadRefName == defaultBranch {
// avoid naming the new branch the same as the default branch
localBranch = fmt.Sprintf("%s/%s", pr.HeadRepositoryOwner.Login, localBranch)
}
currentBranch, _ := opts.Branch()
if localBranch == currentBranch {
// PR head matches currently checked out branch
cmds = append(cmds, []string{"fetch", baseURLOrName, ref, "--no-tags"})
if opts.Force {
cmds = append(cmds, []string{"reset", "--hard", "FETCH_HEAD"})
} else {
// TODO: check if non-fast-forward and suggest to use `--force`
cmds = append(cmds, []string{"merge", "--ff-only", "FETCH_HEAD"})
}
} else {
// TODO: check if non-fast-forward and suggest to use `--force`
fetchCmd := []string{"fetch", baseURLOrName, fmt.Sprintf("%s:%s", ref, localBranch), "--no-tags"}
if opts.Force {
fetchCmd = append(fetchCmd, "--force")
}
cmds = append(cmds, fetchCmd)
cmds = append(cmds, []string{"checkout", localBranch})
}
remote := baseURLOrName
mergeRef := ref
if pr.MaintainerCanModify && pr.HeadRepository != nil {
headRepo := ghrepo.NewWithHost(pr.HeadRepositoryOwner.Login, pr.HeadRepository.Name, repoHost)
remote = ghrepo.FormatRemoteURL(headRepo, protocol)
mergeRef = fmt.Sprintf("refs/heads/%s", pr.HeadRefName)
}
if missingMergeConfigForBranch(opts.GitClient, localBranch) {
// .remote is needed for `git pull` to work
// .pushRemote is needed for `git push` to work, if user has set `remote.pushDefault`.
// see https://git-scm.com/docs/git-config#Documentation/git-config.txt-branchltnamegtremote
cmds = append(cmds, []string{"config", fmt.Sprintf("branch.%s.remote", localBranch), remote})
cmds = append(cmds, []string{"config", fmt.Sprintf("branch.%s.pushRemote", localBranch), remote})
cmds = append(cmds, []string{"config", fmt.Sprintf("branch.%s.merge", localBranch), mergeRef})
}
return cmds
}
func missingMergeConfigForBranch(client *git.Client, b string) bool {
mc, err := client.Config(context.Background(), fmt.Sprintf("branch.%s.merge", b))
return err != nil || mc == ""
}
func localBranchExists(client *git.Client, b string) bool {
_, err := client.ShowRefs(context.Background(), []string{"refs/heads/" + b})
return err == nil
}
func executeCmds(client *git.Client, credentialPattern git.CredentialPattern, cmdQueue [][]string) error {
for _, args := range cmdQueue {
var err error
var cmd *git.Command
switch args[0] {
case "submodule":
cmd, err = client.AuthenticatedCommand(context.Background(), credentialPattern, args...)
case "fetch":
cmd, err = client.AuthenticatedCommand(context.Background(), git.AllMatchingCredentialsPattern, args...)
default:
cmd, err = client.Command(context.Background(), args...)
}
if err != nil {
return err
}
if err := cmd.Run(); err != nil {
return err
}
}
return nil
}
type PRResolver interface {
Resolve() (*api.PullRequest, ghrepo.Interface, error)
}
type specificPRResolver struct {
prFinder shared.PRFinder
selector string
}
func (r *specificPRResolver) Resolve() (*api.PullRequest, ghrepo.Interface, error) {
pr, baseRepo, err := r.prFinder.Find(shared.FindOptions{
Selector: r.selector,
Fields: []string{
"number",
"headRefName",
"headRepository",
"headRepositoryOwner",
"isCrossRepository",
"maintainerCanModify",
},
})
if err != nil {
return nil, nil, err
}
return pr, baseRepo, nil
}
type promptingPRResolver struct {
io *iostreams.IOStreams
prompter shared.Prompt
prLister shared.PRLister
baseRepo ghrepo.Interface
}
func (r *promptingPRResolver) Resolve() (*api.PullRequest, ghrepo.Interface, error) {
r.io.StartProgressIndicator()
listResult, err := r.prLister.List(shared.ListOptions{
BaseRepo: r.baseRepo,
State: "open",
Fields: []string{
"number",
"title",
"state",
"isDraft",
"headRefName",
"headRepository",
"headRepositoryOwner",
"isCrossRepository",
"maintainerCanModify",
},
LimitResults: 10})
r.io.StopProgressIndicator()
if err != nil {
return nil, nil, err
}
if len(listResult.PullRequests) == 0 {
return nil, nil, shared.ListNoResults(ghrepo.FullName(r.baseRepo), "pull request", false)
}
candidates := []string{}
for _, pr := range listResult.PullRequests {
candidates = append(candidates, fmt.Sprintf("%d\t%s %s [%s]",
pr.Number,
shared.PrStateWithDraft(&pr),
text.RemoveExcessiveWhitespace(pr.Title),
pr.HeadLabel(),
))
}
selected, err := r.prompter.Select("Select a pull request", "", candidates)
if err != nil {
return nil, nil, err
}
return &listResult.PullRequests[selected], r.baseRepo, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/view/view.go | pkg/cmd/pr/view/view.go | package view
import (
"fmt"
"sort"
"strconv"
"strings"
"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/cli/cli/v2/pkg/markdown"
"github.com/spf13/cobra"
)
type ViewOptions struct {
IO *iostreams.IOStreams
Browser browser.Browser
// TODO projectsV1Deprecation
// Remove this detector since it is only used for test validation.
Detector fd.Detector
Finder shared.PRFinder
Exporter cmdutil.Exporter
SelectorArg string
BrowserMode bool
Comments bool
Now func() time.Time
}
func NewCmdView(f *cmdutil.Factory, runF func(*ViewOptions) error) *cobra.Command {
opts := &ViewOptions{
IO: f.IOStreams,
Browser: f.Browser,
Now: time.Now,
}
cmd := &cobra.Command{
Use: "view [<number> | <url> | <branch>]",
Short: "View a pull request",
Long: heredoc.Docf(`
Display the title, body, and other information about a pull request.
Without an argument, the pull request that belongs to the current branch
is displayed.
With %[1]s--web%[1]s flag, open the pull request in a web browser instead.
`, "`"),
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]
}
if runF != nil {
return runF(opts)
}
return viewRun(opts)
},
}
cmd.Flags().BoolVarP(&opts.BrowserMode, "web", "w", false, "Open a pull request in the browser")
cmd.Flags().BoolVarP(&opts.Comments, "comments", "c", false, "View pull request comments")
cmdutil.AddJSONFlags(cmd, &opts.Exporter, api.PullRequestFields)
return cmd
}
var defaultFields = []string{
"url", "number", "title", "state", "body", "author", "autoMergeRequest",
"isDraft", "maintainerCanModify", "mergeable", "additions", "deletions", "commitsCount",
"baseRefName", "headRefName", "headRepositoryOwner", "headRepository", "isCrossRepository",
"reviewRequests", "reviews", "assignees", "labels", "projectCards", "projectItems", "milestone",
"comments", "reactionGroups", "createdAt", "statusCheckRollup",
}
func viewRun(opts *ViewOptions) error {
findOptions := shared.FindOptions{
Selector: opts.SelectorArg,
Fields: defaultFields,
Detector: opts.Detector,
}
if opts.BrowserMode {
findOptions.Fields = []string{"url"}
} else if opts.Exporter != nil {
findOptions.Fields = opts.Exporter.Fields()
}
pr, baseRepo, err := opts.Finder.Find(findOptions)
if err != nil {
return err
}
connectedToTerminal := opts.IO.IsStdoutTTY()
if opts.BrowserMode {
openURL := pr.URL
if connectedToTerminal {
fmt.Fprintf(opts.IO.ErrOut, "Opening %s in your browser.\n", text.DisplayURL(openURL))
}
return opts.Browser.Browse(openURL)
}
opts.IO.DetectTerminalTheme()
if err := opts.IO.StartPager(); err == nil {
defer opts.IO.StopPager()
} else {
fmt.Fprintf(opts.IO.ErrOut, "failed to start pager: %v\n", err)
}
if opts.Exporter != nil {
return opts.Exporter.Write(opts.IO, pr)
}
if connectedToTerminal {
return printHumanPrPreview(opts, baseRepo, pr)
}
if opts.Comments {
fmt.Fprint(opts.IO.Out, shared.RawCommentList(pr.Comments, pr.DisplayableReviews()))
return nil
}
return printRawPrPreview(opts.IO, pr)
}
func printRawPrPreview(io *iostreams.IOStreams, pr *api.PullRequest) error {
out := io.Out
cs := io.ColorScheme()
reviewers := prReviewerList(*pr, cs)
assignees := prAssigneeList(*pr)
labels := prLabelList(*pr, cs)
projects := prProjectList(*pr)
fmt.Fprintf(out, "title:\t%s\n", pr.Title)
fmt.Fprintf(out, "state:\t%s\n", prStateWithDraft(pr))
fmt.Fprintf(out, "author:\t%s\n", pr.Author.Login)
fmt.Fprintf(out, "labels:\t%s\n", labels)
fmt.Fprintf(out, "assignees:\t%s\n", assignees)
fmt.Fprintf(out, "reviewers:\t%s\n", reviewers)
fmt.Fprintf(out, "projects:\t%s\n", projects)
var milestoneTitle string
if pr.Milestone != nil {
milestoneTitle = pr.Milestone.Title
}
fmt.Fprintf(out, "milestone:\t%s\n", milestoneTitle)
fmt.Fprintf(out, "number:\t%d\n", pr.Number)
fmt.Fprintf(out, "url:\t%s\n", pr.URL)
fmt.Fprintf(out, "additions:\t%s\n", cs.Green(strconv.Itoa(pr.Additions)))
fmt.Fprintf(out, "deletions:\t%s\n", cs.Red(strconv.Itoa(pr.Deletions)))
var autoMerge string
if pr.AutoMergeRequest == nil {
autoMerge = "disabled"
} else {
autoMerge = fmt.Sprintf("enabled\t%s\t%s",
pr.AutoMergeRequest.EnabledBy.Login,
strings.ToLower(pr.AutoMergeRequest.MergeMethod))
}
fmt.Fprintf(out, "auto-merge:\t%s\n", autoMerge)
fmt.Fprintln(out, "--")
fmt.Fprintln(out, pr.Body)
return nil
}
func printHumanPrPreview(opts *ViewOptions, baseRepo ghrepo.Interface, pr *api.PullRequest) error {
out := opts.IO.Out
cs := opts.IO.ColorScheme()
// Header (Title and State)
fmt.Fprintf(out, "%s %s#%d\n", cs.Bold(pr.Title), ghrepo.FullName(baseRepo), pr.Number)
fmt.Fprintf(out,
"%s • %s wants to merge %s into %s from %s • %s\n",
shared.StateTitleWithColor(cs, *pr),
pr.Author.Login,
text.Pluralize(pr.Commits.TotalCount, "commit"),
pr.BaseRefName,
pr.HeadRefName,
text.FuzzyAgo(opts.Now(), pr.CreatedAt),
)
// added/removed
fmt.Fprintf(out,
"%s %s",
cs.Green("+"+strconv.Itoa(pr.Additions)),
cs.Red("-"+strconv.Itoa(pr.Deletions)),
)
// checks
checks := pr.ChecksStatus()
if summary := shared.PrCheckStatusSummaryWithColor(cs, checks); summary != "" {
fmt.Fprintf(out, " • %s\n", summary)
} else {
fmt.Fprintln(out)
}
// Reactions
if reactions := shared.ReactionGroupList(pr.ReactionGroups); reactions != "" {
fmt.Fprint(out, reactions)
fmt.Fprintln(out)
}
// Metadata
if reviewers := prReviewerList(*pr, cs); reviewers != "" {
fmt.Fprint(out, cs.Bold("Reviewers: "))
fmt.Fprintln(out, reviewers)
}
if assignees := prAssigneeList(*pr); assignees != "" {
fmt.Fprint(out, cs.Bold("Assignees: "))
fmt.Fprintln(out, assignees)
}
if labels := prLabelList(*pr, cs); labels != "" {
fmt.Fprint(out, cs.Bold("Labels: "))
fmt.Fprintln(out, labels)
}
if projects := prProjectList(*pr); projects != "" {
fmt.Fprint(out, cs.Bold("Projects: "))
fmt.Fprintln(out, projects)
}
if pr.Milestone != nil {
fmt.Fprint(out, cs.Bold("Milestone: "))
fmt.Fprintln(out, pr.Milestone.Title)
}
// Auto-Merge status
autoMerge := pr.AutoMergeRequest
if autoMerge != nil {
var mergeMethod string
switch autoMerge.MergeMethod {
case "MERGE":
mergeMethod = "a merge commit"
case "REBASE":
mergeMethod = "rebase and merge"
case "SQUASH":
mergeMethod = "squash and merge"
default:
mergeMethod = fmt.Sprintf("an unknown merge method (%s)", autoMerge.MergeMethod)
}
fmt.Fprintf(out,
"%s %s by %s, using %s\n",
cs.Bold("Auto-merge:"),
cs.Green("enabled"),
autoMerge.EnabledBy.Login,
mergeMethod,
)
}
// Body
var md string
var err error
if pr.Body == "" {
md = fmt.Sprintf("\n %s\n\n", cs.Muted("No description provided"))
} else {
md, err = markdown.Render(pr.Body,
markdown.WithTheme(opts.IO.TerminalTheme()),
markdown.WithWrap(opts.IO.TerminalWidth()))
if err != nil {
return err
}
}
fmt.Fprintf(out, "\n%s\n", md)
// Reviews and Comments
if pr.Comments.TotalCount > 0 || pr.Reviews.TotalCount > 0 {
preview := !opts.Comments
comments, err := shared.CommentList(opts.IO, pr.Comments, pr.DisplayableReviews(), preview)
if err != nil {
return err
}
fmt.Fprint(out, comments)
}
// Footer
fmt.Fprintf(out, cs.Muted("View this pull request on GitHub: %s\n"), pr.URL)
return nil
}
const (
requestedReviewState = "REQUESTED" // This is our own state for review request
approvedReviewState = "APPROVED"
changesRequestedReviewState = "CHANGES_REQUESTED"
commentedReviewState = "COMMENTED"
dismissedReviewState = "DISMISSED"
pendingReviewState = "PENDING"
)
type reviewerState struct {
Name string
State string
}
// formattedReviewerState formats a reviewerState with state color
func formattedReviewerState(cs *iostreams.ColorScheme, reviewer *reviewerState) string {
var displayState string
switch reviewer.State {
case requestedReviewState:
displayState = cs.Yellow("Requested")
case approvedReviewState:
displayState = cs.Green("Approved")
case changesRequestedReviewState:
displayState = cs.Red("Changes requested")
case commentedReviewState, dismissedReviewState:
// Show "DISMISSED" review as "COMMENTED", since "dismissed" only makes
// sense when displayed in an events timeline but not in the final tally.
displayState = "Commented"
default:
displayState = text.Title(reviewer.State)
}
return fmt.Sprintf("%s (%s)", reviewer.Name, displayState)
}
// prReviewerList generates a reviewer list with their last state
func prReviewerList(pr api.PullRequest, cs *iostreams.ColorScheme) string {
reviewerStates := parseReviewers(pr)
reviewers := make([]string, 0, len(reviewerStates))
sortReviewerStates(reviewerStates)
for _, reviewer := range reviewerStates {
reviewers = append(reviewers, formattedReviewerState(cs, reviewer))
}
reviewerList := strings.Join(reviewers, ", ")
return reviewerList
}
const ghostName = "ghost"
// parseReviewers parses given Reviews and ReviewRequests
func parseReviewers(pr api.PullRequest) []*reviewerState {
reviewerStates := make(map[string]*reviewerState)
for _, review := range pr.Reviews.Nodes {
if review.Author.Login != pr.Author.Login {
name := review.Author.Login
if name == "" {
name = ghostName
}
reviewerStates[name] = &reviewerState{
Name: name,
State: review.State,
}
}
}
// Overwrite reviewer's state if a review request for the same reviewer exists.
for _, reviewRequest := range pr.ReviewRequests.Nodes {
name := reviewRequest.RequestedReviewer.LoginOrSlug()
reviewerStates[name] = &reviewerState{
Name: name,
State: requestedReviewState,
}
}
// Convert map to slice for ease of sort
result := make([]*reviewerState, 0, len(reviewerStates))
for _, reviewer := range reviewerStates {
if reviewer.State == pendingReviewState {
continue
}
result = append(result, reviewer)
}
return result
}
// sortReviewerStates puts completed reviews before review requests and sorts names alphabetically
func sortReviewerStates(reviewerStates []*reviewerState) {
sort.Slice(reviewerStates, func(i, j int) bool {
if reviewerStates[i].State == requestedReviewState &&
reviewerStates[j].State != requestedReviewState {
return false
}
if reviewerStates[j].State == requestedReviewState &&
reviewerStates[i].State != requestedReviewState {
return true
}
return reviewerStates[i].Name < reviewerStates[j].Name
})
}
func prAssigneeList(pr api.PullRequest) string {
if len(pr.Assignees.Nodes) == 0 {
return ""
}
AssigneeNames := make([]string, 0, len(pr.Assignees.Nodes))
for _, assignee := range pr.Assignees.Nodes {
AssigneeNames = append(AssigneeNames, assignee.Login)
}
list := strings.Join(AssigneeNames, ", ")
if pr.Assignees.TotalCount > len(pr.Assignees.Nodes) {
list += ", …"
}
return list
}
func prLabelList(pr api.PullRequest, cs *iostreams.ColorScheme) string {
if len(pr.Labels.Nodes) == 0 {
return ""
}
// ignore case sort
sort.SliceStable(pr.Labels.Nodes, func(i, j int) bool {
return strings.ToLower(pr.Labels.Nodes[i].Name) < strings.ToLower(pr.Labels.Nodes[j].Name)
})
labelNames := make([]string, 0, len(pr.Labels.Nodes))
for _, label := range pr.Labels.Nodes {
labelNames = append(labelNames, cs.Label(label.Color, label.Name))
}
list := strings.Join(labelNames, ", ")
if pr.Labels.TotalCount > len(pr.Labels.Nodes) {
list += ", …"
}
return list
}
func prProjectList(pr api.PullRequest) string {
totalCount := pr.ProjectCards.TotalCount + pr.ProjectItems.TotalCount
count := len(pr.ProjectCards.Nodes) + len(pr.ProjectItems.Nodes)
if count == 0 {
return ""
}
projectNames := make([]string, 0, len(pr.ProjectCards.Nodes))
for _, project := range pr.ProjectItems.Nodes {
colName := project.Status.Name
if colName == "" {
colName = "No Status"
}
projectNames = append(projectNames, fmt.Sprintf("%s (%s)", project.Project.Title, colName))
}
for _, project := range pr.ProjectCards.Nodes {
if project == nil {
continue
}
colName := project.Column.Name
if colName == "" {
colName = "Awaiting triage"
}
projectNames = append(projectNames, fmt.Sprintf("%s (%s)", project.Project.Name, colName))
}
list := strings.Join(projectNames, ", ")
if totalCount > count {
list += ", …"
}
return list
}
func prStateWithDraft(pr *api.PullRequest) string {
if pr.IsDraft && pr.State == "OPEN" {
return "DRAFT"
}
return pr.State
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/view/view_test.go | pkg/cmd/pr/view/view_test.go | package view
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"regexp"
"testing"
"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/cli/cli/v2/pkg/jsonfieldstest"
"github.com/cli/cli/v2/test"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestJSONFields(t *testing.T) {
jsonfieldstest.ExpectCommandToSupportJSONFields(t, NewCmdView, []string{
"additions",
"assignees",
"author",
"autoMergeRequest",
"baseRefName",
"baseRefOid",
"body",
"changedFiles",
"closed",
"closedAt",
"closingIssuesReferences",
"comments",
"commits",
"createdAt",
"deletions",
"files",
"fullDatabaseId",
"headRefName",
"headRefOid",
"headRepository",
"headRepositoryOwner",
"id",
"isCrossRepository",
"isDraft",
"labels",
"latestReviews",
"maintainerCanModify",
"mergeCommit",
"mergeStateStatus",
"mergeable",
"mergedAt",
"mergedBy",
"milestone",
"number",
"potentialMergeCommit",
"projectCards",
"projectItems",
"reactionGroups",
"reviewDecision",
"reviewRequests",
"reviews",
"state",
"statusCheckRollup",
"title",
"updatedAt",
"url",
})
}
func Test_NewCmdView(t *testing.T) {
tests := []struct {
name string
args string
isTTY bool
want ViewOptions
wantErr string
}{
{
name: "number argument",
args: "123",
isTTY: true,
want: ViewOptions{
SelectorArg: "123",
BrowserMode: false,
},
},
{
name: "no argument",
args: "",
isTTY: true,
want: ViewOptions{
SelectorArg: "",
BrowserMode: false,
},
},
{
name: "web mode",
args: "123 -w",
isTTY: true,
want: ViewOptions{
SelectorArg: "123",
BrowserMode: true,
},
},
{
name: "no argument with --repo override",
args: "-R owner/repo",
isTTY: true,
wantErr: "argument required when using the --repo flag",
},
{
name: "comments",
args: "123 -c",
isTTY: true,
want: ViewOptions{
SelectorArg: "123",
Comments: true,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
ios.SetStdoutTTY(tt.isTTY)
ios.SetStdinTTY(tt.isTTY)
ios.SetStderrTTY(tt.isTTY)
f := &cmdutil.Factory{
IOStreams: ios,
}
var opts *ViewOptions
cmd := NewCmdView(f, func(o *ViewOptions) 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)
})
}
}
func runCommand(rt http.RoundTripper, branch string, isTTY bool, cli string) (*test.CmdOut, error) {
ios, _, stdout, stderr := iostreams.Test()
ios.SetStdoutTTY(isTTY)
ios.SetStdinTTY(isTTY)
ios.SetStderrTTY(isTTY)
browser := &browser.Stub{}
factory := &cmdutil.Factory{
IOStreams: ios,
Browser: browser,
HttpClient: func() (*http.Client, error) {
return &http.Client{Transport: rt}, nil
},
}
cmd := NewCmdView(factory, nil)
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,
BrowsedURL: browser.BrowsedURL(),
}, err
}
// hack for compatibility with old JSON fixture files
func prFromFixtures(fixtures map[string]string) (*api.PullRequest, error) {
var response struct {
Data struct {
Repository struct {
PullRequest *api.PullRequest
}
}
}
ff, err := os.Open(fixtures["PullRequestByNumber"])
if err != nil {
return nil, err
}
defer ff.Close()
dec := json.NewDecoder(ff)
err = dec.Decode(&response)
if err != nil {
return nil, err
}
for name := range fixtures {
switch name {
case "PullRequestByNumber":
case "ReviewsForPullRequest", "CommentsForPullRequest":
ff, err := os.Open(fixtures[name])
if err != nil {
return nil, err
}
defer ff.Close()
dec := json.NewDecoder(ff)
err = dec.Decode(&response)
if err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("unrecognized fixture type: %q", name)
}
}
return response.Data.Repository.PullRequest, nil
}
func TestPRView_Preview_nontty(t *testing.T) {
tests := map[string]struct {
branch string
args string
fixtures map[string]string
expectedOutputs []string
}{
"Open PR without metadata": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreview.json",
},
expectedOutputs: []string{
`title:\tBlueberries are from a fork\n`,
`state:\tOPEN\n`,
`author:\tnobody\n`,
`labels:\t\n`,
`assignees:\t\n`,
`reviewers:\t\n`,
`projects:\t\n`,
`milestone:\t\n`,
`url:\thttps://github.com/OWNER/REPO/pull/12\n`,
`additions:\t100\n`,
`deletions:\t10\n`,
`number:\t12\n`,
`blueberries taste good`,
},
},
"Open PR with metadata by number": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewWithMetadataByNumber.json",
},
expectedOutputs: []string{
`title:\tBlueberries are from a fork\n`,
`reviewers:\t1 \(Requested\)\n`,
`assignees:\tmarseilles, monaco\n`,
`labels:\tClosed: Duplicate, Closed: Won't Fix, help wanted, Status: In Progress, Type: Bug\n`,
`projects:\tv2 Project 1 \(No Status\), v2 Project 2 \(Done\), Project 1 \(column A\), Project 2 \(column B\), Project 3 \(column C\), Project 4 \(Awaiting triage\)\n`,
`milestone:\tuluru\n`,
`\*\*blueberries taste good\*\*`,
},
},
"Open PR with reviewers by number": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewWithReviewersByNumber.json",
"ReviewsForPullRequest": "./fixtures/prViewPreviewManyReviews.json",
},
expectedOutputs: []string{
`title:\tBlueberries are from a fork\n`,
`state:\tOPEN\n`,
`author:\tnobody\n`,
`labels:\t\n`,
`assignees:\t\n`,
`projects:\t\n`,
`milestone:\t\n`,
`additions:\t100\n`,
`deletions:\t10\n`,
`reviewers:\tDEF \(Commented\), def \(Changes requested\), ghost \(Approved\), hubot \(Commented\), xyz \(Approved\), 123 \(Requested\), abc \(Requested\), my-org\/team-1 \(Requested\)\n`,
`\*\*blueberries taste good\*\*`,
},
},
"Closed PR": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewClosedState.json",
},
expectedOutputs: []string{
`state:\tCLOSED\n`,
`author:\tnobody\n`,
`labels:\t\n`,
`assignees:\t\n`,
`reviewers:\t\n`,
`projects:\t\n`,
`milestone:\t\n`,
`additions:\t100\n`,
`deletions:\t10\n`,
`\*\*blueberries taste good\*\*`,
},
},
"Merged PR": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewMergedState.json",
},
expectedOutputs: []string{
`state:\tMERGED\n`,
`author:\tnobody\n`,
`labels:\t\n`,
`assignees:\t\n`,
`reviewers:\t\n`,
`projects:\t\n`,
`milestone:\t\n`,
`additions:\t100\n`,
`deletions:\t10\n`,
`\*\*blueberries taste good\*\*`,
},
},
"Draft PR": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewDraftState.json",
},
expectedOutputs: []string{
`title:\tBlueberries are from a fork\n`,
`state:\tDRAFT\n`,
`author:\tnobody\n`,
`labels:`,
`assignees:`,
`reviewers:`,
`projects:`,
`milestone:`,
`additions:\t100\n`,
`deletions:\t10\n`,
`\*\*blueberries taste good\*\*`,
},
},
"PR with auto-merge enabled": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewWithAutoMergeEnabled.json",
},
expectedOutputs: []string{
`title:\tBlueberries are from a fork\n`,
`state:\tOPEN\n`,
`author:\tnobody\n`,
`labels:\t\n`,
`assignees:\t\n`,
`projects:\t\n`,
`milestone:\t\n`,
`additions:\t100\n`,
`deletions:\t10\n`,
`auto-merge:\tenabled\thubot\tsquash\n`,
},
},
"PR with nil project": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewWithNilProject.json",
},
expectedOutputs: []string{
`projects:\t\n`,
},
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
pr, err := prFromFixtures(tc.fixtures)
require.NoError(t, err)
shared.StubFinderForRunCommandStyleTests(t, "12", pr, ghrepo.New("OWNER", "REPO"))
output, err := runCommand(http, tc.branch, false, tc.args)
if err != nil {
t.Errorf("error running command `%v`: %v", tc.args, err)
}
assert.Equal(t, "", output.Stderr())
//nolint:staticcheck // prefer exact matchers over ExpectLines
test.ExpectLines(t, output.String(), tc.expectedOutputs...)
})
}
}
func TestPRView_Preview(t *testing.T) {
tests := map[string]struct {
branch string
args string
fixtures map[string]string
expectedOutputs []string
}{
"Open PR without metadata": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreview.json",
},
expectedOutputs: []string{
`Blueberries are from a fork OWNER/REPO#12`,
`Open.*nobody wants to merge 12 commits into master from blueberries . about X years ago`,
`.+100.-10`,
`blueberries taste good`,
`View this pull request on GitHub: https://github.com/OWNER/REPO/pull/12`,
},
},
"Open PR with metadata by number": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewWithMetadataByNumber.json",
},
expectedOutputs: []string{
`Blueberries are from a fork OWNER/REPO#12`,
`Open.*nobody wants to merge 12 commits into master from blueberries . about X years ago`,
`.+100.-10`,
`Reviewers:.*1 \(.*Requested.*\)\n`,
`Assignees:.*marseilles, monaco\n`,
`Labels:.*Closed: Duplicate, Closed: Won't Fix, help wanted, Status: In Progress, Type: Bug\n`,
`Projects:.*v2 Project 1 \(No Status\), v2 Project 2 \(Done\), Project 1 \(column A\), Project 2 \(column B\), Project 3 \(column C\), Project 4 \(Awaiting triage\)\n`,
`Milestone:.*uluru\n`,
`blueberries taste good`,
`View this pull request on GitHub: https://github.com/OWNER/REPO/pull/12`,
},
},
"Open PR with reviewers by number": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewWithReviewersByNumber.json",
"ReviewsForPullRequest": "./fixtures/prViewPreviewManyReviews.json",
},
expectedOutputs: []string{
`Blueberries are from a fork OWNER/REPO#12`,
`Reviewers: DEF \(Commented\), def \(Changes requested\), ghost \(Approved\), hubot \(Commented\), xyz \(Approved\), 123 \(Requested\), abc \(Requested\), my-org\/team-1 \(Requested\)`,
`blueberries taste good`,
`View this pull request on GitHub: https://github.com/OWNER/REPO/pull/12`,
},
},
"Closed PR": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewClosedState.json",
},
expectedOutputs: []string{
`Blueberries are from a fork OWNER/REPO#12`,
`Closed.*nobody wants to merge 12 commits into master from blueberries . about X years ago`,
`.+100.-10`,
`blueberries taste good`,
`View this pull request on GitHub: https://github.com/OWNER/REPO/pull/12`,
},
},
"Merged PR": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewMergedState.json",
},
expectedOutputs: []string{
`Blueberries are from a fork OWNER/REPO#12`,
`Merged.*nobody wants to merge 12 commits into master from blueberries . about X years ago`,
`.+100.-10`,
`blueberries taste good`,
`View this pull request on GitHub: https://github.com/OWNER/REPO/pull/12`,
},
},
"Draft PR": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewDraftState.json",
},
expectedOutputs: []string{
`Blueberries are from a fork OWNER/REPO#12`,
`Draft.*nobody wants to merge 12 commits into master from blueberries . about X years ago`,
`.+100.-10`,
`blueberries taste good`,
`View this pull request on GitHub: https://github.com/OWNER/REPO/pull/12`,
},
},
"Open PR with all checks passing": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewWithAllChecksPassing.json",
},
expectedOutputs: []string{
`Blueberries are from a fork OWNER/REPO#12`,
`Open.*nobody wants to merge 12 commits into master from blueberries . about X years ago`,
`.+100.-10 • ✓ Checks passing`,
`blueberries taste good`,
`View this pull request on GitHub: https://github.com/OWNER/REPO/pull/12`,
},
},
"Open PR with all checks failing": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewWithAllChecksFailing.json",
},
expectedOutputs: []string{
`Blueberries are from a fork OWNER/REPO#12`,
`Open.*nobody wants to merge 12 commits into master from blueberries . about X years ago`,
`.+100.-10 • × All checks failing`,
`blueberries taste good`,
`View this pull request on GitHub: https://github.com/OWNER/REPO/pull/12`,
},
},
"Open PR with some checks failing": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewWithSomeChecksFailing.json",
},
expectedOutputs: []string{
`Blueberries are from a fork OWNER/REPO#12`,
`Open.*nobody wants to merge 12 commits into master from blueberries . about X years ago`,
`.+100.-10 • × 1/2 checks failing`,
`blueberries taste good`,
`View this pull request on GitHub: https://github.com/OWNER/REPO/pull/12`,
},
},
"Open PR with some checks pending": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewWithSomeChecksPending.json",
},
expectedOutputs: []string{
`Blueberries are from a fork OWNER/REPO#12`,
`Open.*nobody wants to merge 12 commits into master from blueberries . about X years ago`,
`.+100.-10 • - Checks pending`,
`blueberries taste good`,
`View this pull request on GitHub: https://github.com/OWNER/REPO/pull/12`,
},
},
"Open PR with no checks": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewWithNoChecks.json",
},
expectedOutputs: []string{
`Blueberries are from a fork OWNER/REPO#12`,
`Open.*nobody wants to merge 12 commits into master from blueberries . about X years ago`,
`.+100.-10 • No checks`,
`blueberries taste good`,
`View this pull request on GitHub: https://github.com/OWNER/REPO/pull/12`,
},
},
"PR with auto-merge enabled": {
branch: "master",
args: "12",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewWithAutoMergeEnabled.json",
},
expectedOutputs: []string{
`Blueberries are from a fork OWNER/REPO#12\n`,
`Open.*nobody wants to merge 12 commits into master from blueberries . about X years ago`,
`Auto-merge:.*enabled.* by hubot, using squash and merge`,
`blueberries taste good`,
`View this pull request on GitHub: https://github.com/OWNER/REPO/pull/12`,
},
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
pr, err := prFromFixtures(tc.fixtures)
require.NoError(t, err)
shared.StubFinderForRunCommandStyleTests(t, "12", pr, ghrepo.New("OWNER", "REPO"))
output, err := runCommand(http, tc.branch, true, tc.args)
if err != nil {
t.Errorf("error running command `%v`: %v", tc.args, err)
}
assert.Equal(t, "", output.Stderr())
out := output.String()
timeRE := regexp.MustCompile(`\d+ years`)
out = timeRE.ReplaceAllString(out, "X years")
//nolint:staticcheck // prefer exact matchers over ExpectLines
test.ExpectLines(t, out, tc.expectedOutputs...)
})
}
}
func TestPRView_web_currentBranch(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t, "", &api.PullRequest{URL: "https://github.com/OWNER/REPO/pull/10"}, ghrepo.New("OWNER", "REPO"))
_, cmdTeardown := run.Stub()
defer cmdTeardown(t)
output, err := runCommand(http, "blueberries", true, "-w")
if err != nil {
t.Errorf("error running command `pr view`: %v", err)
}
assert.Equal(t, "", output.String())
assert.Equal(t, "Opening https://github.com/OWNER/REPO/pull/10 in your browser.\n", output.Stderr())
assert.Equal(t, "https://github.com/OWNER/REPO/pull/10", output.BrowsedURL)
}
func TestPRView_web_noResultsForBranch(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t, "", nil, nil)
_, cmdTeardown := run.Stub()
defer cmdTeardown(t)
_, err := runCommand(http, "blueberries", true, "-w")
if err == nil || err.Error() != `no pull requests found` {
t.Errorf("error running command `pr view`: %v", err)
}
}
func TestPRView_tty_Comments(t *testing.T) {
tests := map[string]struct {
branch string
cli string
fixtures map[string]string
expectedOutputs []string
wantsErr bool
}{
"without comments flag": {
branch: "master",
cli: "123",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewSingleComment.json",
"ReviewsForPullRequest": "./fixtures/prViewPreviewReviews.json",
},
expectedOutputs: []string{
`some title OWNER/REPO#12`,
`1 \x{1f615} • 2 \x{1f440} • 3 \x{2764}\x{fe0f}`,
`some body`,
`———————— Not showing 9 comments ————————`,
`marseilles \(Collaborator\) • Jan 9, 2020 • Newest comment`,
`4 \x{1f389} • 5 \x{1f604} • 6 \x{1f680}`,
`Comment 5`,
`Use --comments to view the full conversation`,
`View this pull request on GitHub: https://github.com/OWNER/REPO/pull/12`,
},
},
"with comments flag": {
branch: "master",
cli: "123 --comments",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewSingleComment.json",
"ReviewsForPullRequest": "./fixtures/prViewPreviewReviews.json",
"CommentsForPullRequest": "./fixtures/prViewPreviewFullComments.json",
},
expectedOutputs: []string{
`some title OWNER/REPO#12`,
`some body`,
`monalisa • Jan 1, 2020 • Edited`,
`1 \x{1f615} • 2 \x{1f440} • 3 \x{2764}\x{fe0f} • 4 \x{1f389} • 5 \x{1f604} • 6 \x{1f680} • 7 \x{1f44e} • 8 \x{1f44d}`,
`Comment 1`,
`sam commented • Jan 2, 2020`,
`1 \x{1f44e} • 1 \x{1f44d}`,
`Review 1`,
`View the full review: https://github.com/OWNER/REPO/pull/12#pullrequestreview-1`,
`johnnytest \(Contributor\) • Jan 3, 2020`,
`Comment 2`,
`matt requested changes \(Owner\) • Jan 4, 2020`,
`1 \x{1f615} • 1 \x{1f440}`,
`Review 2`,
`View the full review: https://github.com/OWNER/REPO/pull/12#pullrequestreview-2`,
`elvisp \(Member\) • Jan 5, 2020`,
`Comment 3`,
`leah approved \(Member\) • Jan 6, 2020 • Edited`,
`Review 3`,
`View the full review: https://github.com/OWNER/REPO/pull/12#pullrequestreview-3`,
`loislane \(Owner\) • Jan 7, 2020`,
`Comment 4`,
`louise dismissed • Jan 8, 2020`,
`Review 4`,
`View the full review: https://github.com/OWNER/REPO/pull/12#pullrequestreview-4`,
`sam-spam • This comment has been marked as spam`,
`marseilles \(Collaborator\) • Jan 9, 2020 • Newest comment`,
`Comment 5`,
`View this pull request on GitHub: https://github.com/OWNER/REPO/pull/12`,
},
},
"with invalid comments flag": {
branch: "master",
cli: "123 --comments 3",
wantsErr: true,
},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
if len(tt.fixtures) > 0 {
pr, err := prFromFixtures(tt.fixtures)
require.NoError(t, err)
shared.StubFinderForRunCommandStyleTests(t, "123", pr, ghrepo.New("OWNER", "REPO"))
} else {
shared.StubFinderForRunCommandStyleTests(t, "123", nil, nil)
}
output, err := runCommand(http, tt.branch, true, tt.cli)
if tt.wantsErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
assert.Equal(t, "", output.Stderr())
//nolint:staticcheck // prefer exact matchers over ExpectLines
test.ExpectLines(t, output.String(), tt.expectedOutputs...)
})
}
}
func TestPRView_nontty_Comments(t *testing.T) {
tests := map[string]struct {
branch string
cli string
fixtures map[string]string
expectedOutputs []string
wantsErr bool
}{
"without comments flag": {
branch: "master",
cli: "123",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewSingleComment.json",
"ReviewsForPullRequest": "./fixtures/prViewPreviewReviews.json",
},
expectedOutputs: []string{
`title:\tsome title`,
`state:\tOPEN`,
`author:\tnobody`,
`url:\thttps://github.com/OWNER/REPO/pull/12`,
`some body`,
},
},
"with comments flag": {
branch: "master",
cli: "123 --comments",
fixtures: map[string]string{
"PullRequestByNumber": "./fixtures/prViewPreviewSingleComment.json",
"ReviewsForPullRequest": "./fixtures/prViewPreviewReviews.json",
"CommentsForPullRequest": "./fixtures/prViewPreviewFullComments.json",
},
expectedOutputs: []string{
`author:\tmonalisa`,
`association:\tnone`,
`edited:\ttrue`,
`status:\tnone`,
`Comment 1`,
`author:\tsam`,
`association:\tnone`,
`edited:\tfalse`,
`status:\tcommented`,
`Review 1`,
`author:\tjohnnytest`,
`association:\tcontributor`,
`edited:\tfalse`,
`status:\tnone`,
`Comment 2`,
`author:\tmatt`,
`association:\towner`,
`edited:\tfalse`,
`status:\tchanges requested`,
`Review 2`,
`author:\telvisp`,
`association:\tmember`,
`edited:\tfalse`,
`status:\tnone`,
`Comment 3`,
`author:\tleah`,
`association:\tmember`,
`edited:\ttrue`,
`status:\tapproved`,
`Review 3`,
`author:\tloislane`,
`association:\towner`,
`edited:\tfalse`,
`status:\tnone`,
`Comment 4`,
`author:\tlouise`,
`association:\tnone`,
`edited:\tfalse`,
`status:\tdismissed`,
`Review 4`,
`author:\tmarseilles`,
`association:\tcollaborator`,
`edited:\tfalse`,
`status:\tnone`,
`Comment 5`,
},
},
"with invalid comments flag": {
branch: "master",
cli: "123 --comments 3",
wantsErr: true,
},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
if len(tt.fixtures) > 0 {
pr, err := prFromFixtures(tt.fixtures)
require.NoError(t, err)
shared.StubFinderForRunCommandStyleTests(t, "123", pr, ghrepo.New("OWNER", "REPO"))
} else {
shared.StubFinderForRunCommandStyleTests(t, "123", nil, nil)
}
output, err := runCommand(http, tt.branch, false, tt.cli)
if tt.wantsErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
assert.Equal(t, "", output.Stderr())
//nolint:staticcheck // prefer exact matchers over ExpectLines
test.ExpectLines(t, output.String(), tt.expectedOutputs...)
})
}
}
// TODO projectsV1Deprecation
// Remove this test.
func TestProjectsV1Deprecation(t *testing.T) {
t.Run("when projects v1 is supported, is included in query", func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
reg := &httpmock.Registry{}
reg.Register(
httpmock.GraphQL(`projectCards`),
// Simulate a GraphQL error to early exit the test.
httpmock.StatusStringResponse(500, ""),
)
f := &cmdutil.Factory{
IOStreams: ios,
HttpClient: func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
},
}
_, cmdTeardown := run.Stub()
defer cmdTeardown(t)
// Ignore the error because we have no way to really stub it without
// fully stubbing a GQL error structure in the request body.
_ = viewRun(&ViewOptions{
IO: ios,
Finder: shared.NewFinder(f),
Detector: &fd.EnabledDetectorMock{},
SelectorArg: "https://github.com/cli/cli/pull/123",
})
// Verify that our request contained projectCards
reg.Verify(t)
})
t.Run("when projects v1 is not supported, is not included in query", func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
reg := &httpmock.Registry{}
reg.Exclude(
t,
httpmock.GraphQL(`projectCards`),
)
f := &cmdutil.Factory{
IOStreams: ios,
HttpClient: func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
},
}
_, cmdTeardown := run.Stub()
defer cmdTeardown(t)
// Ignore the error because we have no way to really stub it without
// fully stubbing a GQL error structure in the request body.
_ = viewRun(&ViewOptions{
IO: ios,
Finder: shared.NewFinder(f),
Detector: &fd.DisabledDetectorMock{},
SelectorArg: "https://github.com/cli/cli/pull/123",
})
// Verify that our request contained projectCards
reg.Verify(t)
})
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/review/review_test.go | pkg/cmd/pr/review/review_test.go | package review
import (
"bytes"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/config"
"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/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 Test_NewCmdReview(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 ReviewOptions
wantErr string
}{
{
name: "number argument",
args: "123",
isTTY: true,
want: ReviewOptions{
SelectorArg: "123",
ReviewType: 0,
Body: "",
},
},
{
name: "no argument",
args: "",
isTTY: true,
want: ReviewOptions{
SelectorArg: "",
ReviewType: 0,
Body: "",
},
},
{
name: "body from stdin",
args: "123 --request-changes --body-file -",
stdin: "this is on standard input",
isTTY: true,
want: ReviewOptions{
SelectorArg: "123",
ReviewType: 1,
Body: "this is on standard input",
},
},
{
name: "body from file",
args: fmt.Sprintf("123 --request-changes --body-file '%s'", tmpFile),
isTTY: true,
want: ReviewOptions{
SelectorArg: "123",
ReviewType: 1,
Body: "a body from file",
},
},
{
name: "no argument with --repo override",
args: "-R owner/repo",
isTTY: true,
wantErr: "argument required when using the --repo flag",
},
{
name: "no arguments in non-interactive mode",
args: "",
isTTY: false,
wantErr: "--approve, --request-changes, or --comment required when not running interactively",
},
{
name: "mutually exclusive review types",
args: `--approve --comment -b hello`,
isTTY: true,
wantErr: "need exactly one of --approve, --request-changes, or --comment",
},
{
name: "comment without body",
args: `--comment`,
isTTY: true,
wantErr: "body cannot be blank for comment review",
},
{
name: "request changes without body",
args: `--request-changes`,
isTTY: true,
wantErr: "body cannot be blank for request-changes review",
},
{
name: "only body argument",
args: `-b hello`,
isTTY: true,
wantErr: "--body unsupported without --approve, --request-changes, or --comment",
},
{
name: "body and body-file flags",
args: "--body 'test' --body-file 'test-file.txt'",
isTTY: true,
wantErr: "specify only one of `--body` or `--body-file`",
},
}
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 *ReviewOptions
cmd := NewCmdReview(f, func(o *ReviewOptions) 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.Body, opts.Body)
})
}
}
func runCommand(rt http.RoundTripper, prompter prompter.Prompter, 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
},
Config: func() (gh.Config, error) {
return config.NewBlankConfig(), nil
},
Prompter: prompter,
}
cmd := NewCmdReview(factory, nil)
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 TestPRReview(t *testing.T) {
tests := []struct {
args string
wantEvent string
wantBody string
}{
{
args: `--request-changes -b"bad"`,
wantEvent: "REQUEST_CHANGES",
wantBody: "bad",
},
{
args: `--approve`,
wantEvent: "APPROVE",
wantBody: "",
},
{
args: `--approve -b"hot damn"`,
wantEvent: "APPROVE",
wantBody: "hot damn",
},
{
args: `--comment --body "i dunno"`,
wantEvent: "COMMENT",
wantBody: "i dunno",
},
}
for _, tt := range tests {
t.Run(tt.args, func(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t, "", &api.PullRequest{ID: "THE-ID"}, ghrepo.New("OWNER", "REPO"))
http.Register(
httpmock.GraphQL(`mutation PullRequestReviewAdd\b`),
httpmock.GraphQLMutation(`{"data": {} }`,
func(inputs map[string]interface{}) {
assert.Equal(t, map[string]interface{}{
"pullRequestId": "THE-ID",
"event": tt.wantEvent,
"body": tt.wantBody,
}, inputs)
}),
)
output, err := runCommand(http, nil, false, tt.args)
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, "", output.Stderr())
})
}
}
func TestPRReview_interactive(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t, "", &api.PullRequest{ID: "THE-ID", Number: 123}, ghrepo.New("OWNER", "REPO"))
http.Register(
httpmock.GraphQL(`mutation PullRequestReviewAdd\b`),
httpmock.GraphQLMutation(`{"data": {} }`,
func(inputs map[string]interface{}) {
assert.Equal(t, inputs["event"], "APPROVE")
assert.Equal(t, inputs["body"], "cool story")
}),
)
pm := &prompter.PrompterMock{
SelectFunc: func(_, _ string, _ []string) (int, error) { return 1, nil },
MarkdownEditorFunc: func(_, _ string, _ bool) (string, error) { return "cool story", nil },
ConfirmFunc: func(_ string, _ bool) (bool, error) { return true, nil },
}
output, err := runCommand(http, pm, true, "")
assert.NoError(t, err)
assert.Equal(t, heredoc.Doc(`
Got:
cool story
`), output.String())
assert.Equal(t, "✓ Approved pull request OWNER/REPO#123\n", output.Stderr())
}
func TestPRReview_interactive_no_body(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t, "", &api.PullRequest{ID: "THE-ID", Number: 123}, ghrepo.New("OWNER", "REPO"))
pm := &prompter.PrompterMock{
SelectFunc: func(_, _ string, _ []string) (int, error) { return 2, nil },
MarkdownEditorFunc: func(_, _ string, _ bool) (string, error) { return "", nil },
}
_, err := runCommand(http, pm, true, "")
assert.EqualError(t, err, "this type of review cannot be blank")
}
func TestPRReview_interactive_blank_approve(t *testing.T) {
http := &httpmock.Registry{}
defer http.Verify(t)
shared.StubFinderForRunCommandStyleTests(t, "", &api.PullRequest{ID: "THE-ID", Number: 123}, ghrepo.New("OWNER", "REPO"))
http.Register(
httpmock.GraphQL(`mutation PullRequestReviewAdd\b`),
httpmock.GraphQLMutation(`{"data": {} }`,
func(inputs map[string]interface{}) {
assert.Equal(t, inputs["event"], "APPROVE")
assert.Equal(t, inputs["body"], "")
}),
)
pm := &prompter.PrompterMock{
SelectFunc: func(_, _ string, _ []string) (int, error) { return 1, nil },
MarkdownEditorFunc: func(_, defVal string, _ bool) (string, error) { return defVal, nil },
ConfirmFunc: func(_ string, _ bool) (bool, error) { return true, nil },
}
output, err := runCommand(http, pm, true, "")
assert.NoError(t, err)
assert.Equal(t, "", output.String())
assert.Equal(t, "✓ Approved pull request OWNER/REPO#123\n", output.Stderr())
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/review/review.go | pkg/cmd/pr/review/review.go | package review
import (
"errors"
"fmt"
"net/http"
"github.com/MakeNowJust/heredoc"
"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/cmd/pr/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/cli/cli/v2/pkg/markdown"
"github.com/spf13/cobra"
)
type ReviewOptions struct {
HttpClient func() (*http.Client, error)
Config func() (gh.Config, error)
IO *iostreams.IOStreams
Prompter prompter.Prompter
Finder shared.PRFinder
SelectorArg string
InteractiveMode bool
ReviewType api.PullRequestReviewState
Body string
}
func NewCmdReview(f *cmdutil.Factory, runF func(*ReviewOptions) error) *cobra.Command {
opts := &ReviewOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
Config: f.Config,
Prompter: f.Prompter,
}
var (
flagApprove bool
flagRequestChanges bool
flagComment bool
)
var bodyFile string
cmd := &cobra.Command{
Use: "review [<number> | <url> | <branch>]",
Short: "Add a review to a pull request",
Long: heredoc.Doc(`
Add a review to a pull request.
Without an argument, the pull request that belongs to the current branch is reviewed.
`),
Example: heredoc.Doc(`
# Approve the pull request of the current branch
$ gh pr review --approve
# Leave a review comment for the current branch
$ gh pr review --comment -b "interesting"
# Add a review for a specific pull request
$ gh pr review 123
# Request changes on a specific pull request
$ gh pr review 123 -r -b "needs more ASCII art"
`),
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]
}
bodyProvided := cmd.Flags().Changed("body")
bodyFileProvided := bodyFile != ""
if err := cmdutil.MutuallyExclusive(
"specify only one of `--body` or `--body-file`",
bodyProvided,
bodyFileProvided,
); err != nil {
return err
}
if bodyFileProvided {
b, err := cmdutil.ReadFile(bodyFile, opts.IO.In)
if err != nil {
return err
}
opts.Body = string(b)
}
found := 0
if flagApprove {
found++
opts.ReviewType = api.ReviewApprove
}
if flagRequestChanges {
found++
opts.ReviewType = api.ReviewRequestChanges
if opts.Body == "" {
return cmdutil.FlagErrorf("body cannot be blank for request-changes review")
}
}
if flagComment {
found++
opts.ReviewType = api.ReviewComment
if opts.Body == "" {
return cmdutil.FlagErrorf("body cannot be blank for comment review")
}
}
if found == 0 && opts.Body == "" {
if !opts.IO.CanPrompt() {
return cmdutil.FlagErrorf("--approve, --request-changes, or --comment required when not running interactively")
}
opts.InteractiveMode = true
} else if found == 0 && opts.Body != "" {
return cmdutil.FlagErrorf("--body unsupported without --approve, --request-changes, or --comment")
} else if found > 1 {
return cmdutil.FlagErrorf("need exactly one of --approve, --request-changes, or --comment")
}
if runF != nil {
return runF(opts)
}
return reviewRun(opts)
},
}
cmd.Flags().BoolVarP(&flagApprove, "approve", "a", false, "Approve pull request")
cmd.Flags().BoolVarP(&flagRequestChanges, "request-changes", "r", false, "Request changes on a pull request")
cmd.Flags().BoolVarP(&flagComment, "comment", "c", false, "Comment on a pull request")
cmd.Flags().StringVarP(&opts.Body, "body", "b", "", "Specify the body of a review")
cmd.Flags().StringVarP(&bodyFile, "body-file", "F", "", "Read body text from `file` (use \"-\" to read from standard input)")
return cmd
}
func reviewRun(opts *ReviewOptions) error {
findOptions := shared.FindOptions{
Selector: opts.SelectorArg,
Fields: []string{"id", "number"},
}
pr, baseRepo, err := opts.Finder.Find(findOptions)
if err != nil {
return err
}
var reviewData *api.PullRequestReviewInput
if opts.InteractiveMode {
reviewData, err = reviewSurvey(opts)
if err != nil {
return err
}
if reviewData == nil {
fmt.Fprint(opts.IO.ErrOut, "Discarding.\n")
return nil
}
} else {
reviewData = &api.PullRequestReviewInput{
State: opts.ReviewType,
Body: opts.Body,
}
}
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
apiClient := api.NewClientFromHTTP(httpClient)
err = api.AddReview(apiClient, baseRepo, pr, reviewData)
if err != nil {
return fmt.Errorf("failed to create review: %w", err)
}
if !opts.IO.IsStdoutTTY() || !opts.IO.IsStderrTTY() {
return nil
}
cs := opts.IO.ColorScheme()
switch reviewData.State {
case api.ReviewComment:
fmt.Fprintf(opts.IO.ErrOut, "%s Reviewed pull request %s#%d\n", cs.Muted("-"), ghrepo.FullName(baseRepo), pr.Number)
case api.ReviewApprove:
fmt.Fprintf(opts.IO.ErrOut, "%s Approved pull request %s#%d\n", cs.SuccessIcon(), ghrepo.FullName(baseRepo), pr.Number)
case api.ReviewRequestChanges:
fmt.Fprintf(opts.IO.ErrOut, "%s Requested changes to pull request %s#%d\n", cs.Red("+"), ghrepo.FullName(baseRepo), pr.Number)
}
return nil
}
func reviewSurvey(opts *ReviewOptions) (*api.PullRequestReviewInput, error) {
options := []string{"Comment", "Approve", "Request Changes"}
reviewType, err := opts.Prompter.Select(
"What kind of review do you want to give?",
options[0],
options)
if err != nil {
return nil, err
}
var reviewState api.PullRequestReviewState
switch reviewType {
case 0:
reviewState = api.ReviewComment
case 1:
reviewState = api.ReviewApprove
case 2:
reviewState = api.ReviewRequestChanges
default:
panic("unreachable state")
}
blankAllowed := false
if reviewState == api.ReviewApprove {
blankAllowed = true
}
body, err := opts.Prompter.MarkdownEditor("Review body", "", blankAllowed)
if err != nil {
return nil, err
}
if body == "" && (reviewState == api.ReviewComment || reviewState == api.ReviewRequestChanges) {
return nil, errors.New("this type of review cannot be blank")
}
if len(body) > 0 {
renderedBody, err := markdown.Render(body,
markdown.WithTheme(opts.IO.TerminalTheme()),
markdown.WithWrap(opts.IO.TerminalWidth()))
if err != nil {
return nil, err
}
fmt.Fprintf(opts.IO.Out, "Got:\n%s", renderedBody)
}
confirm, err := opts.Prompter.Confirm("Submit?", true)
if err != nil {
return nil, err
}
if !confirm {
return nil, nil
}
return &api.PullRequestReviewInput{
Body: body,
State: reviewState,
}, nil
}
| go | MIT | c534a758887878331dda780aeb696b113f37b4ab | 2026-01-07T08:35:47.579368Z | false |
cli/cli | https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/pr/status/status.go | pkg/cmd/pr/status/status.go | package status
import (
"context"
"errors"
"fmt"
"net/http"
"regexp"
"strconv"
"time"
"github.com/MakeNowJust/heredoc"
"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/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"
)
type StatusOptions struct {
HttpClient func() (*http.Client, error)
GitClient *git.Client
Config func() (gh.Config, error)
IO *iostreams.IOStreams
BaseRepo func() (ghrepo.Interface, error)
Remotes func() (ghContext.Remotes, error)
Branch func() (string, error)
HasRepoOverride bool
Exporter cmdutil.Exporter
ConflictStatus bool
Detector fd.Detector
}
func NewCmdStatus(f *cmdutil.Factory, runF func(*StatusOptions) error) *cobra.Command {
opts := &StatusOptions{
IO: f.IOStreams,
HttpClient: f.HttpClient,
GitClient: f.GitClient,
Config: f.Config,
Remotes: f.Remotes,
Branch: f.Branch,
}
cmd := &cobra.Command{
Use: "status",
Short: "Show status of relevant pull requests",
Long: heredoc.Docf(`
Show status of relevant pull requests.
The status shows a summary of pull requests that includes information such as
pull request number, title, CI checks, reviews, etc.
To see more details of CI checks, run %[1]sgh pr checks%[1]s.
`, "`"),
Args: cmdutil.NoArgsQuoteReminder,
RunE: func(cmd *cobra.Command, args []string) error {
// support `-R, --repo` override
opts.BaseRepo = f.BaseRepo
opts.HasRepoOverride = cmd.Flags().Changed("repo")
if runF != nil {
return runF(opts)
}
return statusRun(opts)
},
}
cmd.Flags().BoolVarP(&opts.ConflictStatus, "conflict-status", "c", false, "Display the merge conflict status of each pull request")
cmdutil.AddJSONFlags(cmd, &opts.Exporter, api.PullRequestFields)
return cmd
}
func statusRun(opts *StatusOptions) error {
ctx := context.Background()
httpClient, err := opts.HttpClient()
if err != nil {
return err
}
baseRefRepo, err := opts.BaseRepo()
if err != nil {
return err
}
var currentBranchName string
var currentPRNumber int
var currentHeadRefBranchName string
if !opts.HasRepoOverride {
// We must be in a repo without the override
currentBranchName, err = opts.Branch()
if err != nil && !errors.Is(err, git.ErrNotOnAnyBranch) {
return fmt.Errorf("could not query for pull request for current branch: %w", err)
}
if !errors.Is(err, git.ErrNotOnAnyBranch) {
branchConfig, err := opts.GitClient.ReadBranchConfig(ctx, currentBranchName)
if err != nil {
return 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 {
currentPRNumber, _ = strconv.Atoi(m[1])
}
if currentPRNumber == 0 {
prRefsResolver := shared.NewPullRequestFindRefsResolver(
// We requested the branch config already, so let's cache that
shared.CachedBranchConfigGitConfigClient{
CachedBranchConfig: branchConfig,
GitConfigClient: opts.GitClient,
},
opts.Remotes,
)
prRefs, err := prRefsResolver.ResolvePullRequestRefs(baseRefRepo, "", currentBranchName)
if err != nil {
return err
}
currentHeadRefBranchName = prRefs.QualifiedHeadRef()
}
}
}
options := requestOptions{
Username: "@me",
CurrentPR: currentPRNumber,
HeadRef: currentHeadRefBranchName,
ConflictStatus: opts.ConflictStatus,
}
if opts.Exporter != nil {
options.Fields = opts.Exporter.Fields()
}
if opts.Detector == nil {
cachedClient := api.NewCachedHTTPClient(httpClient, time.Hour*24)
opts.Detector = fd.NewDetector(cachedClient, baseRefRepo.RepoHost())
}
prFeatures, err := opts.Detector.PullRequestFeatures()
if err != nil {
return err
}
options.CheckRunAndStatusContextCountsSupported = prFeatures.CheckRunAndStatusContextCounts
prPayload, err := pullRequestStatus(httpClient, baseRefRepo, options)
if err != nil {
return err
}
err = opts.IO.StartPager()
if err != nil {
fmt.Fprintf(opts.IO.ErrOut, "error starting pager: %v\n", err)
}
defer opts.IO.StopPager()
if opts.Exporter != nil {
data := map[string]interface{}{
"currentBranch": nil,
"createdBy": prPayload.ViewerCreated.PullRequests,
"needsReview": prPayload.ReviewRequested.PullRequests,
}
if prPayload.CurrentPR != nil {
data["currentBranch"] = prPayload.CurrentPR
}
return opts.Exporter.Write(opts.IO, data)
}
out := opts.IO.Out
cs := opts.IO.ColorScheme()
fmt.Fprintln(out, "")
fmt.Fprintf(out, "Relevant pull requests in %s\n", ghrepo.FullName(baseRefRepo))
fmt.Fprintln(out, "")
if !opts.HasRepoOverride {
shared.PrintHeader(opts.IO, "Current branch")
currentPR := prPayload.CurrentPR
if currentPR != nil && currentPR.State != "OPEN" && prPayload.DefaultBranch == currentBranchName {
currentPR = nil
}
if currentPR != nil {
printPrs(opts.IO, 1, *currentPR)
} else if currentHeadRefBranchName == "" {
shared.PrintMessage(opts.IO, " There is no current branch")
} else {
shared.PrintMessage(opts.IO, fmt.Sprintf(" There is no pull request associated with %s", cs.Cyan("["+currentHeadRefBranchName+"]")))
}
fmt.Fprintln(out)
}
shared.PrintHeader(opts.IO, "Created by you")
if prPayload.ViewerCreated.TotalCount > 0 {
printPrs(opts.IO, prPayload.ViewerCreated.TotalCount, prPayload.ViewerCreated.PullRequests...)
} else {
shared.PrintMessage(opts.IO, " You have no open pull requests")
}
fmt.Fprintln(out)
shared.PrintHeader(opts.IO, "Requesting a code review from you")
if prPayload.ReviewRequested.TotalCount > 0 {
printPrs(opts.IO, prPayload.ReviewRequested.TotalCount, prPayload.ReviewRequested.PullRequests...)
} else {
shared.PrintMessage(opts.IO, " You have no pull requests to review")
}
fmt.Fprintln(out)
return nil
}
func totalApprovals(pr *api.PullRequest) int {
approvals := 0
for _, review := range pr.LatestReviews.Nodes {
if review.State == "APPROVED" {
approvals++
}
}
return approvals
}
func printPrs(io *iostreams.IOStreams, totalCount int, prs ...api.PullRequest) {
w := io.Out
cs := io.ColorScheme()
for _, pr := range prs {
prNumber := fmt.Sprintf("#%d", pr.Number)
prStateColorFunc := cs.ColorFromString(shared.ColorForPRState(pr))
fmt.Fprintf(w, " %s %s %s", prStateColorFunc(prNumber), text.Truncate(50, text.RemoveExcessiveWhitespace(pr.Title)), cs.Cyan("["+pr.HeadLabel()+"]"))
checks := pr.ChecksStatus()
reviews := pr.ReviewStatus()
if pr.State == "OPEN" {
reviewStatus := reviews.ChangesRequested || reviews.Approved || reviews.ReviewRequired
if checks.Total > 0 || reviewStatus {
// show checks & reviews on their own line
fmt.Fprintf(w, "\n ")
}
if checks.Total > 0 {
summary := shared.PrCheckStatusSummaryWithColor(cs, checks)
fmt.Fprint(w, summary)
}
if checks.Total > 0 && reviewStatus {
// add padding between checks & reviews
fmt.Fprint(w, " ")
}
if reviews.ChangesRequested {
fmt.Fprint(w, cs.Red("+ Changes requested"))
} else if reviews.ReviewRequired {
fmt.Fprint(w, cs.Yellow("- Review required"))
} else if reviews.Approved {
numRequiredApprovals := pr.BaseRef.BranchProtectionRule.RequiredApprovingReviewCount
gotApprovals := totalApprovals(&pr)
s := fmt.Sprintf("%d", gotApprovals)
if numRequiredApprovals > 0 {
s = fmt.Sprintf("%d/%d", gotApprovals, numRequiredApprovals)
}
fmt.Fprint(w, cs.Green(fmt.Sprintf("✓ %s Approved", s)))
}
if pr.Mergeable == api.PullRequestMergeableMergeable {
// prefer "No merge conflicts" to "Mergeable" as there is more to mergeability
// than the git status. Missing or failing required checks prevent merging
// even though a PR is technically mergeable, which is often a source of confusion.
fmt.Fprintf(w, " %s", cs.Green("✓ No merge conflicts"))
} else if pr.Mergeable == api.PullRequestMergeableConflicting {
fmt.Fprintf(w, " %s", cs.Red("× Merge conflicts"))
} else if pr.Mergeable == api.PullRequestMergeableUnknown {
fmt.Fprintf(w, " %s", cs.Yellow("! Merge conflict status unknown"))
}
if pr.BaseRef.BranchProtectionRule.RequiresStrictStatusChecks {
switch pr.MergeStateStatus {
case "BEHIND":
fmt.Fprintf(w, " %s", cs.Yellow("- Not up to date"))
case "UNKNOWN", "DIRTY":
// do not print anything
default:
fmt.Fprintf(w, " %s", cs.Green("✓ Up to date"))
}
}
if pr.AutoMergeRequest != nil {
fmt.Fprintf(w, " %s", cs.Green("✓ Auto-merge enabled"))
}
} else {
fmt.Fprintf(w, " - %s", shared.StateTitleWithColor(cs, pr))
}
fmt.Fprint(w, "\n")
}
remaining := totalCount - len(prs)
if remaining > 0 {
fmt.Fprintln(w, cs.Mutedf(" And %d more", remaining))
}
}
| 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.