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/repo/unarchive/unarchive.go
pkg/cmd/repo/unarchive/unarchive.go
package unarchive import ( "fmt" "net/http" "strings" "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/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type UnarchiveOptions struct { HttpClient func() (*http.Client, error) Config func() (gh.Config, error) BaseRepo func() (ghrepo.Interface, error) Confirmed bool IO *iostreams.IOStreams RepoArg string Prompter prompter.Prompter } func NewCmdUnarchive(f *cmdutil.Factory, runF func(*UnarchiveOptions) error) *cobra.Command { opts := &UnarchiveOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, Config: f.Config, BaseRepo: f.BaseRepo, Prompter: f.Prompter, } cmd := &cobra.Command{ Use: "unarchive [<repository>]", Short: "Unarchive a repository", Long: heredoc.Doc(`Unarchive a GitHub repository. With no argument, unarchives the current repository.`), Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { if len(args) > 0 { opts.RepoArg = args[0] } if !opts.Confirmed && !opts.IO.CanPrompt() { return cmdutil.FlagErrorf("--yes required when not running interactively") } if runF != nil { return runF(opts) } return unarchiveRun(opts) }, } cmd.Flags().BoolVar(&opts.Confirmed, "confirm", false, "Skip the confirmation prompt") _ = cmd.Flags().MarkDeprecated("confirm", "use `--yes` instead") cmd.Flags().BoolVarP(&opts.Confirmed, "yes", "y", false, "Skip the confirmation prompt") return cmd } func unarchiveRun(opts *UnarchiveOptions) error { cs := opts.IO.ColorScheme() httpClient, err := opts.HttpClient() if err != nil { return err } apiClient := api.NewClientFromHTTP(httpClient) var toUnarchive ghrepo.Interface if opts.RepoArg == "" { toUnarchive, err = opts.BaseRepo() if err != nil { return err } } else { repoSelector := opts.RepoArg if !strings.Contains(repoSelector, "/") { cfg, err := opts.Config() if err != nil { return err } hostname, _ := cfg.Authentication().DefaultHost() currentUser, err := api.CurrentLoginName(apiClient, hostname) if err != nil { return err } repoSelector = currentUser + "/" + repoSelector } toUnarchive, err = ghrepo.FromFullName(repoSelector) if err != nil { return err } } fields := []string{"name", "owner", "isArchived", "id"} repo, err := api.FetchRepository(apiClient, toUnarchive, fields) if err != nil { return err } fullName := ghrepo.FullName(toUnarchive) if !repo.IsArchived { fmt.Fprintf(opts.IO.ErrOut, "%s Repository %s is not archived\n", cs.WarningIcon(), fullName) return nil } if !opts.Confirmed { confirmed, err := opts.Prompter.Confirm(fmt.Sprintf("Unarchive %s?", fullName), false) if err != nil { return err } if !confirmed { return cmdutil.CancelError } } err = unarchiveRepo(httpClient, repo) if err != nil { return err } if opts.IO.IsStdoutTTY() { fmt.Fprintf(opts.IO.Out, "%s Unarchived repository %s\n", cs.SuccessIcon(), fullName) } return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/unarchive/http.go
pkg/cmd/repo/unarchive/http.go
package unarchive import ( "net/http" "github.com/cli/cli/v2/api" "github.com/shurcooL/githubv4" ) func unarchiveRepo(client *http.Client, repo *api.Repository) error { var mutation struct { UnarchiveRepository struct { Repository struct { ID string } } `graphql:"unarchiveRepository(input: $input)"` } variables := map[string]interface{}{ "input": githubv4.UnarchiveRepositoryInput{ RepositoryID: repo.ID, }, } gql := api.NewClientFromHTTP(client) err := gql.Mutate(repo.RepoHost(), "UnarchiveRepository", &mutation, variables) return err }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/unarchive/unarchive_test.go
pkg/cmd/repo/unarchive/unarchive_test.go
package unarchive import ( "bytes" "fmt" "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 TestNewCmdUnarchive(t *testing.T) { tests := []struct { name string input string wantErr bool output UnarchiveOptions errMsg string }{ { name: "no arguments no tty", input: "", errMsg: "--yes required when not running interactively", wantErr: true, }, { name: "repo argument tty", input: "OWNER/REPO --confirm", output: UnarchiveOptions{RepoArg: "OWNER/REPO", Confirmed: true}, }, } 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 *UnarchiveOptions cmd := NewCmdUnarchive(f, func(opts *UnarchiveOptions) 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.Error(t, err) return } assert.NoError(t, err) assert.Equal(t, tt.output.RepoArg, gotOpts.RepoArg) assert.Equal(t, tt.output.Confirmed, gotOpts.Confirmed) }) } } func Test_UnarchiveRun(t *testing.T) { queryResponse := `{ "data": { "repository": { "id": "THE-ID","isArchived": %s} } }` tests := []struct { name string opts UnarchiveOptions httpStubs func(*httpmock.Registry) prompterStubs func(*prompter.PrompterMock) isTTY bool wantStdout string wantStderr string }{ { name: "archived repo tty", wantStdout: "✓ Unarchived repository OWNER/REPO\n", prompterStubs: func(pm *prompter.PrompterMock) { pm.ConfirmFunc = func(p string, d bool) (bool, error) { if p == "Unarchive OWNER/REPO?" { return true, nil } return false, prompter.NoSuchPromptErr(p) } }, isTTY: true, opts: UnarchiveOptions{RepoArg: "OWNER/REPO"}, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(fmt.Sprintf(queryResponse, "true"))) reg.Register( httpmock.GraphQL(`mutation UnarchiveRepository\b`), httpmock.StringResponse(`{}`)) }, }, { name: "infer base repo", wantStdout: "✓ Unarchived repository OWNER/REPO\n", opts: UnarchiveOptions{}, prompterStubs: func(pm *prompter.PrompterMock) { pm.ConfirmFunc = func(p string, d bool) (bool, error) { if p == "Unarchive OWNER/REPO?" { return true, nil } return false, prompter.NoSuchPromptErr(p) } }, isTTY: true, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(fmt.Sprintf(queryResponse, "true"))) reg.Register( httpmock.GraphQL(`mutation UnarchiveRepository\b`), httpmock.StringResponse(`{}`)) }, }, { name: "unarchived repo tty", wantStderr: "! Repository OWNER/REPO is not archived\n", opts: UnarchiveOptions{RepoArg: "OWNER/REPO"}, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(fmt.Sprintf(queryResponse, "false"))) }, }, } for _, tt := range tests { repo, _ := ghrepo.FromFullName("OWNER/REPO") reg := &httpmock.Registry{} if tt.httpStubs != nil { tt.httpStubs(reg) } tt.opts.BaseRepo = func() (ghrepo.Interface, error) { return repo, nil } tt.opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } ios, _, stdout, stderr := iostreams.Test() tt.opts.IO = ios pm := &prompter.PrompterMock{} if tt.prompterStubs != nil { tt.prompterStubs(pm) } tt.opts.Prompter = pm t.Run(tt.name, func(t *testing.T) { defer reg.Verify(t) ios.SetStdoutTTY(tt.isTTY) ios.SetStderrTTY(tt.isTTY) err := unarchiveRun(&tt.opts) 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/repo/view/view.go
pkg/cmd/repo/view/view.go
package view import ( "errors" "fmt" "net/http" "net/url" "strings" "text/template" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/browser" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/text" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/pkg/markdown" "github.com/spf13/cobra" ) type ViewOptions struct { HttpClient func() (*http.Client, error) IO *iostreams.IOStreams BaseRepo func() (ghrepo.Interface, error) Browser browser.Browser Exporter cmdutil.Exporter Config func() (gh.Config, error) RepoArg string Web bool Branch string } func NewCmdView(f *cmdutil.Factory, runF func(*ViewOptions) error) *cobra.Command { opts := ViewOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, BaseRepo: f.BaseRepo, Browser: f.Browser, Config: f.Config, } cmd := &cobra.Command{ Use: "view [<repository>]", Short: "View a repository", Long: heredoc.Docf(` Display the description and the README of a GitHub repository. With no argument, the repository for the current directory is displayed. With %[1]s--web%[1]s, open the repository in a web browser instead. With %[1]s--branch%[1]s, view a specific branch of the repository. `, "`"), Args: cobra.MaximumNArgs(1), RunE: func(c *cobra.Command, args []string) error { if len(args) > 0 { opts.RepoArg = args[0] } if runF != nil { return runF(&opts) } return viewRun(&opts) }, } cmd.Flags().BoolVarP(&opts.Web, "web", "w", false, "Open a repository in the browser") cmd.Flags().StringVarP(&opts.Branch, "branch", "b", "", "View a specific branch of the repository") cmdutil.AddJSONFlags(cmd, &opts.Exporter, api.RepositoryFields) _ = cmdutil.RegisterBranchCompletionFlags(f.GitClient, cmd, "branch") return cmd } var defaultFields = []string{"name", "owner", "description"} func viewRun(opts *ViewOptions) error { httpClient, err := opts.HttpClient() if err != nil { return err } var toView ghrepo.Interface apiClient := api.NewClientFromHTTP(httpClient) if opts.RepoArg == "" { var err error toView, err = opts.BaseRepo() if err != nil { return err } } else { viewURL := opts.RepoArg if !strings.Contains(viewURL, "/") { cfg, err := opts.Config() if err != nil { return err } hostname, _ := cfg.Authentication().DefaultHost() currentUser, err := api.CurrentLoginName(apiClient, hostname) if err != nil { return err } viewURL = currentUser + "/" + viewURL } toView, err = ghrepo.FromFullName(viewURL) if err != nil { return fmt.Errorf("argument error: %w", err) } } var readme *RepoReadme fields := defaultFields if opts.Exporter != nil { fields = opts.Exporter.Fields() } repo, err := api.FetchRepository(apiClient, toView, fields) if err != nil { return err } if !opts.Web && opts.Exporter == nil { readme, err = RepositoryReadme(httpClient, toView, opts.Branch) if err != nil && !errors.Is(err, NotFoundError) { return err } } openURL := generateBranchURL(toView, opts.Branch) if opts.Web { if opts.IO.IsStdoutTTY() { 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, repo) } fullName := ghrepo.FullName(toView) stdout := opts.IO.Out if !opts.IO.IsStdoutTTY() { fmt.Fprintf(stdout, "name:\t%s\n", fullName) fmt.Fprintf(stdout, "description:\t%s\n", repo.Description) if readme != nil { fmt.Fprintln(stdout, "--") fmt.Fprint(stdout, readme.Content) fmt.Fprintln(stdout) } return nil } repoTmpl := heredoc.Doc(` {{.FullName}} {{.Description}} {{.Readme}} {{.View}} `) tmpl, err := template.New("repo").Parse(repoTmpl) if err != nil { return err } cs := opts.IO.ColorScheme() var readmeContent string if readme == nil { readmeContent = cs.Muted("This repository does not have a README") } else if isMarkdownFile(readme.Filename) { var err error readmeContent, err = markdown.Render(readme.Content, markdown.WithTheme(opts.IO.TerminalTheme()), markdown.WithWrap(opts.IO.TerminalWidth()), markdown.WithBaseURL(readme.BaseURL)) if err != nil { return fmt.Errorf("error rendering markdown: %w", err) } } else { readmeContent = readme.Content } description := repo.Description if description == "" { description = cs.Muted("No description provided") } repoData := struct { FullName string Description string Readme string View string }{ FullName: cs.Bold(fullName), Description: description, Readme: readmeContent, View: cs.Mutedf("View this repository on GitHub: %s", openURL), } return tmpl.Execute(stdout, repoData) } func isMarkdownFile(filename string) bool { // kind of gross, but i'm assuming that 90% of the time the suffix will just be .md. it didn't // seem worth executing a regex for this given that assumption. return strings.HasSuffix(filename, ".md") || strings.HasSuffix(filename, ".markdown") || strings.HasSuffix(filename, ".mdown") || strings.HasSuffix(filename, ".mkdown") } func generateBranchURL(r ghrepo.Interface, branch string) string { if branch == "" { return ghrepo.GenerateRepoURL(r, "") } return ghrepo.GenerateRepoURL(r, "tree/%s", url.QueryEscape(branch)) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/view/http.go
pkg/cmd/repo/view/http.go
package view import ( "bytes" "encoding/base64" "errors" "fmt" "io" "net/http" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/go-gh/v2/pkg/asciisanitizer" "golang.org/x/text/transform" ) var NotFoundError = errors.New("not found") type RepoReadme struct { Filename string Content string BaseURL string } func RepositoryReadme(client *http.Client, repo ghrepo.Interface, branch string) (*RepoReadme, error) { apiClient := api.NewClientFromHTTP(client) var response struct { Name string Content string HTMLURL string `json:"html_url"` } err := apiClient.REST(repo.RepoHost(), "GET", getReadmePath(repo, branch), nil, &response) if err != nil { var httpError api.HTTPError if errors.As(err, &httpError) && httpError.StatusCode == 404 { return nil, NotFoundError } return nil, err } decoded, err := base64.StdEncoding.DecodeString(response.Content) if err != nil { return nil, fmt.Errorf("failed to decode readme: %w", err) } sanitized, err := io.ReadAll(transform.NewReader(bytes.NewReader(decoded), &asciisanitizer.Sanitizer{})) if err != nil { return nil, err } return &RepoReadme{ Filename: response.Name, Content: string(sanitized), BaseURL: response.HTMLURL, }, nil } func getReadmePath(repo ghrepo.Interface, branch string) string { path := fmt.Sprintf("repos/%s/readme", ghrepo.FullName(repo)) if branch != "" { path = fmt.Sprintf("%s?ref=%s", path, branch) } return path }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/view/view_test.go
pkg/cmd/repo/view/view_test.go
package view import ( "bytes" "fmt" "net/http" "testing" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/api" "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/internal/ghrepo" "github.com/cli/cli/v2/internal/run" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/pkg/jsonfieldstest" "github.com/google/shlex" "github.com/stretchr/testify/assert" ) func TestJSONFields(t *testing.T) { jsonfieldstest.ExpectCommandToSupportJSONFields(t, NewCmdView, []string{ "archivedAt", "assignableUsers", "codeOfConduct", "contactLinks", "createdAt", "defaultBranchRef", "deleteBranchOnMerge", "description", "diskUsage", "forkCount", "fundingLinks", "hasDiscussionsEnabled", "hasIssuesEnabled", "hasProjectsEnabled", "hasWikiEnabled", "homepageUrl", "id", "isArchived", "isBlankIssuesEnabled", "isEmpty", "isFork", "isInOrganization", "isMirror", "isPrivate", "isSecurityPolicyEnabled", "isTemplate", "isUserConfigurationRepository", "issueTemplates", "issues", "labels", "languages", "latestRelease", "licenseInfo", "mentionableUsers", "mergeCommitAllowed", "milestones", "mirrorUrl", "name", "nameWithOwner", "openGraphImageUrl", "owner", "parent", "primaryLanguage", "projects", "projectsV2", "pullRequestTemplates", "pullRequests", "pushedAt", "rebaseMergeAllowed", "repositoryTopics", "securityPolicyUrl", "sshUrl", "squashMergeAllowed", "stargazerCount", "templateRepository", "updatedAt", "url", "usesCustomOpenGraphImage", "viewerCanAdminister", "viewerDefaultCommitEmail", "viewerDefaultMergeMethod", "viewerHasStarred", "viewerPermission", "viewerPossibleCommitEmails", "viewerSubscription", "visibility", "watchers", }) } func TestNewCmdView(t *testing.T) { tests := []struct { name string cli string wants ViewOptions wantsErr bool }{ { name: "no args", cli: "", wants: ViewOptions{ RepoArg: "", Web: false, }, }, { name: "sets repo arg", cli: "some/repo", wants: ViewOptions{ RepoArg: "some/repo", Web: false, }, }, { name: "sets web", cli: "-w", wants: ViewOptions{ RepoArg: "", Web: true, }, }, { name: "sets branch", cli: "-b feat/awesome", wants: ViewOptions{ RepoArg: "", Branch: "feat/awesome", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { io, _, _, _ := iostreams.Test() f := &cmdutil.Factory{ IOStreams: io, } // THOUGHT: this seems ripe for cmdutil. It's almost identical to the set up for the same test // in gist create. argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts *ViewOptions cmd := NewCmdView(f, func(opts *ViewOptions) 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.Web, gotOpts.Web) assert.Equal(t, tt.wants.Branch, gotOpts.Branch) assert.Equal(t, tt.wants.RepoArg, gotOpts.RepoArg) }) } } func Test_RepoView_Web(t *testing.T) { tests := []struct { name string stdoutTTY bool wantStderr string wantBrowse string }{ { name: "tty", stdoutTTY: true, wantStderr: "Opening https://github.com/OWNER/REPO in your browser.\n", wantBrowse: "https://github.com/OWNER/REPO", }, { name: "nontty", stdoutTTY: false, wantStderr: "", wantBrowse: "https://github.com/OWNER/REPO", }, } for _, tt := range tests { reg := &httpmock.Registry{} reg.StubRepoInfoResponse("OWNER", "REPO", "main") browser := &browser.Stub{} opts := &ViewOptions{ Web: true, HttpClient: func() (*http.Client, error) { return &http.Client{Transport: reg}, nil }, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil }, Browser: browser, } io, _, stdout, stderr := iostreams.Test() opts.IO = io t.Run(tt.name, func(t *testing.T) { io.SetStdoutTTY(tt.stdoutTTY) _, teardown := run.Stub() defer teardown(t) if err := viewRun(opts); err != nil { t.Errorf("viewRun() error = %v", err) } assert.Equal(t, "", stdout.String()) assert.Equal(t, tt.wantStderr, stderr.String()) reg.Verify(t) browser.Verify(t, tt.wantBrowse) }) } } func Test_ViewRun(t *testing.T) { tests := []struct { name string opts *ViewOptions repoName string stdoutTTY bool wantOut string wantStderr string wantErr bool }{ { name: "nontty", wantOut: heredoc.Doc(` name: OWNER/REPO description: social distancing -- # truly cool readme check it out `), }, { name: "url arg", repoName: "jill/valentine", opts: &ViewOptions{ RepoArg: "https://github.com/jill/valentine", }, stdoutTTY: true, wantOut: heredoc.Doc(` jill/valentine social distancing # truly cool readme check it out View this repository on GitHub: https://github.com/jill/valentine `), }, { name: "name arg", repoName: "jill/valentine", opts: &ViewOptions{ RepoArg: "jill/valentine", }, stdoutTTY: true, wantOut: heredoc.Doc(` jill/valentine social distancing # truly cool readme check it out View this repository on GitHub: https://github.com/jill/valentine `), }, { name: "branch arg", opts: &ViewOptions{ Branch: "feat/awesome", }, stdoutTTY: true, wantOut: heredoc.Doc(` OWNER/REPO social distancing # truly cool readme check it out View this repository on GitHub: https://github.com/OWNER/REPO/tree/feat%2Fawesome `), }, { name: "no args", stdoutTTY: true, wantOut: heredoc.Doc(` OWNER/REPO social distancing # truly cool readme check it out View this repository on GitHub: https://github.com/OWNER/REPO `), }, } for _, tt := range tests { if tt.opts == nil { tt.opts = &ViewOptions{} } if tt.repoName == "" { tt.repoName = "OWNER/REPO" } tt.opts.BaseRepo = func() (ghrepo.Interface, error) { repo, _ := ghrepo.FromFullName(tt.repoName) return repo, nil } reg := &httpmock.Registry{} reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "description": "social distancing" } } }`)) reg.Register( httpmock.REST("GET", fmt.Sprintf("repos/%s/readme", tt.repoName)), httpmock.StringResponse(` { "name": "readme.md", "content": "IyB0cnVseSBjb29sIHJlYWRtZSBjaGVjayBpdCBvdXQ="}`)) tt.opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } io, _, stdout, stderr := iostreams.Test() tt.opts.IO = io t.Run(tt.name, func(t *testing.T) { io.SetStdoutTTY(tt.stdoutTTY) if err := viewRun(tt.opts); (err != nil) != tt.wantErr { t.Errorf("viewRun() error = %v, wantErr %v", err, tt.wantErr) } assert.Equal(t, tt.wantStderr, stderr.String()) assert.Equal(t, tt.wantOut, stdout.String()) reg.Verify(t) }) } } func Test_ViewRun_NonMarkdownReadme(t *testing.T) { tests := []struct { name string stdoutTTY bool wantOut string }{ { name: "tty", wantOut: heredoc.Doc(` OWNER/REPO social distancing # truly cool readme check it out View this repository on GitHub: https://github.com/OWNER/REPO `), stdoutTTY: true, }, { name: "nontty", wantOut: heredoc.Doc(` name: OWNER/REPO description: social distancing -- # truly cool readme check it out `), }, } for _, tt := range tests { reg := &httpmock.Registry{} reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "description": "social distancing" } } }`)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/readme"), httpmock.StringResponse(` { "name": "readme.org", "content": "IyB0cnVseSBjb29sIHJlYWRtZSBjaGVjayBpdCBvdXQ="}`)) opts := &ViewOptions{ HttpClient: func() (*http.Client, error) { return &http.Client{Transport: reg}, nil }, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil }, } io, _, stdout, stderr := iostreams.Test() opts.IO = io t.Run(tt.name, func(t *testing.T) { io.SetStdoutTTY(tt.stdoutTTY) if err := viewRun(opts); err != nil { t.Errorf("viewRun() error = %v", err) } assert.Equal(t, tt.wantOut, stdout.String()) assert.Equal(t, "", stderr.String()) reg.Verify(t) }) } } func Test_ViewRun_NoReadme(t *testing.T) { tests := []struct { name string stdoutTTY bool wantOut string }{ { name: "tty", wantOut: heredoc.Doc(` OWNER/REPO social distancing This repository does not have a README View this repository on GitHub: https://github.com/OWNER/REPO `), stdoutTTY: true, }, { name: "nontty", wantOut: heredoc.Doc(` name: OWNER/REPO description: social distancing `), }, } for _, tt := range tests { reg := &httpmock.Registry{} reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "description": "social distancing" } } }`)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/readme"), httpmock.StatusStringResponse(404, `{}`)) opts := &ViewOptions{ HttpClient: func() (*http.Client, error) { return &http.Client{Transport: reg}, nil }, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil }, } io, _, stdout, stderr := iostreams.Test() opts.IO = io t.Run(tt.name, func(t *testing.T) { io.SetStdoutTTY(tt.stdoutTTY) if err := viewRun(opts); err != nil { t.Errorf("viewRun() error = %v", err) } assert.Equal(t, tt.wantOut, stdout.String()) assert.Equal(t, "", stderr.String()) reg.Verify(t) }) } } func Test_ViewRun_NoDescription(t *testing.T) { tests := []struct { name string stdoutTTY bool wantOut string }{ { name: "tty", wantOut: heredoc.Doc(` OWNER/REPO No description provided # truly cool readme check it out View this repository on GitHub: https://github.com/OWNER/REPO `), stdoutTTY: true, }, { name: "nontty", wantOut: heredoc.Doc(` name: OWNER/REPO description: -- # truly cool readme check it out `), }, } for _, tt := range tests { reg := &httpmock.Registry{} reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "description": "" } } }`)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/readme"), httpmock.StringResponse(` { "name": "readme.org", "content": "IyB0cnVseSBjb29sIHJlYWRtZSBjaGVjayBpdCBvdXQ="}`)) opts := &ViewOptions{ HttpClient: func() (*http.Client, error) { return &http.Client{Transport: reg}, nil }, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil }, } io, _, stdout, stderr := iostreams.Test() opts.IO = io t.Run(tt.name, func(t *testing.T) { io.SetStdoutTTY(tt.stdoutTTY) if err := viewRun(opts); err != nil { t.Errorf("viewRun() error = %v", err) } assert.Equal(t, tt.wantOut, stdout.String()) assert.Equal(t, "", stderr.String()) reg.Verify(t) }) } } func Test_ViewRun_WithoutUsername(t *testing.T) { reg := &httpmock.Registry{} reg.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(` { "data": { "viewer": { "login": "OWNER" }}}`)) reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "description": "social distancing" } } }`)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/readme"), httpmock.StringResponse(` { "name": "readme.md", "content": "IyB0cnVseSBjb29sIHJlYWRtZSBjaGVjayBpdCBvdXQ="}`)) io, _, stdout, stderr := iostreams.Test() io.SetStdoutTTY(false) opts := &ViewOptions{ RepoArg: "REPO", HttpClient: func() (*http.Client, error) { return &http.Client{Transport: reg}, nil }, IO: io, Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, } if err := viewRun(opts); err != nil { t.Errorf("viewRun() error = %v", err) } assert.Equal(t, heredoc.Doc(` name: OWNER/REPO description: social distancing -- # truly cool readme check it out `), stdout.String()) assert.Equal(t, "", stderr.String()) reg.Verify(t) } func Test_ViewRun_HandlesSpecialCharacters(t *testing.T) { tests := []struct { name string opts *ViewOptions repoName string stdoutTTY bool wantOut string wantStderr string wantErr bool }{ { name: "nontty", wantOut: heredoc.Doc(` name: OWNER/REPO description: Some basic special characters " & / < > ' -- # < is always > than & ' and " `), }, { name: "no args", stdoutTTY: true, wantOut: heredoc.Doc(` OWNER/REPO Some basic special characters " & / < > ' # < is always > than & ' and " View this repository on GitHub: https://github.com/OWNER/REPO `), }, } for _, tt := range tests { if tt.opts == nil { tt.opts = &ViewOptions{} } if tt.repoName == "" { tt.repoName = "OWNER/REPO" } tt.opts.BaseRepo = func() (ghrepo.Interface, error) { repo, _ := ghrepo.FromFullName(tt.repoName) return repo, nil } reg := &httpmock.Registry{} reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "description": "Some basic special characters \" & / < > '" } } }`)) reg.Register( httpmock.REST("GET", fmt.Sprintf("repos/%s/readme", tt.repoName)), httpmock.StringResponse(` { "name": "readme.md", "content": "IyA8IGlzIGFsd2F5cyA+IHRoYW4gJiAnIGFuZCAi"}`)) tt.opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } io, _, stdout, stderr := iostreams.Test() tt.opts.IO = io t.Run(tt.name, func(t *testing.T) { io.SetStdoutTTY(tt.stdoutTTY) if err := viewRun(tt.opts); (err != nil) != tt.wantErr { t.Errorf("viewRun() error = %v, wantErr %v", err, tt.wantErr) } assert.Equal(t, tt.wantStderr, stderr.String()) assert.Equal(t, tt.wantOut, stdout.String()) reg.Verify(t) }) } } func Test_viewRun_json(t *testing.T) { io, _, stdout, stderr := iostreams.Test() io.SetStdoutTTY(false) reg := &httpmock.Registry{} defer reg.Verify(t) reg.StubRepoInfoResponse("OWNER", "REPO", "main") opts := &ViewOptions{ IO: io, HttpClient: func() (*http.Client, error) { return &http.Client{Transport: reg}, nil }, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil }, Exporter: &testExporter{ fields: []string{"name", "defaultBranchRef"}, }, } _, teardown := run.Stub() defer teardown(t) err := viewRun(opts) assert.NoError(t, err) assert.Equal(t, heredoc.Doc(` name: REPO defaultBranchRef: main `), stdout.String()) assert.Equal(t, "", stderr.String()) } type testExporter struct { fields []string } func (e *testExporter) Fields() []string { return e.fields } func (e *testExporter) Write(io *iostreams.IOStreams, data interface{}) error { r := data.(*api.Repository) fmt.Fprintf(io.Out, "name: %s\n", r.Name) fmt.Fprintf(io.Out, "defaultBranchRef: %s\n", r.DefaultBranchRef.Name) return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/gitignore/gitignore.go
pkg/cmd/repo/gitignore/gitignore.go
package gitignore import ( cmdList "github.com/cli/cli/v2/pkg/cmd/repo/gitignore/list" cmdView "github.com/cli/cli/v2/pkg/cmd/repo/gitignore/view" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/spf13/cobra" ) func NewCmdGitIgnore(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "gitignore <command>", Short: "List and view available repository gitignore templates", } cmd.AddCommand(cmdList.NewCmdList(f, nil)) cmd.AddCommand(cmdView.NewCmdView(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/repo/gitignore/list/list_test.go
pkg/cmd/repo/gitignore/list/list_test.go
package list import ( "bytes" "net/http" "testing" "github.com/MakeNowJust/heredoc" "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/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNewCmdList(t *testing.T) { tests := []struct { name string args []string wantErr bool tty bool }{ { name: "happy path no arguments", args: []string{}, wantErr: false, tty: false, }, { name: "too many arguments", args: []string{"foo"}, wantErr: 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, } cmd := NewCmdList(f, func(*ListOptions) error { return nil }) cmd.SetArgs(tt.args) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err := cmd.ExecuteC() if tt.wantErr { assert.Error(t, err) } else { require.NoError(t, err) } }) } } func TestListRun(t *testing.T) { tests := []struct { name string opts *ListOptions isTTY bool httpStubs func(t *testing.T, reg *httpmock.Registry) wantStdout string wantStderr string wantErr bool errMsg string }{ { name: "gitignore list tty", isTTY: true, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "gitignore/templates"), httpmock.StringResponse(`[ "AL", "Actionscript", "Ada", "Agda", "Android", "AppEngine", "AppceleratorTitanium", "ArchLinuxPackages", "Autotools", "Ballerina", "C", "C++", "CFWheels", "CMake", "CUDA", "CakePHP", "ChefCookbook", "Clojure", "CodeIgniter", "CommonLisp", "Composer", "Concrete5", "Coq", "CraftCMS", "D" ]`, )) }, wantStdout: heredoc.Doc(` GITIGNORE AL Actionscript Ada Agda Android AppEngine AppceleratorTitanium ArchLinuxPackages Autotools Ballerina C C++ CFWheels CMake CUDA CakePHP ChefCookbook Clojure CodeIgniter CommonLisp Composer Concrete5 Coq CraftCMS D `), wantStderr: "", opts: &ListOptions{}, }, { name: "gitignore list no .gitignore templates tty", isTTY: true, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "gitignore/templates"), httpmock.StringResponse(`[]`), ) }, wantStdout: "", wantStderr: "", wantErr: true, errMsg: "No gitignore templates found", opts: &ListOptions{}, }, } for _, tt := range tests { reg := &httpmock.Registry{} if tt.httpStubs != nil { tt.httpStubs(t, reg) } tt.opts.Config = func() (gh.Config, error) { return config.NewBlankConfig(), nil } tt.opts.HTTPClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } ios, _, stdout, stderr := iostreams.Test() ios.SetStdoutTTY(tt.isTTY) ios.SetStdinTTY(tt.isTTY) ios.SetStderrTTY(tt.isTTY) tt.opts.IO = ios t.Run(tt.name, func(t *testing.T) { defer reg.Verify(t) err := listRun(tt.opts) if tt.wantErr { assert.Error(t, err) assert.Equal(t, tt.errMsg, err.Error()) return } 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/repo/gitignore/list/list.go
pkg/cmd/repo/gitignore/list/list.go
package list import ( "fmt" "net/http" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/tableprinter" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type ListOptions struct { IO *iostreams.IOStreams HTTPClient func() (*http.Client, error) Config func() (gh.Config, error) } func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Command { opts := &ListOptions{ IO: f.IOStreams, HTTPClient: f.HttpClient, Config: f.Config, } cmd := &cobra.Command{ Use: "list", Short: "List available repository gitignore templates", Aliases: []string{"ls"}, Args: cobra.ExactArgs(0), RunE: func(cmd *cobra.Command, args []string) error { if runF != nil { return runF(opts) } return listRun(opts) }, } return cmd } func listRun(opts *ListOptions) error { client, err := opts.HTTPClient() if err != nil { return err } cfg, err := opts.Config() if err != nil { return err } if err := opts.IO.StartPager(); err != nil { fmt.Fprintf(opts.IO.ErrOut, "starting pager failed: %v\n", err) } defer opts.IO.StopPager() hostname, _ := cfg.Authentication().DefaultHost() gitIgnoreTemplates, err := api.RepoGitIgnoreTemplates(client, hostname) if err != nil { return err } if len(gitIgnoreTemplates) == 0 { return cmdutil.NewNoResultsError("No gitignore templates found") } return renderGitIgnoreTemplatesTable(gitIgnoreTemplates, opts) } func renderGitIgnoreTemplatesTable(gitIgnoreTemplates []string, opts *ListOptions) error { t := tableprinter.New(opts.IO, tableprinter.WithHeader("GITIGNORE")) for _, gt := range gitIgnoreTemplates { t.AddField(gt) t.EndRow() } return t.Render() }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/gitignore/view/view.go
pkg/cmd/repo/gitignore/view/view.go
package view import ( "errors" "fmt" "net/http" "strings" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type ViewOptions struct { IO *iostreams.IOStreams HTTPClient func() (*http.Client, error) Config func() (gh.Config, error) Template string } func NewCmdView(f *cmdutil.Factory, runF func(*ViewOptions) error) *cobra.Command { opts := &ViewOptions{ IO: f.IOStreams, HTTPClient: f.HttpClient, Config: f.Config, Template: "", } cmd := &cobra.Command{ Use: "view <template>", Short: "View an available repository gitignore template", Long: heredoc.Docf(` View an available repository %[1]s.gitignore%[1]s template. %[1]s<template>%[1]s is a case-sensitive %[1]s.gitignore%[1]s template name. For a list of available templates, run %[1]sgh repo gitignore list%[1]s. `, "`"), Example: heredoc.Doc(` # View the Go gitignore template $ gh repo gitignore view Go # View the Python gitignore template $ gh repo gitignore view Python # Create a new .gitignore file using the Go template $ gh repo gitignore view Go > .gitignore # Create a new .gitignore file using the Python template $ gh repo gitignore view Python > .gitignore `), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.Template = args[0] if runF != nil { return runF(opts) } return viewRun(opts) }, } return cmd } func viewRun(opts *ViewOptions) error { if opts.Template == "" { return errors.New("no template provided") } client, err := opts.HTTPClient() if err != nil { return err } cfg, err := opts.Config() if err != nil { return err } if err := opts.IO.StartPager(); err != nil { fmt.Fprintf(opts.IO.ErrOut, "starting pager failed: %v\n", err) } defer opts.IO.StopPager() hostname, _ := cfg.Authentication().DefaultHost() gitIgnore, err := api.RepoGitIgnoreTemplate(client, hostname, opts.Template) if err != nil { var httpErr api.HTTPError if errors.As(err, &httpErr) { if httpErr.StatusCode == 404 { return fmt.Errorf("'%s' is not a valid gitignore template. Run `gh repo gitignore list` for options", opts.Template) } } return err } return renderGitIgnore(gitIgnore, opts) } func renderGitIgnore(licenseTemplate *api.GitIgnore, opts *ViewOptions) error { // I wanted to render this in a markdown code block and benefit // from .gitignore syntax highlighting. But, the upstream syntax highlighter // does not currently support .gitignore. // So, I just add a newline and print the content as is instead. // Ref: https://github.com/alecthomas/chroma/pull/755 var out strings.Builder if opts.IO.IsStdoutTTY() { out.WriteString("\n") } out.WriteString(licenseTemplate.Source) _, err := opts.IO.Out.Write([]byte(out.String())) 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/repo/gitignore/view/view_test.go
pkg/cmd/repo/gitignore/view/view_test.go
package view import ( "bytes" "net/http" "testing" "github.com/MakeNowJust/heredoc" "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/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestViewRun(t *testing.T) { tests := []struct { name string opts *ViewOptions isTTY bool httpStubs func(t *testing.T, reg *httpmock.Registry) wantStdout string wantStderr string wantErr bool errMsg string }{ { name: "No template", opts: &ViewOptions{}, wantErr: true, errMsg: "no template provided", }, { name: "happy path with template", opts: &ViewOptions{Template: "Go"}, wantErr: false, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "gitignore/templates/Go"), httpmock.StringResponse(`{ "name": "Go", "source": "# If you prefer the allow list template instead of the deny list, see community template:\n# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore\n#\n# Binaries for programs and plugins\n*.exe\n*.exe~\n*.dll\n*.so\n*.dylib\n\n# Test binary, built with go test -c\n*.test\n\n# Output of the go coverage tool, specifically when used with LiteIDE\n*.out\n\n# Dependency directories (remove the comment below to include it)\n# vendor/\n\n# Go workspace file\ngo.work\ngo.work.sum\n\n# env file\n.env\n" }`, )) }, wantStdout: heredoc.Doc(`# If you prefer the allow list template instead of the deny list, see community template: # https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore # # Binaries for programs and plugins *.exe *.exe~ *.dll *.so *.dylib # Test binary, built with go test -c *.test # Output of the go coverage tool, specifically when used with LiteIDE *.out # Dependency directories (remove the comment below to include it) # vendor/ # Go workspace file go.work go.work.sum # env file .env `), }, { name: "non-existent template", opts: &ViewOptions{Template: "non-existent"}, wantErr: true, errMsg: "'non-existent' is not a valid gitignore template. Run `gh repo gitignore list` for options", httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "gitignore/templates/non-existent"), httpmock.StatusStringResponse(404, `{ "message": "Not Found", "documentation_url": "https://docs.github.com/v3/gitignore", "status": "404" }`, )) }, }, } for _, tt := range tests { reg := &httpmock.Registry{} if tt.httpStubs != nil { tt.httpStubs(t, reg) } tt.opts.Config = func() (gh.Config, error) { return config.NewBlankConfig(), nil } tt.opts.HTTPClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } ios, _, stdout, stderr := iostreams.Test() ios.SetStdoutTTY(tt.isTTY) ios.SetStdinTTY(tt.isTTY) ios.SetStderrTTY(tt.isTTY) tt.opts.IO = ios t.Run(tt.name, func(t *testing.T) { defer reg.Verify(t) err := viewRun(tt.opts) if tt.wantErr { assert.Error(t, err) assert.Equal(t, tt.errMsg, err.Error()) return } assert.Equal(t, tt.wantStdout, stdout.String()) assert.Equal(t, tt.wantStderr, stderr.String()) }) } } func TestNewCmdView(t *testing.T) { tests := []struct { name string args []string wantErr bool wantOpts *ViewOptions tty bool }{ { name: "No template", args: []string{}, wantErr: true, wantOpts: &ViewOptions{ Template: "", }, }, { name: "Happy path single template", args: []string{"Go"}, wantErr: false, wantOpts: &ViewOptions{ Template: "Go", }, }, { name: "Happy path too many templates", args: []string{"Go", "Ruby"}, wantErr: true, wantOpts: &ViewOptions{ Template: "", }, }, } 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, } cmd := NewCmdView(f, func(*ViewOptions) error { return nil }) cmd.SetArgs(tt.args) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err := cmd.ExecuteC() if tt.wantErr { assert.Error(t, err) } else { require.NoError(t, err) } assert.Equal(t, tt.wantOpts.Template, tt.wantOpts.Template) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/create/create.go
pkg/cmd/repo/create/create.go
package create import ( "bytes" "context" "errors" "fmt" "io" "net/http" "os/exec" "path/filepath" "sort" "strings" "time" "github.com/MakeNowJust/heredoc" "github.com/cenkalti/backoff/v4" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/git" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/repo/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type errWithExitCode interface { ExitCode() int } type iprompter interface { Input(string, string) (string, error) Select(string, string, []string) (int, error) Confirm(string, bool) (bool, error) } type CreateOptions struct { HttpClient func() (*http.Client, error) GitClient *git.Client Config func() (gh.Config, error) IO *iostreams.IOStreams Prompter iprompter BackOff backoff.BackOff Name string Description string Homepage string Team string Template string Public bool Private bool Internal bool Visibility string Push bool Clone bool Source string Remote string GitIgnoreTemplate string LicenseTemplate string DisableIssues bool DisableWiki bool Interactive bool IncludeAllBranches bool AddReadme bool } func NewCmdCreate(f *cmdutil.Factory, runF func(*CreateOptions) error) *cobra.Command { opts := &CreateOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, GitClient: f.GitClient, Config: f.Config, Prompter: f.Prompter, } var enableIssues bool var enableWiki bool cmd := &cobra.Command{ Use: "create [<name>]", Short: "Create a new repository", Long: heredoc.Docf(` Create a new GitHub repository. To create a repository interactively, use %[1]sgh repo create%[1]s with no arguments. To create a remote repository non-interactively, supply the repository name and one of %[1]s--public%[1]s, %[1]s--private%[1]s, or %[1]s--internal%[1]s. Pass %[1]s--clone%[1]s to clone the new repository locally. If the %[1]sOWNER/%[1]s portion of the %[1]sOWNER/REPO%[1]s name argument is omitted, it defaults to the name of the authenticating user. To create a remote repository from an existing local repository, specify the source directory with %[1]s--source%[1]s. By default, the remote repository name will be the name of the source directory. Pass %[1]s--push%[1]s to push any local commits to the new repository. If the repo is bare, this will mirror all refs. For language or platform .gitignore templates to use with %[1]s--gitignore%[1]s, <https://github.com/github/gitignore>. For license keywords to use with %[1]s--license%[1]s, run %[1]sgh repo license list%[1]s or visit <https://choosealicense.com>. The repo is created with the configured repository default branch, see <https://docs.github.com/en/account-and-profile/setting-up-and-managing-your-personal-account-on-github/managing-user-account-settings/managing-the-default-branch-name-for-your-repositories>. `, "`"), Example: heredoc.Doc(` # Create a repository interactively $ gh repo create # Create a new remote repository and clone it locally $ gh repo create my-project --public --clone # Create a new remote repository in a different organization $ gh repo create my-org/my-project --public # Create a remote repository from the current directory $ gh repo create my-project --private --source=. --remote=upstream `), Args: cobra.MaximumNArgs(1), Aliases: []string{"new"}, RunE: func(cmd *cobra.Command, args []string) error { if len(args) > 0 { opts.Name = args[0] } if len(args) == 0 && cmd.Flags().NFlag() == 0 { if !opts.IO.CanPrompt() { return cmdutil.FlagErrorf("at least one argument required in non-interactive mode") } opts.Interactive = true } else { // exactly one visibility flag required if !opts.Public && !opts.Private && !opts.Internal { return cmdutil.FlagErrorf("`--public`, `--private`, or `--internal` required when not running interactively") } err := cmdutil.MutuallyExclusive( "expected exactly one of `--public`, `--private`, or `--internal`", opts.Public, opts.Private, opts.Internal) if err != nil { return err } if opts.Public { opts.Visibility = "PUBLIC" } else if opts.Private { opts.Visibility = "PRIVATE" } else { opts.Visibility = "INTERNAL" } } if opts.Source == "" { if opts.Remote != "" { return cmdutil.FlagErrorf("the `--remote` option can only be used with `--source`") } if opts.Push { return cmdutil.FlagErrorf("the `--push` option can only be used with `--source`") } if opts.Name == "" && !opts.Interactive { return cmdutil.FlagErrorf("name argument required to create new remote repository") } } else if opts.Clone || opts.GitIgnoreTemplate != "" || opts.LicenseTemplate != "" || opts.Template != "" { return cmdutil.FlagErrorf("the `--source` option is not supported with `--clone`, `--template`, `--license`, or `--gitignore`") } if opts.Template != "" && (opts.GitIgnoreTemplate != "" || opts.LicenseTemplate != "") { return cmdutil.FlagErrorf(".gitignore and license templates are not added when template is provided") } if opts.Template != "" && opts.AddReadme { return cmdutil.FlagErrorf("the `--add-readme` option is not supported with `--template`") } if cmd.Flags().Changed("enable-issues") { opts.DisableIssues = !enableIssues } if cmd.Flags().Changed("enable-wiki") { opts.DisableWiki = !enableWiki } if opts.Template != "" && opts.Team != "" { return cmdutil.FlagErrorf("the `--template` option is not supported with `--team`") } if opts.Template == "" && opts.IncludeAllBranches { return cmdutil.FlagErrorf("the `--include-all-branches` option is only supported when using `--template`") } if runF != nil { return runF(opts) } return createRun(opts) }, } cmd.Flags().StringVarP(&opts.Description, "description", "d", "", "Description of the repository") cmd.Flags().StringVarP(&opts.Homepage, "homepage", "h", "", "Repository home page `URL`") cmd.Flags().StringVarP(&opts.Team, "team", "t", "", "The `name` of the organization team to be granted access") cmd.Flags().StringVarP(&opts.Template, "template", "p", "", "Make the new repository based on a template `repository`") cmd.Flags().BoolVar(&opts.Public, "public", false, "Make the new repository public") cmd.Flags().BoolVar(&opts.Private, "private", false, "Make the new repository private") cmd.Flags().BoolVar(&opts.Internal, "internal", false, "Make the new repository internal") cmd.Flags().StringVarP(&opts.GitIgnoreTemplate, "gitignore", "g", "", "Specify a gitignore template for the repository") cmd.Flags().StringVarP(&opts.LicenseTemplate, "license", "l", "", "Specify an Open Source License for the repository") cmd.Flags().StringVarP(&opts.Source, "source", "s", "", "Specify path to local repository to use as source") cmd.Flags().StringVarP(&opts.Remote, "remote", "r", "", "Specify remote name for the new repository") cmd.Flags().BoolVar(&opts.Push, "push", false, "Push local commits to the new repository") cmd.Flags().BoolVarP(&opts.Clone, "clone", "c", false, "Clone the new repository to the current directory") cmd.Flags().BoolVar(&opts.DisableIssues, "disable-issues", false, "Disable issues in the new repository") cmd.Flags().BoolVar(&opts.DisableWiki, "disable-wiki", false, "Disable wiki in the new repository") cmd.Flags().BoolVar(&opts.IncludeAllBranches, "include-all-branches", false, "Include all branches from template repository") cmd.Flags().BoolVar(&opts.AddReadme, "add-readme", false, "Add a README file to the new repository") // deprecated flags cmd.Flags().BoolP("confirm", "y", false, "Skip the confirmation prompt") cmd.Flags().BoolVar(&enableIssues, "enable-issues", true, "Enable issues in the new repository") cmd.Flags().BoolVar(&enableWiki, "enable-wiki", true, "Enable wiki in the new repository") _ = cmd.Flags().MarkDeprecated("confirm", "Pass any argument to skip confirmation prompt") _ = cmd.Flags().MarkDeprecated("enable-issues", "Disable issues with `--disable-issues`") _ = cmd.Flags().MarkDeprecated("enable-wiki", "Disable wiki with `--disable-wiki`") _ = cmd.RegisterFlagCompletionFunc("gitignore", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { httpClient, err := opts.HttpClient() if err != nil { return nil, cobra.ShellCompDirectiveError } cfg, err := opts.Config() if err != nil { return nil, cobra.ShellCompDirectiveError } hostname, _ := cfg.Authentication().DefaultHost() results, err := api.RepoGitIgnoreTemplates(httpClient, hostname) if err != nil { return nil, cobra.ShellCompDirectiveError } return results, cobra.ShellCompDirectiveNoFileComp }) _ = cmd.RegisterFlagCompletionFunc("license", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { httpClient, err := opts.HttpClient() if err != nil { return nil, cobra.ShellCompDirectiveError } cfg, err := opts.Config() if err != nil { return nil, cobra.ShellCompDirectiveError } hostname, _ := cfg.Authentication().DefaultHost() licenses, err := api.RepoLicenses(httpClient, hostname) if err != nil { return nil, cobra.ShellCompDirectiveError } var results []string for _, license := range licenses { results = append(results, fmt.Sprintf("%s\t%s", license.Key, license.Name)) } return results, cobra.ShellCompDirectiveNoFileComp }) return cmd } func createRun(opts *CreateOptions) error { if opts.Interactive { cfg, err := opts.Config() if err != nil { return err } host, _ := cfg.Authentication().DefaultHost() answer, err := opts.Prompter.Select("What would you like to do?", "", []string{ fmt.Sprintf("Create a new repository on %s from scratch", host), fmt.Sprintf("Create a new repository on %s from a template repository", host), fmt.Sprintf("Push an existing local repository to %s", host), }) if err != nil { return err } switch answer { case 0: return createFromScratch(opts) case 1: return createFromTemplate(opts) case 2: return createFromLocal(opts) } } if opts.Source == "" { return createFromScratch(opts) } return createFromLocal(opts) } // create new repo on remote host func createFromScratch(opts *CreateOptions) error { httpClient, err := opts.HttpClient() if err != nil { return err } var repoToCreate ghrepo.Interface cfg, err := opts.Config() if err != nil { return err } host, _ := cfg.Authentication().DefaultHost() if opts.Interactive { opts.Name, opts.Description, opts.Visibility, err = interactiveRepoInfo(httpClient, host, opts.Prompter, "") if err != nil { return err } opts.AddReadme, err = opts.Prompter.Confirm("Would you like to add a README file?", false) if err != nil { return err } opts.GitIgnoreTemplate, err = interactiveGitIgnore(httpClient, host, opts.Prompter) if err != nil { return err } opts.LicenseTemplate, err = interactiveLicense(httpClient, host, opts.Prompter) if err != nil { return err } targetRepo := shared.NormalizeRepoName(opts.Name) if idx := strings.IndexRune(opts.Name, '/'); idx > 0 { targetRepo = opts.Name[0:idx+1] + shared.NormalizeRepoName(opts.Name[idx+1:]) } confirmed, err := opts.Prompter.Confirm( fmt.Sprintf(`This will create "%s" as a %s repository on %s. Continue?`, targetRepo, strings.ToLower(opts.Visibility), host), true) if err != nil { return err } else if !confirmed { return cmdutil.CancelError } } if strings.Contains(opts.Name, "/") { var err error repoToCreate, err = ghrepo.FromFullName(opts.Name) if err != nil { return fmt.Errorf("argument error: %w", err) } } else { repoToCreate = ghrepo.NewWithHost("", opts.Name, host) } input := repoCreateInput{ Name: repoToCreate.RepoName(), Visibility: opts.Visibility, OwnerLogin: repoToCreate.RepoOwner(), TeamSlug: opts.Team, Description: opts.Description, HomepageURL: opts.Homepage, HasIssuesEnabled: !opts.DisableIssues, HasWikiEnabled: !opts.DisableWiki, GitIgnoreTemplate: opts.GitIgnoreTemplate, LicenseTemplate: opts.LicenseTemplate, IncludeAllBranches: opts.IncludeAllBranches, InitReadme: opts.AddReadme, } var templateRepoMainBranch string if opts.Template != "" { var templateRepo ghrepo.Interface apiClient := api.NewClientFromHTTP(httpClient) templateRepoName := opts.Template if !strings.Contains(templateRepoName, "/") { currentUser, err := api.CurrentLoginName(apiClient, host) if err != nil { return err } templateRepoName = currentUser + "/" + templateRepoName } templateRepo, err = ghrepo.FromFullName(templateRepoName) if err != nil { return fmt.Errorf("argument error: %w", err) } repo, err := api.GitHubRepo(apiClient, templateRepo) if err != nil { return err } input.TemplateRepositoryID = repo.ID templateRepoMainBranch = repo.DefaultBranchRef.Name } repo, err := repoCreate(httpClient, repoToCreate.RepoHost(), input) if err != nil { return err } cs := opts.IO.ColorScheme() isTTY := opts.IO.IsStdoutTTY() if isTTY { fmt.Fprintf(opts.IO.Out, "%s Created repository %s on %s\n %s\n", cs.SuccessIconWithColor(cs.Green), ghrepo.FullName(repo), host, repo.URL) } else { fmt.Fprintln(opts.IO.Out, repo.URL) } if opts.Interactive { var err error opts.Clone, err = opts.Prompter.Confirm("Clone the new repository locally?", true) if err != nil { return err } } if opts.Clone { protocol := cfg.GitProtocol(repo.RepoHost()).Value remoteURL := ghrepo.FormatRemoteURL(repo, protocol) if !opts.AddReadme && opts.LicenseTemplate == "" && opts.GitIgnoreTemplate == "" && opts.Template == "" { // cloning empty repository or template if err := localInit(opts.GitClient, remoteURL, repo.RepoName()); err != nil { return err } } else if err := cloneWithRetry(opts, remoteURL, templateRepoMainBranch); err != nil { return err } } return nil } // create new repo on remote host from template repo func createFromTemplate(opts *CreateOptions) error { httpClient, err := opts.HttpClient() if err != nil { return err } cfg, err := opts.Config() if err != nil { return err } host, _ := cfg.Authentication().DefaultHost() opts.Name, opts.Description, opts.Visibility, err = interactiveRepoInfo(httpClient, host, opts.Prompter, "") if err != nil { return err } if !strings.Contains(opts.Name, "/") { username, _, err := userAndOrgs(httpClient, host) if err != nil { return err } opts.Name = fmt.Sprintf("%s/%s", username, opts.Name) } repoToCreate, err := ghrepo.FromFullName(opts.Name) if err != nil { return fmt.Errorf("argument error: %w", err) } templateRepo, err := interactiveRepoTemplate(httpClient, host, repoToCreate.RepoOwner(), opts.Prompter) if err != nil { return err } input := repoCreateInput{ Name: repoToCreate.RepoName(), Visibility: opts.Visibility, OwnerLogin: repoToCreate.RepoOwner(), TeamSlug: opts.Team, Description: opts.Description, HomepageURL: opts.Homepage, HasIssuesEnabled: !opts.DisableIssues, HasWikiEnabled: !opts.DisableWiki, GitIgnoreTemplate: opts.GitIgnoreTemplate, LicenseTemplate: opts.LicenseTemplate, IncludeAllBranches: opts.IncludeAllBranches, InitReadme: opts.AddReadme, TemplateRepositoryID: templateRepo.ID, } templateRepoMainBranch := templateRepo.DefaultBranchRef.Name targetRepo := shared.NormalizeRepoName(opts.Name) if idx := strings.IndexRune(opts.Name, '/'); idx > 0 { targetRepo = opts.Name[0:idx+1] + shared.NormalizeRepoName(opts.Name[idx+1:]) } confirmed, err := opts.Prompter.Confirm( fmt.Sprintf(`This will create "%s" as a %s repository on %s. Continue?`, targetRepo, strings.ToLower(opts.Visibility), host), true) if err != nil { return err } else if !confirmed { return cmdutil.CancelError } repo, err := repoCreate(httpClient, repoToCreate.RepoHost(), input) if err != nil { return err } cs := opts.IO.ColorScheme() fmt.Fprintf(opts.IO.Out, "%s Created repository %s on %s\n %s\n", cs.SuccessIconWithColor(cs.Green), ghrepo.FullName(repo), host, repo.URL) opts.Clone, err = opts.Prompter.Confirm("Clone the new repository locally?", true) if err != nil { return err } if opts.Clone { protocol := cfg.GitProtocol(repo.RepoHost()).Value remoteURL := ghrepo.FormatRemoteURL(repo, protocol) if err := cloneWithRetry(opts, remoteURL, templateRepoMainBranch); err != nil { return err } } return nil } // create repo on remote host from existing local repo func createFromLocal(opts *CreateOptions) error { httpClient, err := opts.HttpClient() if err != nil { return err } cs := opts.IO.ColorScheme() isTTY := opts.IO.IsStdoutTTY() stdout := opts.IO.Out cfg, err := opts.Config() if err != nil { return err } host, _ := cfg.Authentication().DefaultHost() if opts.Interactive { var err error opts.Source, err = opts.Prompter.Input("Path to local repository", ".") if err != nil { return err } } repoPath := opts.Source opts.GitClient.RepoDir = repoPath var baseRemote string if opts.Remote == "" { baseRemote = "origin" } else { baseRemote = opts.Remote } absPath, err := filepath.Abs(repoPath) if err != nil { return err } repoType, err := localRepoType(opts.GitClient) if err != nil { return err } if repoType == unknown { if repoPath == "." { return fmt.Errorf("current directory is not a git repository. Run `git init` to initialize it") } return fmt.Errorf("%s is not a git repository. Run `git -C \"%s\" init` to initialize it", absPath, repoPath) } committed, err := hasCommits(opts.GitClient) if err != nil { return err } if opts.Push { // fail immediately if trying to push with no commits if !committed { return fmt.Errorf("`--push` enabled but no commits found in %s", absPath) } } if opts.Interactive { opts.Name, opts.Description, opts.Visibility, err = interactiveRepoInfo(httpClient, host, opts.Prompter, filepath.Base(absPath)) if err != nil { return err } } var repoToCreate ghrepo.Interface // repo name will be currdir name or specified if opts.Name == "" { repoToCreate = ghrepo.NewWithHost("", filepath.Base(absPath), host) } else if strings.Contains(opts.Name, "/") { var err error repoToCreate, err = ghrepo.FromFullName(opts.Name) if err != nil { return fmt.Errorf("argument error: %w", err) } } else { repoToCreate = ghrepo.NewWithHost("", opts.Name, host) } input := repoCreateInput{ Name: repoToCreate.RepoName(), Visibility: opts.Visibility, OwnerLogin: repoToCreate.RepoOwner(), TeamSlug: opts.Team, Description: opts.Description, HomepageURL: opts.Homepage, HasIssuesEnabled: !opts.DisableIssues, HasWikiEnabled: !opts.DisableWiki, GitIgnoreTemplate: opts.GitIgnoreTemplate, LicenseTemplate: opts.LicenseTemplate, } repo, err := repoCreate(httpClient, repoToCreate.RepoHost(), input) if err != nil { return err } if isTTY { fmt.Fprintf(stdout, "%s Created repository %s on %s\n %s\n", cs.SuccessIconWithColor(cs.Green), ghrepo.FullName(repo), host, repo.URL) } else { fmt.Fprintln(stdout, repo.URL) } protocol := cfg.GitProtocol(repo.RepoHost()).Value remoteURL := ghrepo.FormatRemoteURL(repo, protocol) if opts.Interactive { addRemote, err := opts.Prompter.Confirm("Add a remote?", true) if err != nil { return err } if !addRemote { return nil } baseRemote, err = opts.Prompter.Input("What should the new remote be called?", "origin") if err != nil { return err } } if err := sourceInit(opts.GitClient, opts.IO, remoteURL, baseRemote); err != nil { return err } // don't prompt for push if there are no commits if opts.Interactive && committed { msg := fmt.Sprintf("Would you like to push commits from the current branch to %q?", baseRemote) if repoType == bare { msg = fmt.Sprintf("Would you like to mirror all refs to %q?", baseRemote) } var err error opts.Push, err = opts.Prompter.Confirm(msg, true) if err != nil { return err } } if opts.Push && repoType == working { err := opts.GitClient.Push(context.Background(), baseRemote, "HEAD") if err != nil { return err } if isTTY { fmt.Fprintf(stdout, "%s Pushed commits to %s\n", cs.SuccessIcon(), remoteURL) } } if opts.Push && repoType == bare { cmd, err := opts.GitClient.AuthenticatedCommand(context.Background(), git.AllMatchingCredentialsPattern, "push", baseRemote, "--mirror") if err != nil { return err } if err = cmd.Run(); err != nil { return err } if isTTY { fmt.Fprintf(stdout, "%s Mirrored all refs to %s\n", cs.SuccessIcon(), remoteURL) } } return nil } func cloneWithRetry(opts *CreateOptions, remoteURL, branch string) error { // Allow injecting alternative BackOff in tests. if opts.BackOff == nil { opts.BackOff = backoff.NewConstantBackOff(3 * time.Second) } var args []string if branch != "" { args = append(args, "--branch", branch) } ctx := context.Background() return backoff.Retry(func() error { stderr := &bytes.Buffer{} _, err := opts.GitClient.Clone(ctx, remoteURL, args, git.WithStderr(stderr)) var execError errWithExitCode if errors.As(err, &execError) && execError.ExitCode() == 128 { return err } else { _, _ = io.Copy(opts.IO.ErrOut, stderr) } return backoff.Permanent(err) }, backoff.WithContext(backoff.WithMaxRetries(opts.BackOff, 3), ctx)) } func sourceInit(gitClient *git.Client, io *iostreams.IOStreams, remoteURL, baseRemote string) error { cs := io.ColorScheme() remoteAdd, err := gitClient.Command(context.Background(), "remote", "add", baseRemote, remoteURL) if err != nil { return err } _, err = remoteAdd.Output() if err != nil { return fmt.Errorf("%s Unable to add remote %q", cs.FailureIcon(), baseRemote) } if io.IsStdoutTTY() { fmt.Fprintf(io.Out, "%s Added remote %s\n", cs.SuccessIcon(), remoteURL) } return nil } // check if local repository has committed changes func hasCommits(gitClient *git.Client) (bool, error) { hasCommitsCmd, err := gitClient.Command(context.Background(), "rev-parse", "HEAD") if err != nil { return false, err } _, err = hasCommitsCmd.Output() if err == nil { return true, nil } var execError *exec.ExitError if errors.As(err, &execError) { exitCode := int(execError.ExitCode()) if exitCode == 128 { return false, nil } return false, err } return false, nil } type repoType int const ( unknown repoType = iota working bare ) func localRepoType(gitClient *git.Client) (repoType, error) { projectDir, projectDirErr := gitClient.GitDir(context.Background()) if projectDirErr != nil { var execError errWithExitCode if errors.As(projectDirErr, &execError) { if exitCode := int(execError.ExitCode()); exitCode == 128 { return unknown, nil } return unknown, projectDirErr } } switch projectDir { case ".": return bare, nil case ".git": return working, nil default: return unknown, nil } } // clone the checkout branch to specified path func localInit(gitClient *git.Client, remoteURL, path string) error { ctx := context.Background() gitInit, err := gitClient.Command(ctx, "init", path) if err != nil { return err } _, err = gitInit.Output() if err != nil { return err } // Copy the client so we do not modify the original client's RepoDir. gc := gitClient.Copy() gc.RepoDir = path gitRemoteAdd, err := gc.Command(ctx, "remote", "add", "origin", remoteURL) if err != nil { return err } _, err = gitRemoteAdd.Output() if err != nil { return err } return nil } func interactiveRepoTemplate(client *http.Client, hostname, owner string, prompter iprompter) (*api.Repository, error) { templateRepos, err := listTemplateRepositories(client, hostname, owner) if err != nil { return nil, err } if len(templateRepos) == 0 { return nil, fmt.Errorf("%s has no template repositories", owner) } var templates []string for _, repo := range templateRepos { templates = append(templates, repo.Name) } selected, err := prompter.Select("Choose a template repository", "", templates) if err != nil { return nil, err } return &templateRepos[selected], nil } func interactiveGitIgnore(client *http.Client, hostname string, prompter iprompter) (string, error) { confirmed, err := prompter.Confirm("Would you like to add a .gitignore?", false) if err != nil { return "", err } else if !confirmed { return "", nil } templates, err := api.RepoGitIgnoreTemplates(client, hostname) if err != nil { return "", err } selected, err := prompter.Select("Choose a .gitignore template", "", templates) if err != nil { return "", err } return templates[selected], nil } func interactiveLicense(client *http.Client, hostname string, prompter iprompter) (string, error) { confirmed, err := prompter.Confirm("Would you like to add a license?", false) if err != nil { return "", err } else if !confirmed { return "", nil } licenses, err := api.RepoLicenses(client, hostname) if err != nil { return "", err } licenseNames := make([]string, 0, len(licenses)) for _, license := range licenses { licenseNames = append(licenseNames, license.Name) } selected, err := prompter.Select("Choose a license", "", licenseNames) if err != nil { return "", err } return licenses[selected].Key, nil } // name, description, and visibility func interactiveRepoInfo(client *http.Client, hostname string, prompter iprompter, defaultName string) (string, string, string, error) { name, owner, err := interactiveRepoNameAndOwner(client, hostname, prompter, defaultName) if err != nil { return "", "", "", err } if owner != "" { name = fmt.Sprintf("%s/%s", owner, name) } description, err := prompter.Input("Description", "") if err != nil { return "", "", "", err } visibilityOptions := getRepoVisibilityOptions(owner) selected, err := prompter.Select("Visibility", "Public", visibilityOptions) if err != nil { return "", "", "", err } return name, description, strings.ToUpper(visibilityOptions[selected]), nil } func getRepoVisibilityOptions(owner string) []string { visibilityOptions := []string{"Public", "Private"} // orgs can also create internal repos if owner != "" { visibilityOptions = append(visibilityOptions, "Internal") } return visibilityOptions } func interactiveRepoNameAndOwner(client *http.Client, hostname string, prompter iprompter, defaultName string) (string, string, error) { name, err := prompter.Input("Repository name", defaultName) if err != nil { return "", "", err } name, owner, err := splitNameAndOwner(name) if err != nil { return "", "", err } if owner != "" { // User supplied an explicit owner prefix. return name, owner, nil } username, orgs, err := userAndOrgs(client, hostname) if err != nil { return "", "", err } if len(orgs) == 0 { // User doesn't belong to any orgs. // Leave the owner blank to indicate a personal repo. return name, "", nil } owners := append(orgs, username) sort.Strings(owners) selected, err := prompter.Select("Repository owner", username, owners) if err != nil { return "", "", err } owner = owners[selected] if owner == username { // Leave the owner blank to indicate a personal repo. return name, "", nil } return name, owner, nil } func splitNameAndOwner(name string) (string, string, error) { if !strings.Contains(name, "/") { return name, "", nil } repo, err := ghrepo.FromFullName(name) if err != nil { return "", "", fmt.Errorf("argument error: %w", err) } return repo.RepoName(), repo.RepoOwner(), nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/create/create_test.go
pkg/cmd/repo/create/create_test.go
package create import ( "bytes" "fmt" "net/http" "testing" "github.com/cenkalti/backoff/v4" "github.com/cli/cli/v2/git" "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/internal/prompter" "github.com/cli/cli/v2/internal/run" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNewCmdCreate(t *testing.T) { tests := []struct { name string tty bool cli string wantsErr bool errMsg string wantsOpts CreateOptions }{ { name: "no args tty", tty: true, cli: "", wantsOpts: CreateOptions{Interactive: true}, }, { name: "no args no-tty", tty: false, cli: "", wantsErr: true, errMsg: "at least one argument required in non-interactive mode", }, { name: "new repo from remote", cli: "NEWREPO --public --clone", wantsOpts: CreateOptions{ Name: "NEWREPO", Public: true, Clone: true}, }, { name: "no visibility", tty: true, cli: "NEWREPO", wantsErr: true, errMsg: "`--public`, `--private`, or `--internal` required when not running interactively", }, { name: "multiple visibility", tty: true, cli: "NEWREPO --public --private", wantsErr: true, errMsg: "expected exactly one of `--public`, `--private`, or `--internal`", }, { name: "new remote from local", cli: "--source=/path/to/repo --private", wantsOpts: CreateOptions{ Private: true, Source: "/path/to/repo"}, }, { name: "new remote from local with remote", cli: "--source=/path/to/repo --public --remote upstream", wantsOpts: CreateOptions{ Public: true, Source: "/path/to/repo", Remote: "upstream", }, }, { name: "new remote from local with push", cli: "--source=/path/to/repo --push --public", wantsOpts: CreateOptions{ Public: true, Source: "/path/to/repo", Push: true, }, }, { name: "new remote from local without visibility", cli: "--source=/path/to/repo --push", wantsOpts: CreateOptions{ Source: "/path/to/repo", Push: true, }, wantsErr: true, errMsg: "`--public`, `--private`, or `--internal` required when not running interactively", }, { name: "source with template", cli: "--source=/path/to/repo --private --template mytemplate", wantsErr: true, errMsg: "the `--source` option is not supported with `--clone`, `--template`, `--license`, or `--gitignore`", }, { name: "include all branches without template", cli: "--source=/path/to/repo --private --include-all-branches", wantsErr: true, errMsg: "the `--include-all-branches` option is only supported when using `--template`", }, { name: "new remote from template with include all branches", cli: "template-repo --template https://github.com/OWNER/REPO --public --include-all-branches", wantsOpts: CreateOptions{ Name: "template-repo", Public: true, Template: "https://github.com/OWNER/REPO", IncludeAllBranches: true, }, }, { name: "template with .gitignore", cli: "template-repo --template mytemplate --gitignore ../.gitignore --public", wantsErr: true, errMsg: ".gitignore and license templates are not added when template is provided", }, { name: "template with license", cli: "template-repo --template mytemplate --license ../.license --public", wantsErr: true, errMsg: ".gitignore and license templates are not added when template is provided", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() ios.SetStdinTTY(tt.tty) ios.SetStdoutTTY(tt.tty) f := &cmdutil.Factory{ IOStreams: ios, } var opts *CreateOptions cmd := NewCmdCreate(f, func(o *CreateOptions) error { opts = o return nil }) // TODO STUPID HACK // cobra aggressively adds help to all commands. since we're not running through the root command // (which manages help when running for real) and since create has a '-h' flag (for homepage), // cobra blows up when it tried to add a help flag and -h is already in use. This hack adds a // dummy help flag with a random shorthand to get around this. cmd.Flags().BoolP("help", "x", false, "") args, err := shlex.Split(tt.cli) require.NoError(t, err) cmd.SetArgs(args) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) assert.Equal(t, tt.errMsg, err.Error()) return } else { require.NoError(t, err) } assert.Equal(t, tt.wantsOpts.Interactive, opts.Interactive) assert.Equal(t, tt.wantsOpts.Source, opts.Source) assert.Equal(t, tt.wantsOpts.Name, opts.Name) assert.Equal(t, tt.wantsOpts.Public, opts.Public) assert.Equal(t, tt.wantsOpts.Internal, opts.Internal) assert.Equal(t, tt.wantsOpts.Private, opts.Private) assert.Equal(t, tt.wantsOpts.Clone, opts.Clone) }) } } func Test_createRun(t *testing.T) { tests := []struct { name string tty bool opts *CreateOptions httpStubs func(*httpmock.Registry) promptStubs func(*prompter.PrompterMock) execStubs func(*run.CommandStubber) wantStdout string wantErr bool errMsg string }{ { name: "interactive create from scratch with gitignore and license", opts: &CreateOptions{Interactive: true}, tty: true, wantStdout: "✓ Created repository OWNER/REPO on github.com\n https://github.com/OWNER/REPO\n", promptStubs: func(p *prompter.PrompterMock) { p.ConfirmFunc = func(message string, defaultValue bool) (bool, error) { switch message { case "Would you like to add a README file?": return false, nil case "Would you like to add a .gitignore?": return true, nil case "Would you like to add a license?": return true, nil case `This will create "REPO" as a private repository on github.com. Continue?`: return defaultValue, nil case "Clone the new repository locally?": return defaultValue, nil default: return false, fmt.Errorf("unexpected confirm prompt: %s", message) } } p.InputFunc = func(message, defaultValue string) (string, error) { switch message { case "Repository name": return "REPO", nil case "Description": return "my new repo", nil default: return "", fmt.Errorf("unexpected input prompt: %s", message) } } p.SelectFunc = func(message, defaultValue string, options []string) (int, error) { switch message { case "What would you like to do?": return prompter.IndexFor(options, "Create a new repository on github.com from scratch") case "Visibility": return prompter.IndexFor(options, "Private") case "Choose a license": return prompter.IndexFor(options, "GNU Lesser General Public License v3.0") case "Choose a .gitignore template": return prompter.IndexFor(options, "Go") default: return 0, fmt.Errorf("unexpected select prompt: %s", message) } } }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data":{"viewer":{"login":"someuser","organizations":{"nodes": []}}}}`)) reg.Register( httpmock.REST("GET", "gitignore/templates"), httpmock.StringResponse(`["Actionscript","Android","AppceleratorTitanium","Autotools","Bancha","C","C++","Go"]`)) reg.Register( httpmock.REST("GET", "licenses"), httpmock.StringResponse(`[{"key": "mit","name": "MIT License"},{"key": "lgpl-3.0","name": "GNU Lesser General Public License v3.0"}]`)) reg.Register( httpmock.REST("POST", "user/repos"), httpmock.StringResponse(`{"name":"REPO", "owner":{"login": "OWNER"}, "html_url":"https://github.com/OWNER/REPO"}`)) }, execStubs: func(cs *run.CommandStubber) { cs.Register(`git clone https://github.com/OWNER/REPO.git`, 0, "") }, }, { name: "interactive create from scratch but with prompted owner", opts: &CreateOptions{Interactive: true}, tty: true, wantStdout: "✓ Created repository org1/REPO on github.com\n https://github.com/org1/REPO\n", promptStubs: func(p *prompter.PrompterMock) { p.ConfirmFunc = func(message string, defaultValue bool) (bool, error) { switch message { case "Would you like to add a README file?": return false, nil case "Would you like to add a .gitignore?": return false, nil case "Would you like to add a license?": return false, nil case `This will create "org1/REPO" as a private repository on github.com. Continue?`: return true, nil case "Clone the new repository locally?": return false, nil default: return false, fmt.Errorf("unexpected confirm prompt: %s", message) } } p.InputFunc = func(message, defaultValue string) (string, error) { switch message { case "Repository name": return "REPO", nil case "Description": return "my new repo", nil default: return "", fmt.Errorf("unexpected input prompt: %s", message) } } p.SelectFunc = func(message, defaultValue string, options []string) (int, error) { switch message { case "Repository owner": return prompter.IndexFor(options, "org1") case "What would you like to do?": return prompter.IndexFor(options, "Create a new repository on github.com from scratch") case "Visibility": return prompter.IndexFor(options, "Private") default: return 0, fmt.Errorf("unexpected select prompt: %s", message) } } }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data":{"viewer":{"login":"someuser","organizations":{"nodes": [{"login": "org1"}, {"login": "org2"}]}}}}`)) reg.Register( httpmock.REST("GET", "users/org1"), httpmock.StringResponse(`{"login":"org1","type":"Organization"}`)) reg.Register( httpmock.GraphQL(`mutation RepositoryCreate\b`), httpmock.StringResponse(` { "data": { "createRepository": { "repository": { "id": "REPOID", "name": "REPO", "owner": {"login":"org1"}, "url": "https://github.com/org1/REPO" } } } }`)) }, }, { name: "interactive create from scratch but cancel before submit", opts: &CreateOptions{Interactive: true}, tty: true, promptStubs: func(p *prompter.PrompterMock) { p.ConfirmFunc = func(message string, defaultValue bool) (bool, error) { switch message { case "Would you like to add a README file?": return false, nil case "Would you like to add a .gitignore?": return false, nil case "Would you like to add a license?": return false, nil case `This will create "REPO" as a private repository on github.com. Continue?`: return false, nil default: return false, fmt.Errorf("unexpected confirm prompt: %s", message) } } p.InputFunc = func(message, defaultValue string) (string, error) { switch message { case "Repository name": return "REPO", nil case "Description": return "my new repo", nil default: return "", fmt.Errorf("unexpected input prompt: %s", message) } } p.SelectFunc = func(message, defaultValue string, options []string) (int, error) { switch message { case "What would you like to do?": return prompter.IndexFor(options, "Create a new repository on github.com from scratch") case "Visibility": return prompter.IndexFor(options, "Private") default: return 0, fmt.Errorf("unexpected select prompt: %s", message) } } }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data":{"viewer":{"login":"someuser","organizations":{"nodes": []}}}}`)) }, wantStdout: "", wantErr: true, errMsg: "CancelError", }, { name: "interactive with existing repository public", opts: &CreateOptions{Interactive: true}, tty: true, promptStubs: func(p *prompter.PrompterMock) { p.ConfirmFunc = func(message string, defaultValue bool) (bool, error) { switch message { case "Add a remote?": return false, nil default: return false, fmt.Errorf("unexpected confirm prompt: %s", message) } } p.InputFunc = func(message, defaultValue string) (string, error) { switch message { case "Path to local repository": return defaultValue, nil case "Repository name": return "REPO", nil case "Description": return "my new repo", nil default: return "", fmt.Errorf("unexpected input prompt: %s", message) } } p.SelectFunc = func(message, defaultValue string, options []string) (int, error) { switch message { case "What would you like to do?": return prompter.IndexFor(options, "Push an existing local repository to github.com") case "Visibility": return prompter.IndexFor(options, "Private") default: return 0, fmt.Errorf("unexpected select prompt: %s", message) } } }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data":{"viewer":{"login":"someuser","organizations":{"nodes": []}}}}`)) reg.Register( httpmock.GraphQL(`mutation RepositoryCreate\b`), httpmock.StringResponse(` { "data": { "createRepository": { "repository": { "id": "REPOID", "name": "REPO", "owner": {"login":"OWNER"}, "url": "https://github.com/OWNER/REPO" } } } }`)) }, execStubs: func(cs *run.CommandStubber) { cs.Register(`git -C . rev-parse --git-dir`, 0, ".git") cs.Register(`git -C . rev-parse HEAD`, 0, "commithash") }, wantStdout: "✓ Created repository OWNER/REPO on github.com\n https://github.com/OWNER/REPO\n", }, { name: "interactive with existing bare repository public and push", opts: &CreateOptions{Interactive: true}, tty: true, promptStubs: func(p *prompter.PrompterMock) { p.ConfirmFunc = func(message string, defaultValue bool) (bool, error) { switch message { case "Add a remote?": return true, nil case `Would you like to mirror all refs to "origin"?`: return true, nil default: return false, fmt.Errorf("unexpected confirm prompt: %s", message) } } p.InputFunc = func(message, defaultValue string) (string, error) { switch message { case "Path to local repository": return defaultValue, nil case "Repository name": return "REPO", nil case "Description": return "my new repo", nil case "What should the new remote be called?": return defaultValue, nil default: return "", fmt.Errorf("unexpected input prompt: %s", message) } } p.SelectFunc = func(message, defaultValue string, options []string) (int, error) { switch message { case "What would you like to do?": return prompter.IndexFor(options, "Push an existing local repository to github.com") case "Visibility": return prompter.IndexFor(options, "Private") default: return 0, fmt.Errorf("unexpected select prompt: %s", message) } } }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data":{"viewer":{"login":"someuser","organizations":{"nodes": []}}}}`)) reg.Register( httpmock.GraphQL(`mutation RepositoryCreate\b`), httpmock.StringResponse(` { "data": { "createRepository": { "repository": { "id": "REPOID", "name": "REPO", "owner": {"login":"OWNER"}, "url": "https://github.com/OWNER/REPO" } } } }`)) }, execStubs: func(cs *run.CommandStubber) { cs.Register(`git -C . rev-parse --git-dir`, 0, ".") cs.Register(`git -C . rev-parse HEAD`, 0, "commithash") cs.Register(`git -C . remote add origin https://github.com/OWNER/REPO`, 0, "") cs.Register(`git -C . push origin --mirror`, 0, "") }, wantStdout: "✓ Created repository OWNER/REPO on github.com\n https://github.com/OWNER/REPO\n✓ Added remote https://github.com/OWNER/REPO.git\n✓ Mirrored all refs to https://github.com/OWNER/REPO.git\n", }, { name: "interactive with existing repository public add remote and push", opts: &CreateOptions{Interactive: true}, tty: true, promptStubs: func(p *prompter.PrompterMock) { p.ConfirmFunc = func(message string, defaultValue bool) (bool, error) { switch message { case "Add a remote?": return true, nil case `Would you like to push commits from the current branch to "origin"?`: return true, nil default: return false, fmt.Errorf("unexpected confirm prompt: %s", message) } } p.InputFunc = func(message, defaultValue string) (string, error) { switch message { case "Path to local repository": return defaultValue, nil case "Repository name": return "REPO", nil case "Description": return "my new repo", nil case "What should the new remote be called?": return defaultValue, nil default: return "", fmt.Errorf("unexpected input prompt: %s", message) } } p.SelectFunc = func(message, defaultValue string, options []string) (int, error) { switch message { case "What would you like to do?": return prompter.IndexFor(options, "Push an existing local repository to github.com") case "Visibility": return prompter.IndexFor(options, "Private") default: return 0, fmt.Errorf("unexpected select prompt: %s", message) } } }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data":{"viewer":{"login":"someuser","organizations":{"nodes": []}}}}`)) reg.Register( httpmock.GraphQL(`mutation RepositoryCreate\b`), httpmock.StringResponse(` { "data": { "createRepository": { "repository": { "id": "REPOID", "name": "REPO", "owner": {"login":"OWNER"}, "url": "https://github.com/OWNER/REPO" } } } }`)) }, execStubs: func(cs *run.CommandStubber) { cs.Register(`git -C . rev-parse --git-dir`, 0, ".git") cs.Register(`git -C . rev-parse HEAD`, 0, "commithash") cs.Register(`git -C . remote add origin https://github.com/OWNER/REPO`, 0, "") cs.Register(`git -C . push --set-upstream origin HEAD`, 0, "") }, wantStdout: "✓ Created repository OWNER/REPO on github.com\n https://github.com/OWNER/REPO\n✓ Added remote https://github.com/OWNER/REPO.git\n✓ Pushed commits to https://github.com/OWNER/REPO.git\n", }, { name: "interactive create from a template repository", opts: &CreateOptions{Interactive: true}, tty: true, promptStubs: func(p *prompter.PrompterMock) { p.ConfirmFunc = func(message string, defaultValue bool) (bool, error) { switch message { case `This will create "OWNER/REPO" as a private repository on github.com. Continue?`: return defaultValue, nil case "Clone the new repository locally?": return defaultValue, nil default: return false, fmt.Errorf("unexpected confirm prompt: %s", message) } } p.InputFunc = func(message, defaultValue string) (string, error) { switch message { case "Repository name": return "REPO", nil case "Description": return "my new repo", nil default: return "", fmt.Errorf("unexpected input prompt: %s", message) } } p.SelectFunc = func(message, defaultValue string, options []string) (int, error) { switch message { case "Repository owner": return prompter.IndexFor(options, "OWNER") case "Choose a template repository": return prompter.IndexFor(options, "REPO") case "What would you like to do?": return prompter.IndexFor(options, "Create a new repository on github.com from a template repository") case "Visibility": return prompter.IndexFor(options, "Private") default: return 0, fmt.Errorf("unexpected select prompt: %s", message) } } }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data":{"viewer":{"login":"OWNER","organizations":{"nodes": []}}}}`)) reg.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data":{"viewer":{"login":"OWNER","organizations":{"nodes": []}}}}`)) reg.Register( httpmock.GraphQL(`query RepositoryList\b`), httpmock.FileResponse("./fixtures/repoTempList.json")) reg.Register( httpmock.REST("GET", "users/OWNER"), httpmock.StringResponse(`{"login":"OWNER","type":"User"}`)) reg.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data":{"viewer":{"id":"OWNER"}}}`)) reg.Register( httpmock.GraphQL(`mutation CloneTemplateRepository\b`), httpmock.StringResponse(` { "data": { "cloneTemplateRepository": { "repository": { "id": "REPOID", "name": "REPO", "owner": {"login":"OWNER"}, "url": "https://github.com/OWNER/REPO" } } } }`)) }, execStubs: func(cs *run.CommandStubber) { cs.Register(`git clone --branch main https://github.com/OWNER/REPO`, 0, "") }, wantStdout: "✓ Created repository OWNER/REPO on github.com\n https://github.com/OWNER/REPO\n", }, { name: "interactive create from template repo but there are no template repos", opts: &CreateOptions{Interactive: true}, tty: true, promptStubs: func(p *prompter.PrompterMock) { p.ConfirmFunc = func(message string, defaultValue bool) (bool, error) { switch message { default: return false, fmt.Errorf("unexpected confirm prompt: %s", message) } } p.InputFunc = func(message, defaultValue string) (string, error) { switch message { case "Repository name": return "REPO", nil case "Description": return "my new repo", nil default: return "", fmt.Errorf("unexpected input prompt: %s", message) } } p.SelectFunc = func(message, defaultValue string, options []string) (int, error) { switch message { case "What would you like to do?": return prompter.IndexFor(options, "Create a new repository on github.com from a template repository") case "Visibility": return prompter.IndexFor(options, "Private") default: return 0, fmt.Errorf("unexpected select prompt: %s", message) } } }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data":{"viewer":{"login":"OWNER","organizations":{"nodes": []}}}}`)) reg.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data":{"viewer":{"login":"OWNER","organizations":{"nodes": []}}}}`)) reg.Register( httpmock.GraphQL(`query RepositoryList\b`), httpmock.StringResponse(`{"data":{"repositoryOwner":{"login":"OWNER","repositories":{"nodes":[]},"totalCount":0,"pageInfo":{"hasNextPage":false,"endCursor":""}}}}`)) }, execStubs: func(cs *run.CommandStubber) {}, wantStdout: "", wantErr: true, errMsg: "OWNER has no template repositories", }, { name: "noninteractive create from scratch", opts: &CreateOptions{ Interactive: false, Name: "REPO", Visibility: "PRIVATE", }, tty: false, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`mutation RepositoryCreate\b`), httpmock.StringResponse(` { "data": { "createRepository": { "repository": { "id": "REPOID", "name": "REPO", "owner": {"login":"OWNER"}, "url": "https://github.com/OWNER/REPO" } } } }`)) }, wantStdout: "https://github.com/OWNER/REPO\n", }, { name: "noninteractive create from source", opts: &CreateOptions{ Interactive: false, Source: ".", Name: "REPO", Visibility: "PRIVATE", }, tty: false, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`mutation RepositoryCreate\b`), httpmock.StringResponse(` { "data": { "createRepository": { "repository": { "id": "REPOID", "name": "REPO", "owner": {"login":"OWNER"}, "url": "https://github.com/OWNER/REPO" } } } }`)) }, execStubs: func(cs *run.CommandStubber) { cs.Register(`git -C . rev-parse --git-dir`, 0, ".git") cs.Register(`git -C . rev-parse HEAD`, 0, "commithash") cs.Register(`git -C . remote add origin https://github.com/OWNER/REPO`, 0, "") }, wantStdout: "https://github.com/OWNER/REPO\n", }, { name: "noninteractive create bare from source and push", opts: &CreateOptions{ Interactive: false, Source: ".", Push: true, Name: "REPO", Visibility: "PRIVATE", }, tty: false, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`mutation RepositoryCreate\b`), httpmock.StringResponse(` { "data": { "createRepository": { "repository": { "id": "REPOID", "name": "REPO", "owner": {"login":"OWNER"}, "url": "https://github.com/OWNER/REPO" } } } }`)) }, execStubs: func(cs *run.CommandStubber) { cs.Register(`git -C . rev-parse --git-dir`, 0, ".") cs.Register(`git -C . rev-parse HEAD`, 0, "commithash") cs.Register(`git -C . remote add origin https://github.com/OWNER/REPO`, 0, "") cs.Register(`git -C . push origin --mirror`, 0, "") }, wantStdout: "https://github.com/OWNER/REPO\n", }, { name: "noninteractive create from cwd that isn't a git repo", opts: &CreateOptions{ Interactive: false, Source: ".", Name: "REPO", Visibility: "PRIVATE", }, tty: false, execStubs: func(cs *run.CommandStubber) { cs.Register(`git -C . rev-parse --git-dir`, 128, "") }, wantErr: true, errMsg: "current directory is not a git repository. Run `git init` to initialize it", }, { name: "noninteractive create from cwd that isn't a git repo", opts: &CreateOptions{ Interactive: false, Source: "some-dir", Name: "REPO", Visibility: "PRIVATE", }, tty: false, execStubs: func(cs *run.CommandStubber) { cs.Register(`git -C some-dir rev-parse --git-dir`, 128, "") }, wantErr: true, errMsg: "some-dir is not a git repository. Run `git -C \"some-dir\" init` to initialize it", }, { name: "noninteractive clone from scratch", opts: &CreateOptions{ Interactive: false, Name: "REPO", Visibility: "PRIVATE", Clone: true, }, tty: false, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`mutation RepositoryCreate\b`), httpmock.StringResponse(` { "data": { "createRepository": { "repository": { "id": "REPOID", "name": "REPO", "owner": {"login":"OWNER"}, "url": "https://github.com/OWNER/REPO" } } } }`)) }, execStubs: func(cs *run.CommandStubber) { cs.Register(`git init REPO`, 0, "") cs.Register(`git -C REPO remote add origin https://github.com/OWNER/REPO`, 0, "") }, wantStdout: "https://github.com/OWNER/REPO\n", }, { name: "noninteractive clone with readme", opts: &CreateOptions{ Interactive: false, Name: "ElliotAlderson", Visibility: "PRIVATE", Clone: true, AddReadme: true, }, tty: false, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("POST", "user/repos"), httpmock.RESTPayload(200, "{\"name\":\"ElliotAlderson\", \"owner\":{\"login\": \"OWNER\"}, \"html_url\":\"https://github.com/OWNER/ElliotAlderson\"}", func(payload map[string]interface{}) { payload["name"] = "ElliotAlderson" payload["owner"] = map[string]interface{}{"login": "OWNER"} payload["auto_init"] = true payload["private"] = true }, ), ) }, execStubs: func(cs *run.CommandStubber) { cs.Register(`git clone https://github.com/OWNER/ElliotAlderson`, 128, "") cs.Register(`git clone https://github.com/OWNER/ElliotAlderson`, 0, "") }, wantStdout: "https://github.com/OWNER/ElliotAlderson\n", }, { name: "noninteractive create from template with retry", opts: &CreateOptions{ Interactive: false, Name: "REPO", Visibility: "PRIVATE", Clone: true, Template: "mytemplate", BackOff: &backoff.ZeroBackOff{}, }, tty: false, httpStubs: func(reg *httpmock.Registry) { // Test resolving repo owner from repo name only. reg.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data":{"viewer":{"login":"OWNER"}}}`)) reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.GraphQLQuery(`{ "data": { "repository": { "id": "REPOID", "defaultBranchRef": { "name": "main" } } } }`, func(s string, m map[string]interface{}) { assert.Equal(t, "OWNER", m["owner"]) assert.Equal(t, "mytemplate", m["name"]) }), ) reg.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data":{"viewer":{"id":"OWNERID"}}}`)) reg.Register( httpmock.GraphQL(`mutation CloneTemplateRepository\b`), httpmock.GraphQLMutation(` { "data": { "cloneTemplateRepository": { "repository": { "id": "REPOID", "name": "REPO", "owner": {"login":"OWNER"}, "url": "https://github.com/OWNER/REPO" } } } }`, func(m map[string]interface{}) { assert.Equal(t, "REPOID", m["repositoryId"]) })) }, execStubs: func(cs *run.CommandStubber) { // fatal: Remote branch main not found in upstream origin cs.Register(`git clone --branch main https://github.com/OWNER/REPO`, 128, "") cs.Register(`git clone --branch main https://github.com/OWNER/REPO`, 0, "") }, wantStdout: "https://github.com/OWNER/REPO\n", }, { name: "interactive create from scratch with host override", opts: &CreateOptions{ Interactive: true, Config: func() (gh.Config, error) { cfg := &ghmock.ConfigMock{ AuthenticationFunc: func() gh.AuthConfig { authCfg := &config.AuthConfig{} authCfg.SetHosts([]string{"example.com"}) authCfg.SetDefaultHost("example.com", "GH_HOST") return authCfg }, } return cfg, nil }, }, tty: true, promptStubs: func(p *prompter.PrompterMock) { p.ConfirmFunc = func(message string, defaultValue bool) (bool, error) { switch message { case "Would you like to add a README file?": return false, nil case "Would you like to add a .gitignore?": return false, nil case "Would you like to add a license?": return false, nil case `This will create "REPO" as a private repository on example.com. Continue?`: return defaultValue, nil case "Clone the new repository locally?": return false, nil default: return false, fmt.Errorf("unexpected confirm prompt: %s", message) } } p.InputFunc = func(message, defaultValue string) (string, error) { switch message { case "Repository name": return "REPO", nil case "Description": return "my new repo", nil
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
true
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/create/http_test.go
pkg/cmd/repo/create/http_test.go
package create import ( "net/http" "testing" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/httpmock" "github.com/stretchr/testify/assert" ) func Test_repoCreate(t *testing.T) { tests := []struct { name string hostname string input repoCreateInput stubs func(t *testing.T, r *httpmock.Registry) wantErr bool errMsg string wantRepo string }{ { name: "create personal repository", hostname: "github.com", input: repoCreateInput{ Name: "winter-foods", Description: "roasted chestnuts", HomepageURL: "http://example.com", Visibility: "public", HasIssuesEnabled: true, HasWikiEnabled: true, }, stubs: func(t *testing.T, r *httpmock.Registry) { r.Register( httpmock.GraphQL(`mutation RepositoryCreate\b`), httpmock.GraphQLMutation( `{ "data": { "createRepository": { "repository": { "id": "REPOID", "name": "REPO", "owner": {"login":"OWNER"}, "url": "the://URL" } } } }`, func(inputs map[string]interface{}) { assert.Equal(t, map[string]interface{}{ "name": "winter-foods", "description": "roasted chestnuts", "homepageUrl": "http://example.com", "visibility": "PUBLIC", "hasIssuesEnabled": true, "hasWikiEnabled": true, }, inputs) }), ) }, wantRepo: "https://github.com/OWNER/REPO", }, { name: "create Enterprise repository", hostname: "example.com", input: repoCreateInput{ Name: "winter-foods", Description: "roasted chestnuts", HomepageURL: "http://example.com", Visibility: "public", HasIssuesEnabled: true, HasWikiEnabled: true, }, stubs: func(t *testing.T, r *httpmock.Registry) { r.Register( httpmock.GraphQL(`mutation RepositoryCreate\b`), httpmock.GraphQLMutation( `{ "data": { "createRepository": { "repository": { "id": "REPOID", "name": "REPO", "owner": {"login":"OWNER"}, "url": "the://URL" } } } }`, func(inputs map[string]interface{}) { assert.Equal(t, map[string]interface{}{ "name": "winter-foods", "description": "roasted chestnuts", "homepageUrl": "http://example.com", "visibility": "PUBLIC", "hasIssuesEnabled": true, "hasWikiEnabled": true, }, inputs) }), ) }, wantRepo: "https://example.com/OWNER/REPO", }, { name: "create in organization", hostname: "github.com", input: repoCreateInput{ Name: "crisps", Visibility: "internal", OwnerLogin: "snacks-inc", HasIssuesEnabled: true, HasWikiEnabled: true, }, stubs: func(t *testing.T, r *httpmock.Registry) { r.Register( httpmock.REST("GET", "users/snacks-inc"), httpmock.StringResponse(`{ "node_id": "ORGID", "type": "Organization" }`)) r.Register( httpmock.GraphQL(`mutation RepositoryCreate\b`), httpmock.GraphQLMutation( `{ "data": { "createRepository": { "repository": { "id": "REPOID", "name": "REPO", "owner": {"login":"OWNER"}, "url": "the://URL" } } } }`, func(inputs map[string]interface{}) { assert.Equal(t, map[string]interface{}{ "name": "crisps", "visibility": "INTERNAL", "ownerId": "ORGID", "hasIssuesEnabled": true, "hasWikiEnabled": true, }, inputs) }), ) }, wantRepo: "https://github.com/OWNER/REPO", }, { name: "create for team", hostname: "github.com", input: repoCreateInput{ Name: "crisps", Visibility: "internal", OwnerLogin: "snacks-inc", TeamSlug: "munchies", HasIssuesEnabled: true, HasWikiEnabled: true, }, stubs: func(t *testing.T, r *httpmock.Registry) { r.Register( httpmock.REST("GET", "orgs/snacks-inc/teams/munchies"), httpmock.StringResponse(`{ "node_id": "TEAMID", "id": 1234, "organization": {"node_id": "ORGID"} }`)) r.Register( httpmock.GraphQL(`mutation RepositoryCreate\b`), httpmock.GraphQLMutation( `{ "data": { "createRepository": { "repository": { "id": "REPOID", "name": "REPO", "owner": {"login":"OWNER"}, "url": "the://URL" } } } }`, func(inputs map[string]interface{}) { assert.Equal(t, map[string]interface{}{ "name": "crisps", "visibility": "INTERNAL", "ownerId": "ORGID", "teamId": "TEAMID", "hasIssuesEnabled": true, "hasWikiEnabled": true, }, inputs) }), ) }, wantRepo: "https://github.com/OWNER/REPO", }, { name: "create personal repo from template repo", hostname: "github.com", input: repoCreateInput{ Name: "gen-project", Description: "my generated project", Visibility: "private", TemplateRepositoryID: "TPLID", HasIssuesEnabled: true, HasWikiEnabled: true, IncludeAllBranches: false, }, stubs: func(t *testing.T, r *httpmock.Registry) { r.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data": {"viewer": {"id":"USERID"} } }`)) r.Register( httpmock.GraphQL(`mutation CloneTemplateRepository\b`), httpmock.GraphQLMutation( `{ "data": { "cloneTemplateRepository": { "repository": { "id": "REPOID", "name": "REPO", "owner": {"login":"OWNER"}, "url": "the://URL" } } } }`, func(inputs map[string]interface{}) { assert.Equal(t, map[string]interface{}{ "name": "gen-project", "description": "my generated project", "visibility": "PRIVATE", "ownerId": "USERID", "repositoryId": "TPLID", "includeAllBranches": false, }, inputs) }), ) }, wantRepo: "https://github.com/OWNER/REPO", }, { name: "create personal repo from template repo, and disable wiki", hostname: "github.com", input: repoCreateInput{ Name: "gen-project", Description: "my generated project", Visibility: "private", TemplateRepositoryID: "TPLID", HasIssuesEnabled: true, HasWikiEnabled: false, IncludeAllBranches: false, }, stubs: func(t *testing.T, r *httpmock.Registry) { r.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data": {"viewer": {"id":"USERID"} } }`)) r.Register( httpmock.GraphQL(`mutation CloneTemplateRepository\b`), httpmock.GraphQLMutation( `{ "data": { "cloneTemplateRepository": { "repository": { "id": "REPOID", "name": "REPO", "owner": {"login":"OWNER"}, "url": "the://URL" } } } }`, func(inputs map[string]interface{}) { assert.Equal(t, map[string]interface{}{ "name": "gen-project", "description": "my generated project", "visibility": "PRIVATE", "ownerId": "USERID", "repositoryId": "TPLID", "includeAllBranches": false, }, inputs) }), ) r.Register( httpmock.GraphQL(`mutation UpdateRepository\b`), httpmock.GraphQLMutation( `{ "data": { "updateRepository": { "repository": { "id": "REPOID" } } } }`, func(inputs map[string]interface{}) { assert.Equal(t, map[string]interface{}{ "repositoryId": "REPOID", "hasIssuesEnabled": true, "hasWikiEnabled": false, }, inputs) }), ) }, wantRepo: "https://github.com/OWNER/REPO", }, { name: "create personal repo from template repo, and disable issues", hostname: "github.com", input: repoCreateInput{ Name: "gen-project", Description: "my generated project", Visibility: "private", TemplateRepositoryID: "TPLID", HasIssuesEnabled: false, HasWikiEnabled: true, IncludeAllBranches: false, }, stubs: func(t *testing.T, r *httpmock.Registry) { r.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data": {"viewer": {"id":"USERID"} } }`)) r.Register( httpmock.GraphQL(`mutation CloneTemplateRepository\b`), httpmock.GraphQLMutation( `{ "data": { "cloneTemplateRepository": { "repository": { "id": "REPOID", "name": "REPO", "owner": {"login":"OWNER"}, "url": "the://URL" } } } }`, func(inputs map[string]interface{}) { assert.Equal(t, map[string]interface{}{ "name": "gen-project", "description": "my generated project", "visibility": "PRIVATE", "ownerId": "USERID", "repositoryId": "TPLID", "includeAllBranches": false, }, inputs) }), ) r.Register( httpmock.GraphQL(`mutation UpdateRepository\b`), httpmock.GraphQLMutation( `{ "data": { "updateRepository": { "repository": { "id": "REPOID" } } } }`, func(inputs map[string]interface{}) { assert.Equal(t, map[string]interface{}{ "repositoryId": "REPOID", "hasIssuesEnabled": false, "hasWikiEnabled": true, }, inputs) }), ) }, wantRepo: "https://github.com/OWNER/REPO", }, { name: "create personal repo from template repo, and disable both wiki and issues", hostname: "github.com", input: repoCreateInput{ Name: "gen-project", Description: "my generated project", Visibility: "private", TemplateRepositoryID: "TPLID", HasIssuesEnabled: false, HasWikiEnabled: false, IncludeAllBranches: false, }, stubs: func(t *testing.T, r *httpmock.Registry) { r.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data": {"viewer": {"id":"USERID"} } }`)) r.Register( httpmock.GraphQL(`mutation CloneTemplateRepository\b`), httpmock.GraphQLMutation( `{ "data": { "cloneTemplateRepository": { "repository": { "id": "REPOID", "name": "REPO", "owner": {"login":"OWNER"}, "url": "the://URL" } } } }`, func(inputs map[string]interface{}) { assert.Equal(t, map[string]interface{}{ "name": "gen-project", "description": "my generated project", "visibility": "PRIVATE", "ownerId": "USERID", "repositoryId": "TPLID", "includeAllBranches": false, }, inputs) }), ) r.Register( httpmock.GraphQL(`mutation UpdateRepository\b`), httpmock.GraphQLMutation( `{ "data": { "updateRepository": { "repository": { "id": "REPOID" } } } }`, func(inputs map[string]interface{}) { assert.Equal(t, map[string]interface{}{ "repositoryId": "REPOID", "hasIssuesEnabled": false, "hasWikiEnabled": false, }, inputs) }), ) }, wantRepo: "https://github.com/OWNER/REPO", }, { name: "create personal repo from template repo, and set homepage url", hostname: "github.com", input: repoCreateInput{ Name: "gen-project", Description: "my generated project", Visibility: "private", TemplateRepositoryID: "TPLID", HasIssuesEnabled: true, HasWikiEnabled: true, IncludeAllBranches: false, HomepageURL: "https://example.com", }, stubs: func(t *testing.T, r *httpmock.Registry) { r.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data": {"viewer": {"id":"USERID"} } }`)) r.Register( httpmock.GraphQL(`mutation CloneTemplateRepository\b`), httpmock.GraphQLMutation( `{ "data": { "cloneTemplateRepository": { "repository": { "id": "REPOID", "name": "REPO", "owner": {"login":"OWNER"}, "url": "the://URL" } } } }`, func(inputs map[string]interface{}) { assert.Equal(t, map[string]interface{}{ "name": "gen-project", "description": "my generated project", "visibility": "PRIVATE", "ownerId": "USERID", "repositoryId": "TPLID", "includeAllBranches": false, }, inputs) }), ) r.Register( httpmock.GraphQL(`mutation UpdateRepository\b`), httpmock.GraphQLMutation( `{ "data": { "updateRepository": { "repository": { "id": "REPOID" } } } }`, func(inputs map[string]interface{}) { assert.Equal(t, map[string]interface{}{ "repositoryId": "REPOID", "hasIssuesEnabled": true, "hasWikiEnabled": true, "homepageUrl": "https://example.com", }, inputs) }), ) }, wantRepo: "https://github.com/OWNER/REPO", }, { name: "create org repo from template repo", hostname: "github.com", input: repoCreateInput{ Name: "gen-project", Description: "my generated project", Visibility: "internal", OwnerLogin: "myorg", TemplateRepositoryID: "TPLID", HasIssuesEnabled: true, HasWikiEnabled: true, IncludeAllBranches: false, }, stubs: func(t *testing.T, r *httpmock.Registry) { r.Register( httpmock.REST("GET", "users/myorg"), httpmock.StringResponse(`{ "node_id": "ORGID", "type": "Organization" }`)) r.Register( httpmock.GraphQL(`mutation CloneTemplateRepository\b`), httpmock.GraphQLMutation( `{ "data": { "cloneTemplateRepository": { "repository": { "id": "REPOID", "name": "REPO", "owner": {"login":"OWNER"}, "url": "the://URL" } } } }`, func(inputs map[string]interface{}) { assert.Equal(t, map[string]interface{}{ "name": "gen-project", "description": "my generated project", "visibility": "INTERNAL", "ownerId": "ORGID", "repositoryId": "TPLID", "includeAllBranches": false, }, inputs) }), ) }, wantRepo: "https://github.com/OWNER/REPO", }, { name: "create with license and gitignore", hostname: "github.com", input: repoCreateInput{ Name: "crisps", Visibility: "private", LicenseTemplate: "lgpl-3.0", GitIgnoreTemplate: "Go", HasIssuesEnabled: true, HasWikiEnabled: true, }, stubs: func(t *testing.T, r *httpmock.Registry) { r.Register( httpmock.REST("POST", "user/repos"), httpmock.RESTPayload(201, `{"name":"crisps", "owner":{"login": "snacks-inc"}, "html_url":"the://URL"}`, func(payload map[string]interface{}) { assert.Equal(t, map[string]interface{}{ "name": "crisps", "private": true, "gitignore_template": "Go", "license_template": "lgpl-3.0", "has_issues": true, "has_wiki": true, }, payload) })) }, wantRepo: "https://github.com/snacks-inc/crisps", }, { name: "create with README", hostname: "github.com", input: repoCreateInput{ Name: "crisps", InitReadme: true, }, stubs: func(t *testing.T, r *httpmock.Registry) { r.Register( httpmock.REST("POST", "user/repos"), httpmock.RESTPayload(201, `{"name":"crisps", "owner":{"login": "snacks-inc"}, "html_url":"the://URL"}`, func(payload map[string]interface{}) { assert.Equal(t, map[string]interface{}{ "name": "crisps", "private": false, "has_issues": false, "has_wiki": false, "auto_init": true, }, payload) })) }, wantRepo: "https://github.com/snacks-inc/crisps", }, { name: "create with license and gitignore on Enterprise", hostname: "example.com", input: repoCreateInput{ Name: "crisps", Visibility: "private", LicenseTemplate: "lgpl-3.0", GitIgnoreTemplate: "Go", HasIssuesEnabled: true, HasWikiEnabled: true, }, stubs: func(t *testing.T, r *httpmock.Registry) { r.Register( httpmock.REST("POST", "api/v3/user/repos"), httpmock.RESTPayload(201, `{"name":"crisps", "owner":{"login": "snacks-inc"}, "html_url":"the://URL"}`, func(payload map[string]interface{}) { assert.Equal(t, map[string]interface{}{ "name": "crisps", "private": true, "gitignore_template": "Go", "license_template": "lgpl-3.0", "has_issues": true, "has_wiki": true, }, payload) })) }, wantRepo: "https://example.com/snacks-inc/crisps", }, { name: "create with license and gitignore in org", hostname: "github.com", input: repoCreateInput{ Name: "crisps", Visibility: "INTERNAL", OwnerLogin: "snacks-inc", LicenseTemplate: "lgpl-3.0", GitIgnoreTemplate: "Go", HasIssuesEnabled: true, HasWikiEnabled: true, }, stubs: func(t *testing.T, r *httpmock.Registry) { r.Register( httpmock.REST("GET", "users/snacks-inc"), httpmock.StringResponse(`{ "node_id": "ORGID", "type": "Organization" }`)) r.Register( httpmock.REST("POST", "orgs/snacks-inc/repos"), httpmock.RESTPayload(201, `{"name":"crisps", "owner":{"login": "snacks-inc"}, "html_url":"the://URL"}`, func(payload map[string]interface{}) { assert.Equal(t, map[string]interface{}{ "name": "crisps", "private": false, "visibility": "internal", "gitignore_template": "Go", "license_template": "lgpl-3.0", "has_issues": true, "has_wiki": true, }, payload) })) }, wantRepo: "https://github.com/snacks-inc/crisps", }, { name: "create with license and gitignore for team", hostname: "github.com", input: repoCreateInput{ Name: "crisps", Visibility: "internal", OwnerLogin: "snacks-inc", TeamSlug: "munchies", LicenseTemplate: "lgpl-3.0", GitIgnoreTemplate: "Go", HasIssuesEnabled: true, HasWikiEnabled: true, }, stubs: func(t *testing.T, r *httpmock.Registry) { r.Register( httpmock.REST("GET", "orgs/snacks-inc/teams/munchies"), httpmock.StringResponse(`{ "node_id": "TEAMID", "id": 1234, "organization": {"node_id": "ORGID"} }`)) r.Register( httpmock.REST("POST", "orgs/snacks-inc/repos"), httpmock.RESTPayload(201, `{"name":"crisps", "owner":{"login": "snacks-inc"}, "html_url":"the://URL"}`, func(payload map[string]interface{}) { assert.Equal(t, map[string]interface{}{ "name": "crisps", "private": false, "visibility": "internal", "gitignore_template": "Go", "license_template": "lgpl-3.0", "team_id": float64(1234), "has_issues": true, "has_wiki": true, }, payload) })) }, wantRepo: "https://github.com/snacks-inc/crisps", }, { name: "create personal repository but try to set it as 'internal'", hostname: "github.com", input: repoCreateInput{ Name: "winter-foods", Description: "roasted chestnuts", HomepageURL: "http://example.com", Visibility: "internal", OwnerLogin: "OWNER", }, wantErr: true, errMsg: "internal repositories can only be created within an organization", stubs: func(t *testing.T, r *httpmock.Registry) { r.Register( httpmock.REST("GET", "users/OWNER"), httpmock.StringResponse(`{ "node_id": "1234", "type": "Not-Org" }`)) r.Exclude( t, httpmock.GraphQL(`mutation RepositoryCreate\b`), ) }, }, { name: "create personal repository with README but try to set it as 'internal'", hostname: "github.com", input: repoCreateInput{ Name: "winter-foods", Description: "roasted chestnuts", HomepageURL: "http://example.com", Visibility: "internal", OwnerLogin: "OWNER", InitReadme: true, }, wantErr: true, errMsg: "internal repositories can only be created within an organization", stubs: func(t *testing.T, r *httpmock.Registry) { r.Register( httpmock.REST("GET", "users/OWNER"), httpmock.StringResponse(`{ "node_id": "1234", "type": "Not-Org" }`)) r.Exclude( t, httpmock.REST("POST", "user/repos"), ) }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { reg := &httpmock.Registry{} defer reg.Verify(t) tt.stubs(t, reg) httpClient := &http.Client{Transport: reg} r, err := repoCreate(httpClient, tt.hostname, tt.input) if tt.wantErr { assert.Error(t, err) if tt.errMsg != "" { assert.ErrorContains(t, err, tt.errMsg) } return } else { assert.NoError(t, err) } assert.Equal(t, tt.wantRepo, ghrepo.GenerateRepoURL(r, "")) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/create/http.go
pkg/cmd/repo/create/http.go
package create import ( "bytes" "encoding/json" "fmt" "net/http" "strings" "github.com/cli/cli/v2/api" "github.com/shurcooL/githubv4" ) // repoCreateInput is input parameters for the repoCreate method type repoCreateInput struct { Name string HomepageURL string Description string Visibility string OwnerLogin string TeamSlug string TemplateRepositoryID string HasIssuesEnabled bool HasWikiEnabled bool GitIgnoreTemplate string LicenseTemplate string IncludeAllBranches bool InitReadme bool } // createRepositoryInputV3 is the payload for the repo create REST API type createRepositoryInputV3 struct { Name string `json:"name"` HomepageURL string `json:"homepage,omitempty"` Description string `json:"description,omitempty"` IsPrivate bool `json:"private"` Visibility string `json:"visibility,omitempty"` TeamID uint64 `json:"team_id,omitempty"` HasIssuesEnabled bool `json:"has_issues"` HasWikiEnabled bool `json:"has_wiki"` GitIgnoreTemplate string `json:"gitignore_template,omitempty"` LicenseTemplate string `json:"license_template,omitempty"` InitReadme bool `json:"auto_init,omitempty"` } // createRepositoryInput is the payload for the repo create GraphQL mutation type createRepositoryInput struct { Name string `json:"name"` HomepageURL string `json:"homepageUrl,omitempty"` Description string `json:"description,omitempty"` Visibility string `json:"visibility"` OwnerID string `json:"ownerId,omitempty"` TeamID string `json:"teamId,omitempty"` HasIssuesEnabled bool `json:"hasIssuesEnabled"` HasWikiEnabled bool `json:"hasWikiEnabled"` } // cloneTemplateRepositoryInput is the payload for creating a repo from a template using GraphQL type cloneTemplateRepositoryInput struct { Name string `json:"name"` Visibility string `json:"visibility"` Description string `json:"description,omitempty"` OwnerID string `json:"ownerId"` RepositoryID string `json:"repositoryId"` IncludeAllBranches bool `json:"includeAllBranches"` } type updateRepositoryInput struct { RepositoryID string `json:"repositoryId"` HasWikiEnabled bool `json:"hasWikiEnabled"` HasIssuesEnabled bool `json:"hasIssuesEnabled"` HomepageURL string `json:"homepageUrl,omitempty"` } // repoCreate creates a new GitHub repository func repoCreate(client *http.Client, hostname string, input repoCreateInput) (*api.Repository, error) { isOrg := false var ownerID string var teamID string var teamIDv3 uint64 apiClient := api.NewClientFromHTTP(client) if input.TeamSlug != "" { team, err := resolveOrganizationTeam(apiClient, hostname, input.OwnerLogin, input.TeamSlug) if err != nil { return nil, err } teamIDv3 = team.ID teamID = team.NodeID ownerID = team.Organization.NodeID isOrg = true } else if input.OwnerLogin != "" { owner, err := resolveOwner(apiClient, hostname, input.OwnerLogin) if err != nil { return nil, err } ownerID = owner.NodeID isOrg = owner.IsOrganization() } isInternal := strings.ToLower(input.Visibility) == "internal" if isInternal && !isOrg { return nil, fmt.Errorf("internal repositories can only be created within an organization") } if input.TemplateRepositoryID != "" { var response struct { CloneTemplateRepository struct { Repository api.Repository } } if ownerID == "" { var err error ownerID, err = api.CurrentUserID(apiClient, hostname) if err != nil { return nil, err } } variables := map[string]interface{}{ "input": cloneTemplateRepositoryInput{ Name: input.Name, Description: input.Description, Visibility: strings.ToUpper(input.Visibility), OwnerID: ownerID, RepositoryID: input.TemplateRepositoryID, IncludeAllBranches: input.IncludeAllBranches, }, } err := apiClient.GraphQL(hostname, ` mutation CloneTemplateRepository($input: CloneTemplateRepositoryInput!) { cloneTemplateRepository(input: $input) { repository { id name owner { login } url } } } `, variables, &response) if err != nil { return nil, err } if !input.HasWikiEnabled || !input.HasIssuesEnabled || input.HomepageURL != "" { updateVariables := map[string]interface{}{ "input": updateRepositoryInput{ RepositoryID: response.CloneTemplateRepository.Repository.ID, HasWikiEnabled: input.HasWikiEnabled, HasIssuesEnabled: input.HasIssuesEnabled, HomepageURL: input.HomepageURL, }, } if err := apiClient.GraphQL(hostname, ` mutation UpdateRepository($input: UpdateRepositoryInput!) { updateRepository(input: $input) { repository { id } } } `, updateVariables, nil); err != nil { return nil, err } } return api.InitRepoHostname(&response.CloneTemplateRepository.Repository, hostname), nil } if input.GitIgnoreTemplate != "" || input.LicenseTemplate != "" || input.InitReadme { inputv3 := createRepositoryInputV3{ Name: input.Name, HomepageURL: input.HomepageURL, Description: input.Description, IsPrivate: strings.EqualFold(input.Visibility, "PRIVATE"), TeamID: teamIDv3, HasIssuesEnabled: input.HasIssuesEnabled, HasWikiEnabled: input.HasWikiEnabled, GitIgnoreTemplate: input.GitIgnoreTemplate, LicenseTemplate: input.LicenseTemplate, InitReadme: input.InitReadme, } path := "user/repos" if isOrg { path = fmt.Sprintf("orgs/%s/repos", input.OwnerLogin) inputv3.Visibility = strings.ToLower(input.Visibility) } body := &bytes.Buffer{} enc := json.NewEncoder(body) if err := enc.Encode(inputv3); err != nil { return nil, err } repo, err := api.CreateRepoTransformToV4(apiClient, hostname, "POST", path, body) if err != nil { return nil, err } return repo, nil } var response struct { CreateRepository struct { Repository api.Repository } } variables := map[string]interface{}{ "input": createRepositoryInput{ Name: input.Name, Description: input.Description, HomepageURL: input.HomepageURL, Visibility: strings.ToUpper(input.Visibility), OwnerID: ownerID, TeamID: teamID, HasIssuesEnabled: input.HasIssuesEnabled, HasWikiEnabled: input.HasWikiEnabled, }, } err := apiClient.GraphQL(hostname, ` mutation RepositoryCreate($input: CreateRepositoryInput!) { createRepository(input: $input) { repository { id name owner { login } url } } } `, variables, &response) if err != nil { return nil, err } return api.InitRepoHostname(&response.CreateRepository.Repository, hostname), nil } type ownerResponse struct { NodeID string `json:"node_id"` Type string `json:"type"` } func (r *ownerResponse) IsOrganization() bool { return r.Type == "Organization" } func resolveOwner(client *api.Client, hostname, orgName string) (*ownerResponse, error) { var response ownerResponse err := client.REST(hostname, "GET", fmt.Sprintf("users/%s", orgName), nil, &response) return &response, err } type teamResponse struct { ID uint64 `json:"id"` NodeID string `json:"node_id"` Organization struct { NodeID string `json:"node_id"` } } func resolveOrganizationTeam(client *api.Client, hostname, orgName, teamSlug string) (*teamResponse, error) { var response teamResponse err := client.REST(hostname, "GET", fmt.Sprintf("orgs/%s/teams/%s", orgName, teamSlug), nil, &response) return &response, err } func listTemplateRepositories(client *http.Client, hostname, owner string) ([]api.Repository, error) { ownerConnection := "repositoryOwner(login: $owner)" variables := map[string]interface{}{ "perPage": githubv4.Int(100), "owner": githubv4.String(owner), } inputs := []string{"$perPage:Int!", "$endCursor:String", "$owner:String!"} type result struct { RepositoryOwner struct { Login string Repositories struct { Nodes []api.Repository TotalCount int PageInfo struct { HasNextPage bool EndCursor string } } } } query := fmt.Sprintf(`query RepositoryList(%s) { %s { login repositories(first: $perPage, after: $endCursor, ownerAffiliations: OWNER, orderBy: { field: PUSHED_AT, direction: DESC }) { nodes{ id name isTemplate defaultBranchRef { name } } totalCount pageInfo{hasNextPage,endCursor} } } }`, strings.Join(inputs, ","), ownerConnection) apiClient := api.NewClientFromHTTP(client) var templateRepositories []api.Repository for { var res result err := apiClient.GraphQL(hostname, query, variables, &res) if err != nil { return nil, err } owner := res.RepositoryOwner for _, repo := range owner.Repositories.Nodes { if repo.IsTemplate { templateRepositories = append(templateRepositories, repo) } } if !owner.Repositories.PageInfo.HasNextPage { break } variables["endCursor"] = githubv4.String(owner.Repositories.PageInfo.EndCursor) } return templateRepositories, nil } // Returns the current username and any orgs that user is a member of. func userAndOrgs(httpClient *http.Client, hostname string) (string, []string, error) { client := api.NewClientFromHTTP(httpClient) return api.CurrentLoginNameAndOrgs(client, hostname) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/clone/clone_test.go
pkg/cmd/repo/clone/clone_test.go
package clone import ( "net/http" "net/url" "testing" "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/run" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/test" "github.com/google/shlex" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNewCmdClone(t *testing.T) { testCases := []struct { name string args string wantOpts CloneOptions wantErr string }{ { name: "no arguments", args: "", wantErr: "cannot clone: repository argument required", }, { name: "repo argument", args: "OWNER/REPO", wantOpts: CloneOptions{ Repository: "OWNER/REPO", GitArgs: []string{}, }, }, { name: "directory argument", args: "OWNER/REPO mydir", wantOpts: CloneOptions{ Repository: "OWNER/REPO", GitArgs: []string{"mydir"}, }, }, { name: "git clone arguments", args: "OWNER/REPO -- --depth 1 --recurse-submodules", wantOpts: CloneOptions{ Repository: "OWNER/REPO", GitArgs: []string{"--depth", "1", "--recurse-submodules"}, }, }, { name: "unknown argument", args: "OWNER/REPO --depth 1", wantErr: "unknown flag: --depth\nSeparate git clone flags with '--'.", }, } for _, tt := range testCases { t.Run(tt.name, func(t *testing.T) { ios, stdin, stdout, stderr := iostreams.Test() fac := &cmdutil.Factory{IOStreams: ios} var opts *CloneOptions cmd := NewCmdClone(fac, func(co *CloneOptions) error { opts = co return nil }) argv, err := shlex.Split(tt.args) require.NoError(t, err) cmd.SetArgs(argv) cmd.SetIn(stdin) cmd.SetOut(stderr) cmd.SetErr(stderr) _, err = cmd.ExecuteC() if tt.wantErr != "" { assert.EqualError(t, err, tt.wantErr) return } else { assert.NoError(t, err) } assert.Equal(t, "", stdout.String()) assert.Equal(t, "", stderr.String()) assert.Equal(t, tt.wantOpts.Repository, opts.Repository) assert.Equal(t, tt.wantOpts.GitArgs, opts.GitArgs) }) } } func runCloneCommand(httpClient *http.Client, cli string) (*test.CmdOut, error) { ios, stdin, stdout, stderr := iostreams.Test() fac := &cmdutil.Factory{ IOStreams: ios, HttpClient: func() (*http.Client, error) { return httpClient, nil }, Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, GitClient: &git.Client{ GhPath: "some/path/gh", GitPath: "some/path/git", }, } cmd := NewCmdClone(fac, nil) argv, err := shlex.Split(cli) cmd.SetArgs(argv) cmd.SetIn(stdin) cmd.SetOut(stderr) cmd.SetErr(stderr) if err != nil { panic(err) } _, err = cmd.ExecuteC() if err != nil { return nil, err } return &test.CmdOut{OutBuf: stdout, ErrBuf: stderr}, nil } func Test_RepoClone(t *testing.T) { tests := []struct { name string args string want string }{ { name: "shorthand", args: "OWNER/REPO", want: "git clone https://github.com/OWNER/REPO.git", }, { name: "shorthand with directory", args: "OWNER/REPO target_directory", want: "git clone https://github.com/OWNER/REPO.git target_directory", }, { name: "clone arguments", args: "OWNER/REPO -- -o upstream --depth 1", want: "git clone -o upstream --depth 1 https://github.com/OWNER/REPO.git", }, { name: "clone arguments with directory", args: "OWNER/REPO target_directory -- -o upstream --depth 1", want: "git clone -o upstream --depth 1 https://github.com/OWNER/REPO.git target_directory", }, { name: "HTTPS URL", args: "https://github.com/OWNER/REPO", want: "git clone https://github.com/OWNER/REPO.git", }, { name: "HTTPS URL with extra path parts", args: "https://github.com/OWNER/REPO/extra/part?key=value#fragment", want: "git clone https://github.com/OWNER/REPO.git", }, { name: "SSH URL", args: "git@github.com:OWNER/REPO.git", want: "git clone git@github.com:OWNER/REPO.git", }, { name: "Non-canonical capitalization", args: "Owner/Repo", want: "git clone https://github.com/OWNER/REPO.git", }, { name: "clone wiki", args: "Owner/Repo.wiki", want: "git clone https://github.com/OWNER/REPO.wiki.git", }, { name: "wiki URL", args: "https://github.com/owner/repo.wiki", want: "git clone https://github.com/OWNER/REPO.wiki.git", }, { name: "wiki URL with extra path parts", args: "https://github.com/owner/repo.wiki/extra/path?key=value#fragment", want: "git clone https://github.com/OWNER/REPO.wiki.git", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { reg := &httpmock.Registry{} defer reg.Verify(t) reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "name": "REPO", "owner": { "login": "OWNER" }, "hasWikiEnabled": true } } } `)) httpClient := &http.Client{Transport: reg} cs, restore := run.Stub() defer restore(t) cs.Register(tt.want, 0, "") output, err := runCloneCommand(httpClient, tt.args) if err != nil { t.Fatalf("error running command `repo clone`: %v", err) } assert.Equal(t, "", output.String()) assert.Equal(t, "", output.Stderr()) }) } } func Test_RepoClone_hasParent(t *testing.T) { reg := &httpmock.Registry{} defer reg.Verify(t) reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "name": "REPO", "owner": { "login": "OWNER" }, "parent": { "name": "ORIG", "owner": { "login": "hubot" }, "defaultBranchRef": { "name": "trunk" } } } } } `)) httpClient := &http.Client{Transport: reg} cs, cmdTeardown := run.Stub() defer cmdTeardown(t) cs.Register(`git clone https://github.com/OWNER/REPO.git`, 0, "") cs.Register(`git -C REPO remote add -t trunk upstream https://github.com/hubot/ORIG.git`, 0, "") cs.Register(`git -C REPO fetch upstream`, 0, "") cs.Register(`git -C REPO remote set-branches upstream *`, 0, "") cs.Register(`git -C REPO config --add remote.upstream.gh-resolved base`, 0, "") _, err := runCloneCommand(httpClient, "OWNER/REPO") if err != nil { t.Fatalf("error running command `repo clone`: %v", err) } } func Test_RepoClone_hasParent_upstreamRemoteName(t *testing.T) { reg := &httpmock.Registry{} defer reg.Verify(t) reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "name": "REPO", "owner": { "login": "OWNER" }, "parent": { "name": "ORIG", "owner": { "login": "hubot" }, "defaultBranchRef": { "name": "trunk" } } } } } `)) httpClient := &http.Client{Transport: reg} cs, cmdTeardown := run.Stub() defer cmdTeardown(t) cs.Register(`git clone https://github.com/OWNER/REPO.git`, 0, "") cs.Register(`git -C REPO remote add -t trunk test https://github.com/hubot/ORIG.git`, 0, "") cs.Register(`git -C REPO fetch test`, 0, "") cs.Register(`git -C REPO remote set-branches test *`, 0, "") cs.Register(`git -C REPO config --add remote.test.gh-resolved base`, 0, "") _, err := runCloneCommand(httpClient, "OWNER/REPO --upstream-remote-name test") if err != nil { t.Fatalf("error running command `repo clone`: %v", err) } } func Test_RepoClone_withoutUsername(t *testing.T) { reg := &httpmock.Registry{} defer reg.Verify(t) reg.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(` { "data": { "viewer": { "login": "OWNER" }}}`)) reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "name": "REPO", "owner": { "login": "OWNER" } } } } `)) httpClient := &http.Client{Transport: reg} cs, restore := run.Stub() defer restore(t) cs.Register(`git clone https://github\.com/OWNER/REPO\.git`, 0, "") output, err := runCloneCommand(httpClient, "REPO") if err != nil { t.Fatalf("error running command `repo clone`: %v", err) } assert.Equal(t, "", output.String()) assert.Equal(t, "", output.Stderr()) } func TestSimplifyURL(t *testing.T) { tests := []struct { name string raw string expectedRaw string }{ { name: "empty", raw: "", expectedRaw: "", }, { name: "no change, no path", raw: "https://github.com", expectedRaw: "https://github.com", }, { name: "no change, single part path", raw: "https://github.com/owner", expectedRaw: "https://github.com/owner", }, { name: "no change, two-part path", raw: "https://github.com/owner/repo", expectedRaw: "https://github.com/owner/repo", }, { name: "no change, three-part path", raw: "https://github.com/owner/repo/pulls", expectedRaw: "https://github.com/owner/repo", }, { name: "no change, two-part path, with query, with fragment", raw: "https://github.com/owner/repo?key=value#fragment", expectedRaw: "https://github.com/owner/repo", }, { name: "no change, single part path, with query, with fragment", raw: "https://github.com/owner?key=value#fragment", expectedRaw: "https://github.com/owner", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { u, err := url.Parse(tt.raw) require.NoError(t, err) result := simplifyURL(u) assert.Equal(t, tt.expectedRaw, result.String()) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/clone/clone.go
pkg/cmd/repo/clone/clone.go
package clone import ( "context" "fmt" "net/http" "net/url" "strings" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/git" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" "github.com/spf13/pflag" ) type CloneOptions struct { HttpClient func() (*http.Client, error) GitClient *git.Client Config func() (gh.Config, error) IO *iostreams.IOStreams GitArgs []string Repository string UpstreamName string } func NewCmdClone(f *cmdutil.Factory, runF func(*CloneOptions) error) *cobra.Command { opts := &CloneOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, GitClient: f.GitClient, Config: f.Config, } cmd := &cobra.Command{ DisableFlagsInUseLine: true, Use: "clone <repository> [<directory>] [-- <gitflags>...]", Args: cmdutil.MinimumArgs(1, "cannot clone: repository argument required"), Short: "Clone a repository locally", Long: heredoc.Docf(` Clone a GitHub repository locally. Pass additional %[1]sgit clone%[1]s flags by listing them after %[1]s--%[1]s. If the %[1]sOWNER/%[1]s portion of the %[1]sOWNER/REPO%[1]s repository argument is omitted, it defaults to the name of the authenticating user. When a protocol scheme is not provided in the repository argument, the %[1]sgit_protocol%[1]s will be chosen from your configuration, which can be checked via %[1]sgh config get git_protocol%[1]s. If the protocol scheme is provided, the repository will be cloned using the specified protocol. If the repository is a fork, its parent repository will be added as an additional git remote called %[1]supstream%[1]s. The remote name can be configured using %[1]s--upstream-remote-name%[1]s. The %[1]s--upstream-remote-name%[1]s option supports an %[1]s@owner%[1]s value which will name the remote after the owner of the parent repository. If the repository is a fork, its parent repository will be set as the default remote repository. `, "`"), Example: heredoc.Doc(` # Clone a repository from a specific org $ gh repo clone cli/cli # Clone a repository from your own account $ gh repo clone myrepo # Clone a repo, overriding git protocol configuration $ gh repo clone https://github.com/cli/cli $ gh repo clone git@github.com:cli/cli.git # Clone a repository to a custom directory $ gh repo clone cli/cli workspace/cli # Clone a repository with additional git clone flags $ gh repo clone cli/cli -- --depth=1 `), RunE: func(cmd *cobra.Command, args []string) error { opts.Repository = args[0] opts.GitArgs = args[1:] if runF != nil { return runF(opts) } return cloneRun(opts) }, } cmd.Flags().StringVarP(&opts.UpstreamName, "upstream-remote-name", "u", "upstream", "Upstream remote name when cloning a fork") cmd.SetFlagErrorFunc(func(cmd *cobra.Command, err error) error { if err == pflag.ErrHelp { return err } return cmdutil.FlagErrorf("%w\nSeparate git clone flags with '--'.", err) }) return cmd } func cloneRun(opts *CloneOptions) error { httpClient, err := opts.HttpClient() if err != nil { return err } cfg, err := opts.Config() if err != nil { return err } apiClient := api.NewClientFromHTTP(httpClient) repositoryIsURL := strings.Contains(opts.Repository, ":") repositoryIsFullName := !repositoryIsURL && strings.Contains(opts.Repository, "/") var repo ghrepo.Interface var protocol string if repositoryIsURL { initialURL, err := git.ParseURL(opts.Repository) if err != nil { return err } repoURL := simplifyURL(initialURL) repo, err = ghrepo.FromURL(repoURL) if err != nil { return err } if repoURL.Scheme == "git+ssh" { repoURL.Scheme = "ssh" } protocol = repoURL.Scheme } else { var fullName string if repositoryIsFullName { fullName = opts.Repository } else { host, _ := cfg.Authentication().DefaultHost() currentUser, err := api.CurrentLoginName(apiClient, host) if err != nil { return err } fullName = currentUser + "/" + opts.Repository } repo, err = ghrepo.FromFullName(fullName) if err != nil { return err } protocol = cfg.GitProtocol(repo.RepoHost()).Value } wantsWiki := strings.HasSuffix(repo.RepoName(), ".wiki") if wantsWiki { repoName := strings.TrimSuffix(repo.RepoName(), ".wiki") repo = ghrepo.NewWithHost(repo.RepoOwner(), repoName, repo.RepoHost()) } // Load the repo from the API to get the username/repo name in its // canonical capitalization canonicalRepo, err := api.GitHubRepo(apiClient, repo) if err != nil { return err } canonicalCloneURL := ghrepo.FormatRemoteURL(canonicalRepo, protocol) // If repo HasWikiEnabled and wantsWiki is true then create a new clone URL if wantsWiki { if !canonicalRepo.HasWikiEnabled { return fmt.Errorf("The '%s' repository does not have a wiki", ghrepo.FullName(canonicalRepo)) } canonicalCloneURL = strings.TrimSuffix(canonicalCloneURL, ".git") + ".wiki.git" } gitClient := opts.GitClient ctx := context.Background() cloneDir, err := gitClient.Clone(ctx, canonicalCloneURL, opts.GitArgs) if err != nil { return err } // If the repo is a fork, add the parent as an upstream remote and set the parent as the default repo. if canonicalRepo.Parent != nil { protocol := cfg.GitProtocol(canonicalRepo.Parent.RepoHost()).Value upstreamURL := ghrepo.FormatRemoteURL(canonicalRepo.Parent, protocol) upstreamName := opts.UpstreamName if opts.UpstreamName == "@owner" { upstreamName = canonicalRepo.Parent.RepoOwner() } gc := gitClient.Copy() gc.RepoDir = cloneDir if _, err := gc.AddRemote(ctx, upstreamName, upstreamURL, []string{canonicalRepo.Parent.DefaultBranchRef.Name}); err != nil { return err } if err := gc.Fetch(ctx, upstreamName, ""); err != nil { return err } if err := gc.SetRemoteBranches(ctx, upstreamName, `*`); err != nil { return err } if err = gc.SetRemoteResolution(ctx, upstreamName, "base"); err != nil { return err } connectedToTerminal := opts.IO.IsStdoutTTY() if connectedToTerminal { cs := opts.IO.ColorScheme() fmt.Fprintf(opts.IO.ErrOut, "%s Repository %s set as the default repository. To learn more about the default repository, run: gh repo set-default --help\n", cs.WarningIcon(), cs.Bold(ghrepo.FullName(canonicalRepo.Parent))) } } return nil } // simplifyURL strips given URL of extra parts like extra path segments (i.e., // anything beyond `/owner/repo`), query strings, or fragments. This function // never returns an error. // // The rationale behind this function is to let users clone a repo with any // URL related to the repo; like: // - (Tree) github.com/owner/repo/blob/main/foo/bar // - (Deep-link to line) github.com/owner/repo/blob/main/foo/bar#L168 // - (Issue/PR comment) github.com/owner/repo/pull/999#issue-9999999999 // - (Commit history) github.com/owner/repo/commits/main/?author=foo func simplifyURL(u *url.URL) *url.URL { result := &url.URL{ Scheme: u.Scheme, User: u.User, Host: u.Host, Path: u.Path, } pathParts := strings.SplitN(strings.Trim(u.Path, "/"), "/", 3) if len(pathParts) <= 2 { return result } result.Path = strings.Join(pathParts[0:2], "/") return result }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/shared/repo.go
pkg/cmd/repo/shared/repo.go
package shared import ( "regexp" "strings" ) var invalidCharactersRE = regexp.MustCompile(`[^\w._-]+`) // NormalizeRepoName takes in the repo name the user inputted and normalizes it using the same logic as GitHub (GitHub.com/new) func NormalizeRepoName(repoName string) string { newName := invalidCharactersRE.ReplaceAllString(repoName, "-") return strings.TrimSuffix(newName, ".git") }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/shared/repo_test.go
pkg/cmd/repo/shared/repo_test.go
package shared import ( "testing" ) func TestNormalizeRepoName(t *testing.T) { // confirmed using GitHub.com/new tests := []struct { LocalName string NormalizedName string }{ { LocalName: "cli", NormalizedName: "cli", }, { LocalName: "cli.git", NormalizedName: "cli", }, { LocalName: "@-#$^", NormalizedName: "---", }, { LocalName: "[cli]", NormalizedName: "-cli-", }, { LocalName: "Hello World, I'm a new repo!", NormalizedName: "Hello-World-I-m-a-new-repo-", }, { LocalName: " @E3H*(#$#_$-ZVp,n.7lGq*_eMa-(-zAZSJYg!", NormalizedName: "-E3H-_--ZVp-n.7lGq-_eMa---zAZSJYg-", }, { LocalName: "I'm a crazy .git repo name .git.git .git", NormalizedName: "I-m-a-crazy-.git-repo-name-.git.git-", }, } for _, tt := range tests { output := NormalizeRepoName(tt.LocalName) if output != tt.NormalizedName { t.Errorf("Expected %q, got %q", tt.NormalizedName, output) } } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/sync/git.go
pkg/cmd/repo/sync/git.go
package sync import ( "context" "fmt" "github.com/cli/cli/v2/git" ) type gitClient interface { CurrentBranch() (string, error) UpdateBranch(string, string) error CreateBranch(string, string, string) error Fetch(string, string) error HasLocalBranch(string) bool IsAncestor(string, string) (bool, error) IsDirty() (bool, error) MergeFastForward(string) error ResetHard(string) error } type gitExecuter struct { client *git.Client } func (g *gitExecuter) UpdateBranch(branch, ref string) error { cmd, err := g.client.Command(context.Background(), "update-ref", fmt.Sprintf("refs/heads/%s", branch), ref) if err != nil { return err } _, err = cmd.Output() return err } func (g *gitExecuter) CreateBranch(branch, ref, upstream string) error { ctx := context.Background() cmd, err := g.client.Command(ctx, "branch", branch, ref) if err != nil { return err } if _, err := cmd.Output(); err != nil { return err } cmd, err = g.client.Command(ctx, "branch", "--set-upstream-to", upstream, branch) if err != nil { return err } _, err = cmd.Output() return err } func (g *gitExecuter) CurrentBranch() (string, error) { return g.client.CurrentBranch(context.Background()) } func (g *gitExecuter) Fetch(remote, ref string) error { args := []string{"fetch", "-q", remote, ref} cmd, err := g.client.AuthenticatedCommand(context.Background(), git.AllMatchingCredentialsPattern, args...) if err != nil { return err } return cmd.Run() } func (g *gitExecuter) HasLocalBranch(branch string) bool { return g.client.HasLocalBranch(context.Background(), branch) } func (g *gitExecuter) IsAncestor(ancestor, progeny string) (bool, error) { args := []string{"merge-base", "--is-ancestor", ancestor, progeny} cmd, err := g.client.Command(context.Background(), args...) if err != nil { return false, err } _, err = cmd.Output() return err == nil, nil } func (g *gitExecuter) IsDirty() (bool, error) { changeCount, err := g.client.UncommittedChangeCount(context.Background()) if err != nil { return false, err } return changeCount != 0, nil } func (g *gitExecuter) MergeFastForward(ref string) error { args := []string{"merge", "--ff-only", "--quiet", ref} cmd, err := g.client.Command(context.Background(), args...) if err != nil { return err } _, err = cmd.Output() return err } func (g *gitExecuter) ResetHard(ref string) error { args := []string{"reset", "--hard", ref} cmd, err := g.client.Command(context.Background(), args...) if err != nil { return err } _, err = cmd.Output() return err }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/sync/sync_test.go
pkg/cmd/repo/sync/sync_test.go
package sync import ( "bytes" "io" "net/http" "testing" "github.com/cli/cli/v2/context" "github.com/cli/cli/v2/git" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/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 TestNewCmdSync(t *testing.T) { tests := []struct { name string tty bool input string output SyncOptions wantErr bool errMsg string }{ { name: "no argument", tty: true, input: "", output: SyncOptions{}, }, { name: "destination repo", tty: true, input: "cli/cli", output: SyncOptions{ DestArg: "cli/cli", }, }, { name: "source repo", tty: true, input: "--source cli/cli", output: SyncOptions{ SrcArg: "cli/cli", }, }, { name: "branch", tty: true, input: "--branch trunk", output: SyncOptions{ Branch: "trunk", }, }, { name: "force", tty: true, input: "--force", output: SyncOptions{ Force: true, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() ios.SetStdinTTY(tt.tty) ios.SetStdoutTTY(tt.tty) f := &cmdutil.Factory{ IOStreams: ios, } argv, err := shlex.Split(tt.input) assert.NoError(t, err) var gotOpts *SyncOptions cmd := NewCmdSync(f, func(opts *SyncOptions) 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.Error(t, err) assert.Equal(t, tt.errMsg, err.Error()) return } assert.NoError(t, err) assert.Equal(t, tt.output.DestArg, gotOpts.DestArg) assert.Equal(t, tt.output.SrcArg, gotOpts.SrcArg) assert.Equal(t, tt.output.Branch, gotOpts.Branch) assert.Equal(t, tt.output.Force, gotOpts.Force) }) } } func Test_SyncRun(t *testing.T) { tests := []struct { name string tty bool opts *SyncOptions remotes []*context.Remote httpStubs func(*httpmock.Registry) gitStubs func(*mockGitClient) wantStdout string wantErr bool errMsg string }{ { name: "sync local repo with parent - tty", tty: true, opts: &SyncOptions{}, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(`{"data":{"repository":{"defaultBranchRef":{"name": "trunk"}}}}`)) }, gitStubs: func(mgc *mockGitClient) { mgc.On("Fetch", "origin", "refs/heads/trunk").Return(nil).Once() mgc.On("HasLocalBranch", "trunk").Return(true).Once() mgc.On("IsAncestor", "trunk", "FETCH_HEAD").Return(true, nil).Once() mgc.On("CurrentBranch").Return("trunk", nil).Once() mgc.On("IsDirty").Return(false, nil).Once() mgc.On("MergeFastForward", "FETCH_HEAD").Return(nil).Once() }, wantStdout: "✓ Synced the \"trunk\" branch from \"OWNER/REPO\" to local repository\n", }, { name: "sync local repo with parent - notty", tty: false, opts: &SyncOptions{ Branch: "trunk", }, gitStubs: func(mgc *mockGitClient) { mgc.On("Fetch", "origin", "refs/heads/trunk").Return(nil).Once() mgc.On("HasLocalBranch", "trunk").Return(true).Once() mgc.On("IsAncestor", "trunk", "FETCH_HEAD").Return(true, nil).Once() mgc.On("CurrentBranch").Return("trunk", nil).Once() mgc.On("IsDirty").Return(false, nil).Once() mgc.On("MergeFastForward", "FETCH_HEAD").Return(nil).Once() }, wantStdout: "", }, { name: "sync local repo with specified source repo", tty: true, opts: &SyncOptions{ Branch: "trunk", SrcArg: "OWNER2/REPO2", }, gitStubs: func(mgc *mockGitClient) { mgc.On("Fetch", "upstream", "refs/heads/trunk").Return(nil).Once() mgc.On("HasLocalBranch", "trunk").Return(true).Once() mgc.On("IsAncestor", "trunk", "FETCH_HEAD").Return(true, nil).Once() mgc.On("CurrentBranch").Return("trunk", nil).Once() mgc.On("IsDirty").Return(false, nil).Once() mgc.On("MergeFastForward", "FETCH_HEAD").Return(nil).Once() }, wantStdout: "✓ Synced the \"trunk\" branch from \"OWNER2/REPO2\" to local repository\n", }, { name: "sync local repo with parent and force specified", tty: true, opts: &SyncOptions{ Branch: "trunk", Force: true, }, gitStubs: func(mgc *mockGitClient) { mgc.On("Fetch", "origin", "refs/heads/trunk").Return(nil).Once() mgc.On("HasLocalBranch", "trunk").Return(true).Once() mgc.On("IsAncestor", "trunk", "FETCH_HEAD").Return(false, nil).Once() mgc.On("CurrentBranch").Return("trunk", nil).Once() mgc.On("IsDirty").Return(false, nil).Once() mgc.On("ResetHard", "FETCH_HEAD").Return(nil).Once() }, wantStdout: "✓ Synced the \"trunk\" branch from \"OWNER/REPO\" to local repository\n", }, { name: "sync local repo with specified source repo and force specified", tty: true, opts: &SyncOptions{ Branch: "trunk", SrcArg: "OWNER2/REPO2", Force: true, }, gitStubs: func(mgc *mockGitClient) { mgc.On("Fetch", "upstream", "refs/heads/trunk").Return(nil).Once() mgc.On("HasLocalBranch", "trunk").Return(true).Once() mgc.On("IsAncestor", "trunk", "FETCH_HEAD").Return(false, nil).Once() mgc.On("CurrentBranch").Return("trunk", nil).Once() mgc.On("IsDirty").Return(false, nil).Once() mgc.On("ResetHard", "FETCH_HEAD").Return(nil).Once() }, wantStdout: "✓ Synced the \"trunk\" branch from \"OWNER2/REPO2\" to local repository\n", }, { name: "sync local repo with parent and not fast forward merge", tty: true, opts: &SyncOptions{ Branch: "trunk", }, gitStubs: func(mgc *mockGitClient) { mgc.On("Fetch", "origin", "refs/heads/trunk").Return(nil).Once() mgc.On("HasLocalBranch", "trunk").Return(true).Once() mgc.On("IsAncestor", "trunk", "FETCH_HEAD").Return(false, nil).Once() }, wantErr: true, errMsg: "can't sync because there are diverging changes; use `--force` to overwrite the destination branch", }, { name: "sync local repo with specified source repo and not fast forward merge", tty: true, opts: &SyncOptions{ Branch: "trunk", SrcArg: "OWNER2/REPO2", }, gitStubs: func(mgc *mockGitClient) { mgc.On("Fetch", "upstream", "refs/heads/trunk").Return(nil).Once() mgc.On("HasLocalBranch", "trunk").Return(true).Once() mgc.On("IsAncestor", "trunk", "FETCH_HEAD").Return(false, nil).Once() }, wantErr: true, errMsg: "can't sync because there are diverging changes; use `--force` to overwrite the destination branch", }, { name: "sync local repo with parent and local changes", tty: true, opts: &SyncOptions{ Branch: "trunk", }, gitStubs: func(mgc *mockGitClient) { mgc.On("Fetch", "origin", "refs/heads/trunk").Return(nil).Once() mgc.On("HasLocalBranch", "trunk").Return(true).Once() mgc.On("IsAncestor", "trunk", "FETCH_HEAD").Return(true, nil).Once() mgc.On("CurrentBranch").Return("trunk", nil).Once() mgc.On("IsDirty").Return(true, nil).Once() }, wantErr: true, errMsg: "refusing to sync due to uncommitted/untracked local changes\ntip: use `git stash --all` before retrying the sync and run `git stash pop` afterwards", }, { name: "sync local repo with parent - existing branch, non-current", tty: true, opts: &SyncOptions{ Branch: "trunk", }, gitStubs: func(mgc *mockGitClient) { mgc.On("Fetch", "origin", "refs/heads/trunk").Return(nil).Once() mgc.On("HasLocalBranch", "trunk").Return(true).Once() mgc.On("IsAncestor", "trunk", "FETCH_HEAD").Return(true, nil).Once() mgc.On("CurrentBranch").Return("test", nil).Once() mgc.On("UpdateBranch", "trunk", "FETCH_HEAD").Return(nil).Once() }, wantStdout: "✓ Synced the \"trunk\" branch from \"OWNER/REPO\" to local repository\n", }, { name: "sync local repo with parent - create new branch", tty: true, opts: &SyncOptions{ Branch: "trunk", }, gitStubs: func(mgc *mockGitClient) { mgc.On("Fetch", "origin", "refs/heads/trunk").Return(nil).Once() mgc.On("HasLocalBranch", "trunk").Return(false).Once() mgc.On("CurrentBranch").Return("test", nil).Once() mgc.On("CreateBranch", "trunk", "FETCH_HEAD", "origin/trunk").Return(nil).Once() }, wantStdout: "✓ Synced the \"trunk\" branch from \"OWNER/REPO\" to local repository\n", }, { name: "sync remote fork with parent with new api - tty", tty: true, opts: &SyncOptions{ DestArg: "FORKOWNER/REPO-FORK", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(`{"data":{"repository":{"defaultBranchRef":{"name": "trunk"}}}}`)) reg.Register( httpmock.REST("POST", "repos/FORKOWNER/REPO-FORK/merge-upstream"), httpmock.StatusStringResponse(200, `{"base_branch": "OWNER:trunk"}`)) }, wantStdout: "✓ Synced the \"FORKOWNER:trunk\" branch from \"OWNER:trunk\"\n", }, { name: "sync remote fork with parent using api fallback - tty", tty: true, opts: &SyncOptions{ DestArg: "FORKOWNER/REPO-FORK", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryFindParent\b`), httpmock.StringResponse(`{"data":{"repository":{"parent":{"name":"REPO","owner":{"login": "OWNER"}}}}}`)) reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(`{"data":{"repository":{"defaultBranchRef":{"name": "trunk"}}}}`)) reg.Register( httpmock.REST("POST", "repos/FORKOWNER/REPO-FORK/merge-upstream"), httpmock.StatusStringResponse(422, `{}`)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/git/refs/heads/trunk"), httpmock.StringResponse(`{"object":{"sha":"0xDEADBEEF"}}`)) reg.Register( httpmock.REST("PATCH", "repos/FORKOWNER/REPO-FORK/git/refs/heads/trunk"), httpmock.StringResponse(`{}`)) }, wantStdout: "✓ Synced the \"FORKOWNER:trunk\" branch from \"OWNER:trunk\"\n", }, { name: "sync remote fork with parent - notty", tty: false, opts: &SyncOptions{ DestArg: "FORKOWNER/REPO-FORK", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(`{"data":{"repository":{"defaultBranchRef":{"name": "trunk"}}}}`)) reg.Register( httpmock.REST("POST", "repos/FORKOWNER/REPO-FORK/merge-upstream"), httpmock.StatusStringResponse(200, `{"base_branch": "OWNER:trunk"}`)) }, wantStdout: "", }, { name: "sync remote repo with no parent", tty: true, opts: &SyncOptions{ DestArg: "OWNER/REPO", Branch: "trunk", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/merge-upstream"), httpmock.StatusStringResponse(422, `{"message": "Validation Failed"}`)) reg.Register( httpmock.GraphQL(`query RepositoryFindParent\b`), httpmock.StringResponse(`{"data":{"repository":{"parent":null}}}`)) }, wantErr: true, errMsg: "can't determine source repository for OWNER/REPO because repository is not fork", }, { name: "sync remote repo with specified source repo", tty: true, opts: &SyncOptions{ DestArg: "OWNER/REPO", SrcArg: "OWNER2/REPO2", Branch: "trunk", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/merge-upstream"), httpmock.StatusStringResponse(200, `{"base_branch": "OWNER2:trunk"}`)) }, wantStdout: "✓ Synced the \"OWNER:trunk\" branch from \"OWNER2:trunk\"\n", }, { name: "sync remote fork with parent and specified branch", tty: true, opts: &SyncOptions{ DestArg: "OWNER/REPO-FORK", Branch: "test", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("POST", "repos/OWNER/REPO-FORK/merge-upstream"), httpmock.StatusStringResponse(200, `{"base_branch": "OWNER:test"}`)) }, wantStdout: "✓ Synced the \"OWNER:test\" branch from \"OWNER:test\"\n", }, { name: "sync remote fork with parent and force specified", tty: true, opts: &SyncOptions{ DestArg: "OWNER/REPO-FORK", Force: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryFindParent\b`), httpmock.StringResponse(`{"data":{"repository":{"parent":{"name":"REPO","owner":{"login": "OWNER"}}}}}`)) reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(`{"data":{"repository":{"defaultBranchRef":{"name": "trunk"}}}}`)) reg.Register( httpmock.REST("POST", "repos/OWNER/REPO-FORK/merge-upstream"), httpmock.StatusStringResponse(409, `{"message": "Merge conflict"}`)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/git/refs/heads/trunk"), httpmock.StringResponse(`{"object":{"sha":"0xDEADBEEF"}}`)) reg.Register( httpmock.REST("PATCH", "repos/OWNER/REPO-FORK/git/refs/heads/trunk"), httpmock.StringResponse(`{}`)) }, wantStdout: "✓ Synced the \"OWNER:trunk\" branch from \"OWNER:trunk\"\n", }, { name: "sync remote fork with parent and not fast forward merge", tty: true, opts: &SyncOptions{ DestArg: "OWNER/REPO-FORK", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryFindParent\b`), httpmock.StringResponse(`{"data":{"repository":{"parent":{"name":"REPO","owner":{"login": "OWNER"}}}}}`)) reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(`{"data":{"repository":{"defaultBranchRef":{"name": "trunk"}}}}`)) reg.Register( httpmock.REST("POST", "repos/OWNER/REPO-FORK/merge-upstream"), httpmock.StatusStringResponse(409, `{"message": "Merge conflict"}`)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/git/refs/heads/trunk"), httpmock.StringResponse(`{"object":{"sha":"0xDEADBEEF"}}`)) reg.Register( httpmock.REST("PATCH", "repos/OWNER/REPO-FORK/git/refs/heads/trunk"), func(req *http.Request) (*http.Response, error) { return &http.Response{ StatusCode: 422, Request: req, Header: map[string][]string{"Content-Type": {"application/json"}}, Body: io.NopCloser(bytes.NewBufferString(`{"message":"Update is not a fast forward"}`)), }, nil }) }, wantErr: true, errMsg: "can't sync because there are diverging changes; use `--force` to overwrite the destination branch", }, { name: "sync remote fork with parent and no existing branch on fork", tty: true, opts: &SyncOptions{ DestArg: "OWNER/REPO-FORK", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryFindParent\b`), httpmock.StringResponse(`{"data":{"repository":{"parent":{"name":"REPO","owner":{"login": "OWNER"}}}}}`)) reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(`{"data":{"repository":{"defaultBranchRef":{"name": "trunk"}}}}`)) reg.Register( httpmock.REST("POST", "repos/OWNER/REPO-FORK/merge-upstream"), httpmock.StatusStringResponse(409, `{"message": "Merge conflict"}`)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/git/refs/heads/trunk"), httpmock.StringResponse(`{"object":{"sha":"0xDEADBEEF"}}`)) reg.Register( httpmock.REST("PATCH", "repos/OWNER/REPO-FORK/git/refs/heads/trunk"), func(req *http.Request) (*http.Response, error) { return &http.Response{ StatusCode: 422, Request: req, Header: map[string][]string{"Content-Type": {"application/json"}}, Body: io.NopCloser(bytes.NewBufferString(`{"message":"Reference does not exist"}`)), }, nil }) }, wantErr: true, errMsg: "trunk branch does not exist on OWNER/REPO-FORK repository", }, { name: "sync remote fork with missing workflow scope on OAuth App token", opts: &SyncOptions{ DestArg: "FORKOWNER/REPO-FORK", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(`{"data":{"repository":{"defaultBranchRef":{"name": "trunk"}}}}`)) reg.Register( httpmock.REST("POST", "repos/FORKOWNER/REPO-FORK/merge-upstream"), httpmock.StatusJSONResponse(422, struct { Message string `json:"message"` }{Message: "refusing to allow an OAuth App to create or update workflow `.github/workflows/unimportant.yml` without `workflow` scope"})) }, wantErr: true, errMsg: "Upstream commits contain workflow changes, which require the `workflow` scope or permission to merge. To request it, run: gh auth refresh -s workflow", }, { name: "sync remote fork with missing workflow permission on GitHub App token", opts: &SyncOptions{ DestArg: "FORKOWNER/REPO-FORK", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(`{"data":{"repository":{"defaultBranchRef":{"name": "trunk"}}}}`)) reg.Register( httpmock.REST("POST", "repos/FORKOWNER/REPO-FORK/merge-upstream"), httpmock.StatusJSONResponse(422, struct { Message string `json:"message"` }{Message: "refusing to allow a GitHub App to create or update workflow `.github/workflows/unimportant.yml` without `workflows` permission"})) }, wantErr: true, errMsg: "Upstream commits contain workflow changes, which require the `workflow` scope or permission to merge. To request it, run: gh auth refresh -s workflow", }, { name: "sync remote fork with missing workflow scope on personal access token", opts: &SyncOptions{ DestArg: "FORKOWNER/REPO-FORK", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(`{"data":{"repository":{"defaultBranchRef":{"name": "trunk"}}}}`)) reg.Register( httpmock.REST("POST", "repos/FORKOWNER/REPO-FORK/merge-upstream"), httpmock.StatusJSONResponse(422, struct { Message string `json:"message"` }{Message: "refusing to allow a Personal Access Token to create or update workflow `.github/workflows/unimportant.yml` without `workflow` scope"})) }, wantErr: true, errMsg: "Upstream commits contain workflow changes, which require the `workflow` scope or permission to merge. To request it, run: gh auth refresh -s workflow", }, } for _, tt := range tests { 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.SetStdinTTY(tt.tty) ios.SetStdoutTTY(tt.tty) tt.opts.IO = ios repo1, _ := ghrepo.FromFullName("OWNER/REPO") repo2, _ := ghrepo.FromFullName("OWNER2/REPO2") tt.opts.BaseRepo = func() (ghrepo.Interface, error) { return repo1, nil } tt.opts.Remotes = func() (context.Remotes, error) { if tt.remotes == nil { return []*context.Remote{ { Remote: &git.Remote{Name: "origin"}, Repo: repo1, }, { Remote: &git.Remote{Name: "upstream"}, Repo: repo2, }, }, nil } return tt.remotes, nil } t.Run(tt.name, func(t *testing.T) { tt.opts.Git = newMockGitClient(t, tt.gitStubs) defer reg.Verify(t) err := syncRun(tt.opts) if tt.wantErr { assert.EqualError(t, err, tt.errMsg) return } else if err != nil { t.Fatalf("syncRun() unexpected error: %v", err) } assert.Equal(t, tt.wantStdout, stdout.String()) }) } } func newMockGitClient(t *testing.T, config func(*mockGitClient)) *mockGitClient { t.Helper() m := &mockGitClient{} m.Test(t) t.Cleanup(func() { t.Helper() m.AssertExpectations(t) }) if config != nil { config(m) } return m }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/sync/mocks.go
pkg/cmd/repo/sync/mocks.go
package sync import ( "github.com/stretchr/testify/mock" ) type mockGitClient struct { mock.Mock } func (g *mockGitClient) UpdateBranch(b, r string) error { args := g.Called(b, r) return args.Error(0) } func (g *mockGitClient) CreateBranch(b, r, u string) error { args := g.Called(b, r, u) return args.Error(0) } func (g *mockGitClient) CurrentBranch() (string, error) { args := g.Called() return args.String(0), args.Error(1) } func (g *mockGitClient) Fetch(a, b string) error { args := g.Called(a, b) return args.Error(0) } func (g *mockGitClient) HasLocalBranch(a string) bool { args := g.Called(a) return args.Bool(0) } func (g *mockGitClient) IsAncestor(a, b string) (bool, error) { args := g.Called(a, b) return args.Bool(0), args.Error(1) } func (g *mockGitClient) IsDirty() (bool, error) { args := g.Called() return args.Bool(0), args.Error(1) } func (g *mockGitClient) MergeFastForward(a string) error { args := g.Called(a) return args.Error(0) } func (g *mockGitClient) ResetHard(a string) error { args := g.Called(a) return args.Error(0) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/sync/sync.go
pkg/cmd/repo/sync/sync.go
package sync import ( "errors" "fmt" "net/http" "strings" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/context" gitpkg "github.com/cli/cli/v2/git" "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" ) const ( notFastForwardErrorMessage = "Update is not a fast forward" branchDoesNotExistErrorMessage = "Reference does not exist" ) type SyncOptions struct { HttpClient func() (*http.Client, error) IO *iostreams.IOStreams BaseRepo func() (ghrepo.Interface, error) Remotes func() (context.Remotes, error) Git gitClient DestArg string SrcArg string Branch string Force bool } func NewCmdSync(f *cmdutil.Factory, runF func(*SyncOptions) error) *cobra.Command { opts := SyncOptions{ HttpClient: f.HttpClient, IO: f.IOStreams, BaseRepo: f.BaseRepo, Remotes: f.Remotes, Git: &gitExecuter{client: f.GitClient}, } cmd := &cobra.Command{ Use: "sync [<destination-repository>]", Short: "Sync a repository", Long: heredoc.Docf(` Sync destination repository from source repository. Syncing uses the default branch of the source repository to update the matching branch on the destination repository so they are equal. A fast forward update will be used except when the %[1]s--force%[1]s flag is specified, then the two branches will be synced using a hard reset. Without an argument, the local repository is selected as the destination repository. The source repository is the parent of the destination repository by default. This can be overridden with the %[1]s--source%[1]s flag. `, "`"), Example: heredoc.Doc(` # Sync local repository from remote parent $ gh repo sync # Sync local repository from remote parent on specific branch $ gh repo sync --branch v1 # Sync remote fork from its parent $ gh repo sync owner/cli-fork # Sync remote repository from another remote repository $ gh repo sync owner/repo --source owner2/repo2 `), Args: cobra.MaximumNArgs(1), RunE: func(c *cobra.Command, args []string) error { if len(args) > 0 { opts.DestArg = args[0] } if runF != nil { return runF(&opts) } return syncRun(&opts) }, } cmd.Flags().StringVarP(&opts.SrcArg, "source", "s", "", "Source repository") cmd.Flags().StringVarP(&opts.Branch, "branch", "b", "", "Branch to sync (default [default branch])") cmd.Flags().BoolVarP(&opts.Force, "force", "", false, "Hard reset the branch of the destination repository to match the source repository") return cmd } func syncRun(opts *SyncOptions) error { if opts.DestArg == "" { return syncLocalRepo(opts) } else { return syncRemoteRepo(opts) } } func syncLocalRepo(opts *SyncOptions) error { var srcRepo ghrepo.Interface if opts.SrcArg != "" { var err error srcRepo, err = ghrepo.FromFullName(opts.SrcArg) if err != nil { return err } } else { var err error srcRepo, err = opts.BaseRepo() if err != nil { return err } } // Find remote that matches the srcRepo var remote string remotes, err := opts.Remotes() if err != nil { return err } if r, err := remotes.FindByRepo(srcRepo.RepoOwner(), srcRepo.RepoName()); err == nil { remote = r.Name } else { return fmt.Errorf("can't find corresponding remote for %s", ghrepo.FullName(srcRepo)) } if opts.Branch == "" { httpClient, err := opts.HttpClient() if err != nil { return err } apiClient := api.NewClientFromHTTP(httpClient) opts.IO.StartProgressIndicator() opts.Branch, err = api.RepoDefaultBranch(apiClient, srcRepo) opts.IO.StopProgressIndicator() if err != nil { return err } } // Git fetch might require input from user, so do it before starting progress indicator. if err := opts.Git.Fetch(remote, fmt.Sprintf("refs/heads/%s", opts.Branch)); err != nil { return err } opts.IO.StartProgressIndicator() err = executeLocalRepoSync(srcRepo, remote, opts) opts.IO.StopProgressIndicator() if err != nil { if errors.Is(err, divergingError) { return fmt.Errorf("can't sync because there are diverging changes; use `--force` to overwrite the destination branch") } return err } if opts.IO.IsStdoutTTY() { cs := opts.IO.ColorScheme() fmt.Fprintf(opts.IO.Out, "%s Synced the \"%s\" branch from \"%s\" to local repository\n", cs.SuccessIcon(), opts.Branch, ghrepo.FullName(srcRepo)) } return nil } func syncRemoteRepo(opts *SyncOptions) error { httpClient, err := opts.HttpClient() if err != nil { return err } apiClient := api.NewClientFromHTTP(httpClient) var destRepo, srcRepo ghrepo.Interface destRepo, err = ghrepo.FromFullName(opts.DestArg) if err != nil { return err } if opts.SrcArg != "" { srcRepo, err = ghrepo.FromFullName(opts.SrcArg) if err != nil { return err } } if srcRepo != nil && destRepo.RepoHost() != srcRepo.RepoHost() { return fmt.Errorf("can't sync repositories from different hosts") } opts.IO.StartProgressIndicator() baseBranchLabel, err := executeRemoteRepoSync(apiClient, destRepo, srcRepo, opts) opts.IO.StopProgressIndicator() if err != nil { if errors.Is(err, divergingError) { return fmt.Errorf("can't sync because there are diverging changes; use `--force` to overwrite the destination branch") } return err } if opts.IO.IsStdoutTTY() { cs := opts.IO.ColorScheme() branchName := opts.Branch if idx := strings.Index(baseBranchLabel, ":"); idx >= 0 { branchName = baseBranchLabel[idx+1:] } fmt.Fprintf(opts.IO.Out, "%s Synced the \"%s:%s\" branch from \"%s\"\n", cs.SuccessIcon(), destRepo.RepoOwner(), branchName, baseBranchLabel) } return nil } var divergingError = errors.New("diverging changes") func executeLocalRepoSync(srcRepo ghrepo.Interface, remote string, opts *SyncOptions) error { git := opts.Git branch := opts.Branch useForce := opts.Force hasLocalBranch := git.HasLocalBranch(branch) if hasLocalBranch { fastForward, err := git.IsAncestor(branch, "FETCH_HEAD") if err != nil { return err } if !fastForward && !useForce { return divergingError } if fastForward && useForce { useForce = false } } currentBranch, err := git.CurrentBranch() if err != nil && !errors.Is(err, gitpkg.ErrNotOnAnyBranch) { return err } if currentBranch == branch { if isDirty, err := git.IsDirty(); err == nil && isDirty { return fmt.Errorf("refusing to sync due to uncommitted/untracked local changes\ntip: use `git stash --all` before retrying the sync and run `git stash pop` afterwards") } else if err != nil { return err } if useForce { if err := git.ResetHard("FETCH_HEAD"); err != nil { return err } } else { if err := git.MergeFastForward("FETCH_HEAD"); err != nil { return err } } } else { if hasLocalBranch { if err := git.UpdateBranch(branch, "FETCH_HEAD"); err != nil { return err } } else { if err := git.CreateBranch(branch, "FETCH_HEAD", fmt.Sprintf("%s/%s", remote, branch)); err != nil { return err } } } return nil } // ExecuteRemoteRepoSync will take several steps to sync the source and destination repositories. // First it will try to use the merge-upstream API endpoint. If this fails due to merge conflicts // or unknown merge issues then it will fallback to using the low level git references API endpoint. // The reason the fallback is necessary is to better support these error cases. The git references API // endpoint allows us to sync repositories that are not fast-forward merge compatible. Additionally, // the git references API endpoint gives more detailed error responses as to why the sync failed. // Unless the --force flag is specified we will not perform non-fast-forward merges. func executeRemoteRepoSync(client *api.Client, destRepo, srcRepo ghrepo.Interface, opts *SyncOptions) (string, error) { branchName := opts.Branch if branchName == "" { var err error branchName, err = api.RepoDefaultBranch(client, destRepo) if err != nil { return "", err } } var apiErr upstreamMergeErr if baseBranch, err := triggerUpstreamMerge(client, destRepo, branchName); err == nil { return baseBranch, nil } else if !errors.As(err, &apiErr) { return "", err } if srcRepo == nil { var err error srcRepo, err = api.RepoParent(client, destRepo) if err != nil { return "", err } if srcRepo == nil { return "", fmt.Errorf("can't determine source repository for %s because repository is not fork", ghrepo.FullName(destRepo)) } } commit, err := latestCommit(client, srcRepo, branchName) if err != nil { return "", err } // Using string comparison is a brittle way to determine the error returned by the API // endpoint but unfortunately the API returns 422 for many reasons so we must // interpret the message provide better error messaging for our users. err = syncFork(client, destRepo, branchName, commit.Object.SHA, opts.Force) var httpErr api.HTTPError if err != nil { if errors.As(err, &httpErr) { switch httpErr.Message { case notFastForwardErrorMessage: return "", divergingError case branchDoesNotExistErrorMessage: return "", fmt.Errorf("%s branch does not exist on %s repository", branchName, ghrepo.FullName(destRepo)) } } return "", err } return fmt.Sprintf("%s:%s", srcRepo.RepoOwner(), branchName), nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/sync/http.go
pkg/cmd/repo/sync/http.go
package sync import ( "bytes" "encoding/json" "errors" "fmt" "net/http" "regexp" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghrepo" ) type commit struct { Ref string `json:"ref"` NodeID string `json:"node_id"` URL string `json:"url"` Object struct { Type string `json:"type"` SHA string `json:"sha"` URL string `json:"url"` } `json:"object"` } func latestCommit(client *api.Client, repo ghrepo.Interface, branch string) (commit, error) { var response commit path := fmt.Sprintf("repos/%s/%s/git/refs/heads/%s", repo.RepoOwner(), repo.RepoName(), branch) err := client.REST(repo.RepoHost(), "GET", path, nil, &response) return response, err } type upstreamMergeErr struct{ error } var missingWorkflowScopeRE = regexp.MustCompile("refusing to allow.*without `workflow(s)?` (scope|permission)") var missingWorkflowScopeErr = errors.New("Upstream commits contain workflow changes, which require the `workflow` scope or permission to merge. To request it, run: gh auth refresh -s workflow") func triggerUpstreamMerge(client *api.Client, repo ghrepo.Interface, branch string) (string, error) { var payload bytes.Buffer if err := json.NewEncoder(&payload).Encode(map[string]interface{}{ "branch": branch, }); err != nil { return "", err } var response struct { Message string `json:"message"` MergeType string `json:"merge_type"` BaseBranch string `json:"base_branch"` } path := fmt.Sprintf("repos/%s/%s/merge-upstream", repo.RepoOwner(), repo.RepoName()) var httpErr api.HTTPError if err := client.REST(repo.RepoHost(), "POST", path, &payload, &response); err != nil { if errors.As(err, &httpErr) { switch httpErr.StatusCode { case http.StatusUnprocessableEntity, http.StatusConflict: if missingWorkflowScopeRE.MatchString(httpErr.Message) { return "", missingWorkflowScopeErr } return "", upstreamMergeErr{errors.New(httpErr.Message)} } } return "", err } return response.BaseBranch, nil } func syncFork(client *api.Client, repo ghrepo.Interface, branch, SHA string, force bool) error { path := fmt.Sprintf("repos/%s/%s/git/refs/heads/%s", repo.RepoOwner(), repo.RepoName(), branch) body := map[string]interface{}{ "sha": SHA, "force": force, } requestByte, err := json.Marshal(body) if err != nil { return err } requestBody := bytes.NewReader(requestByte) return client.REST(repo.RepoHost(), "PATCH", path, requestBody, nil) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/issue/issue.go
pkg/cmd/issue/issue.go
package issue import ( "github.com/MakeNowJust/heredoc" cmdClose "github.com/cli/cli/v2/pkg/cmd/issue/close" cmdComment "github.com/cli/cli/v2/pkg/cmd/issue/comment" cmdCreate "github.com/cli/cli/v2/pkg/cmd/issue/create" cmdDelete "github.com/cli/cli/v2/pkg/cmd/issue/delete" cmdDevelop "github.com/cli/cli/v2/pkg/cmd/issue/develop" cmdEdit "github.com/cli/cli/v2/pkg/cmd/issue/edit" cmdList "github.com/cli/cli/v2/pkg/cmd/issue/list" cmdLock "github.com/cli/cli/v2/pkg/cmd/issue/lock" cmdPin "github.com/cli/cli/v2/pkg/cmd/issue/pin" cmdReopen "github.com/cli/cli/v2/pkg/cmd/issue/reopen" cmdStatus "github.com/cli/cli/v2/pkg/cmd/issue/status" cmdTransfer "github.com/cli/cli/v2/pkg/cmd/issue/transfer" cmdUnpin "github.com/cli/cli/v2/pkg/cmd/issue/unpin" cmdView "github.com/cli/cli/v2/pkg/cmd/issue/view" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/spf13/cobra" ) func NewCmdIssue(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "issue <command>", Short: "Manage issues", Long: `Work with GitHub issues.`, Example: heredoc.Doc(` $ gh issue list $ gh issue create --label bug $ gh issue view 123 --web `), Annotations: map[string]string{ "help:arguments": heredoc.Doc(` An issue can be supplied as argument in any of the following formats: - by number, e.g. "123"; or - by URL, e.g. "https://github.com/OWNER/REPO/issues/123". `), }, 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), cmdComment.NewCmdComment(f, nil), cmdClose.NewCmdClose(f, nil), cmdReopen.NewCmdReopen(f, nil), cmdEdit.NewCmdEdit(f, nil), cmdDevelop.NewCmdDevelop(f, nil), cmdLock.NewCmdLock(f, cmd.Name(), nil), cmdLock.NewCmdUnlock(f, cmd.Name(), nil), cmdPin.NewCmdPin(f, nil), cmdUnpin.NewCmdUnpin(f, nil), cmdTransfer.NewCmdTransfer(f, nil), 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/issue/unpin/unpin.go
pkg/cmd/issue/unpin/unpin.go
package unpin import ( "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/pkg/cmd/issue/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/shurcooL/githubv4" "github.com/spf13/cobra" ) type UnpinOptions struct { HttpClient func() (*http.Client, error) Config func() (gh.Config, error) IO *iostreams.IOStreams BaseRepo func() (ghrepo.Interface, error) IssueNumber int } func NewCmdUnpin(f *cmdutil.Factory, runF func(*UnpinOptions) error) *cobra.Command { opts := &UnpinOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, Config: f.Config, BaseRepo: f.BaseRepo, } cmd := &cobra.Command{ Use: "unpin {<number> | <url>}", Short: "Unpin a issue", Long: heredoc.Doc(` Unpin an issue from a repository. The issue can be specified by issue number or URL. `), Example: heredoc.Doc(` # Unpin issue from the current repository $ gh issue unpin 23 # Unpin issue by URL $ gh issue unpin https://github.com/owner/repo/issues/23 # Unpin an issue from specific repository $ gh issue unpin 23 --repo owner/repo `), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { issueNumber, baseRepo, err := shared.ParseIssueFromArg(args[0]) if err != nil { return err } // If the args provided the base repo then use that directly. if baseRepo, present := baseRepo.Value(); present { opts.BaseRepo = func() (ghrepo.Interface, error) { return baseRepo, nil } } else { // support `-R, --repo` override opts.BaseRepo = f.BaseRepo } opts.IssueNumber = issueNumber if runF != nil { return runF(opts) } return unpinRun(opts) }, } return cmd } func unpinRun(opts *UnpinOptions) error { cs := opts.IO.ColorScheme() httpClient, err := opts.HttpClient() if err != nil { return err } baseRepo, err := opts.BaseRepo() if err != nil { return err } issue, err := shared.FindIssueOrPR(httpClient, baseRepo, opts.IssueNumber, []string{"id", "number", "title", "isPinned"}) if err != nil { return err } if !issue.IsPinned { fmt.Fprintf(opts.IO.ErrOut, "%s Issue %s#%d (%s) is not pinned\n", cs.Yellow("!"), ghrepo.FullName(baseRepo), issue.Number, issue.Title) return nil } err = unpinIssue(httpClient, baseRepo, issue) if err != nil { return err } fmt.Fprintf(opts.IO.ErrOut, "%s Unpinned issue %s#%d (%s)\n", cs.SuccessIconWithColor(cs.Red), ghrepo.FullName(baseRepo), issue.Number, issue.Title) return nil } func unpinIssue(httpClient *http.Client, repo ghrepo.Interface, issue *api.Issue) error { var mutation struct { UnpinIssue struct { Issue struct { ID githubv4.ID } } `graphql:"unpinIssue(input: $input)"` } variables := map[string]interface{}{ "input": githubv4.UnpinIssueInput{ IssueID: issue.ID, }, } gql := api.NewClientFromHTTP(httpClient) return gql.Mutate(repo.RepoHost(), "IssueUnpin", &mutation, variables) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/issue/unpin/unpin_test.go
pkg/cmd/issue/unpin/unpin_test.go
package unpin import ( "net/http" "testing" "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/pkg/cmd/issue/argparsetest" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/stretchr/testify/assert" ) func TestNewCmdUnpin(t *testing.T) { // Test shared parsing of issue number / URL. argparsetest.TestArgParsing(t, NewCmdUnpin) } func TestUnpinRun(t *testing.T) { tests := []struct { name string tty bool opts *UnpinOptions httpStubs func(*httpmock.Registry) wantStdout string wantStderr string }{ { name: "unpin issue", tty: true, opts: &UnpinOptions{IssueNumber: 20}, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "issue": { "id": "ISSUE-ID", "number": 20, "title": "Issue Title", "isPinned": true} } } }`), ) reg.Register( httpmock.GraphQL(`mutation IssueUnpin\b`), httpmock.GraphQLMutation(`{"id": "ISSUE-ID"}`, func(inputs map[string]interface{}) { assert.Equal(t, inputs["issueId"], "ISSUE-ID") }, ), ) }, wantStdout: "", wantStderr: "✓ Unpinned issue OWNER/REPO#20 (Issue Title)\n", }, { name: "issue not pinned", tty: true, opts: &UnpinOptions{IssueNumber: 20}, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "issue": { "id": "ISSUE-ID", "number": 20, "title": "Issue Title", "isPinned": false} } } }`), ) }, wantStderr: "! Issue OWNER/REPO#20 (Issue Title) is not pinned\n", }, } for _, tt := range tests { 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.SetStdinTTY(tt.tty) ios.SetStdoutTTY(tt.tty) tt.opts.IO = ios tt.opts.Config = func() (gh.Config, error) { return config.NewBlankConfig(), nil } tt.opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil } t.Run(tt.name, func(t *testing.T) { defer reg.Verify(t) err := unpinRun(tt.opts) 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/issue/delete/delete.go
pkg/cmd/issue/delete/delete.go
package delete import ( "fmt" "net/http" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/issue/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/shurcooL/githubv4" "github.com/spf13/cobra" ) type DeleteOptions struct { HttpClient func() (*http.Client, error) Config func() (gh.Config, error) IO *iostreams.IOStreams BaseRepo func() (ghrepo.Interface, error) Prompter iprompter IssueNumber int Confirmed bool } type iprompter interface { ConfirmDeletion(string) error } func NewCmdDelete(f *cmdutil.Factory, runF func(*DeleteOptions) error) *cobra.Command { opts := &DeleteOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, Config: f.Config, Prompter: f.Prompter, } cmd := &cobra.Command{ Use: "delete {<number> | <url>}", Short: "Delete issue", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { issueNumber, baseRepo, err := shared.ParseIssueFromArg(args[0]) if err != nil { return err } // If the args provided the base repo then use that directly. if baseRepo, present := baseRepo.Value(); present { opts.BaseRepo = func() (ghrepo.Interface, error) { return baseRepo, nil } } else { // support `-R, --repo` override opts.BaseRepo = f.BaseRepo } opts.IssueNumber = issueNumber 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 { cs := opts.IO.ColorScheme() httpClient, err := opts.HttpClient() if err != nil { return err } baseRepo, err := opts.BaseRepo() if err != nil { return err } issue, err := shared.FindIssueOrPR(httpClient, baseRepo, opts.IssueNumber, []string{"id", "number", "title"}) if err != nil { return err } if issue.IsPullRequest() { return fmt.Errorf("issue %s#%d is a pull request and cannot be deleted", ghrepo.FullName(baseRepo), issue.Number) } // When executed in an interactive shell, require confirmation, unless // already provided. Otherwise skip confirmation. if opts.IO.CanPrompt() && !opts.Confirmed { cs := opts.IO.ColorScheme() fmt.Printf("%s Deleted issues cannot be recovered.\n", cs.WarningIcon()) err := opts.Prompter.ConfirmDeletion(fmt.Sprintf("%d", issue.Number)) if err != nil { return err } } if err := apiDelete(httpClient, baseRepo, issue.ID); err != nil { return err } if opts.IO.IsStdoutTTY() { fmt.Fprintf(opts.IO.ErrOut, "%s Deleted issue %s#%d (%s).\n", cs.Red("✔"), ghrepo.FullName(baseRepo), issue.Number, issue.Title) } return nil } func apiDelete(httpClient *http.Client, repo ghrepo.Interface, issueID string) error { var mutation struct { DeleteIssue struct { Repository struct { ID githubv4.ID } } `graphql:"deleteIssue(input: $input)"` } variables := map[string]interface{}{ "input": githubv4.DeleteIssueInput{ IssueID: issueID, }, } gql := api.NewClientFromHTTP(httpClient) return gql.Mutate(repo.RepoHost(), "IssueDelete", &mutation, variables) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/issue/delete/delete_test.go
pkg/cmd/issue/delete/delete_test.go
package delete import ( "bytes" "errors" "io" "net/http" "regexp" "testing" "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/issue/argparsetest" "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 TestNewCmdDelete(t *testing.T) { argparsetest.TestArgParsing(t, NewCmdDelete) } func runCommand(rt http.RoundTripper, pm *prompter.MockPrompter, 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, Prompter: pm, HttpClient: func() (*http.Client, error) { return &http.Client{Transport: rt}, nil }, Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil }, } cmd := NewCmdDelete(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 TestIssueDelete(t *testing.T) { httpRegistry := &httpmock.Registry{} defer httpRegistry.Verify(t) httpRegistry.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "id": "THE-ID", "number": 13, "title": "The title of the issue"} } } }`), ) httpRegistry.Register( httpmock.GraphQL(`mutation IssueDelete\b`), httpmock.GraphQLMutation(`{"id": "THE-ID"}`, func(inputs map[string]interface{}) { assert.Equal(t, inputs["issueId"], "THE-ID") }), ) pm := prompter.NewMockPrompter(t) pm.RegisterConfirmDeletion("13", func(_ string) error { return nil }) output, err := runCommand(httpRegistry, pm, true, "13") if err != nil { t.Fatalf("error running command `issue delete`: %v", err) } r := regexp.MustCompile(`Deleted issue OWNER/REPO#13 \(The title of the issue\)`) if !r.MatchString(output.Stderr()) { t.Fatalf("output did not match regexp /%s/\n> output\n%q\n", r, output.Stderr()) } } func TestIssueDelete_confirm(t *testing.T) { httpRegistry := &httpmock.Registry{} defer httpRegistry.Verify(t) httpRegistry.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "id": "THE-ID", "number": 13, "title": "The title of the issue"} } } }`), ) httpRegistry.Register( httpmock.GraphQL(`mutation IssueDelete\b`), httpmock.GraphQLMutation(`{"id": "THE-ID"}`, func(inputs map[string]interface{}) { assert.Equal(t, inputs["issueId"], "THE-ID") }), ) output, err := runCommand(httpRegistry, nil, true, "13 --confirm") if err != nil { t.Fatalf("error running command `issue delete`: %v", err) } r := regexp.MustCompile(`Deleted issue OWNER/REPO#13 \(The title of the issue\)`) if !r.MatchString(output.Stderr()) { t.Fatalf("output did not match regexp /%s/\n> output\n%q\n", r, output.Stderr()) } } func TestIssueDelete_cancel(t *testing.T) { httpRegistry := &httpmock.Registry{} defer httpRegistry.Verify(t) httpRegistry.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "id": "THE-ID", "number": 13, "title": "The title of the issue"} } } }`), ) pm := prompter.NewMockPrompter(t) pm.RegisterConfirmDeletion("13", func(_ string) error { return errors.New("You entered 14") }) _, err := runCommand(httpRegistry, pm, true, "13") if err == nil { t.Fatalf("expected error") } if err.Error() != "You entered 14" { t.Fatalf("got unexpected error '%s'", err) } } func TestIssueDelete_doesNotExist(t *testing.T) { httpRegistry := &httpmock.Registry{} defer httpRegistry.Verify(t) httpRegistry.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "errors": [ { "message": "Could not resolve to an Issue with the number of 13." } ] } `), ) _, err := runCommand(httpRegistry, nil, true, "13") if err == nil || err.Error() != "GraphQL: Could not resolve to an Issue with the number of 13." { t.Errorf("error running command `issue delete`: %v", err) } } func TestIssueDelete_issuesDisabled(t *testing.T) { httpRegistry := &httpmock.Registry{} defer httpRegistry.Verify(t) httpRegistry.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": false, "issue": null } }, "errors": [ { "type": "NOT_FOUND", "path": [ "repository", "issue" ], "message": "Could not resolve to an issue or pull request with the number of 13." } ] }`), ) _, err := runCommand(httpRegistry, nil, true, "13") if err == nil || err.Error() != "the 'OWNER/REPO' repository has disabled issues" { t.Fatalf("got error: %v", err) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/issue/reopen/reopen_test.go
pkg/cmd/issue/reopen/reopen_test.go
package reopen import ( "bytes" "io" "net/http" "regexp" "testing" "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/pkg/cmd/issue/argparsetest" "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 TestNewCmdReopen(t *testing.T) { // Test shared parsing of issue number / URL. argparsetest.TestArgParsing(t, NewCmdReopen) } 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 }, Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), 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 TestIssueReopen(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) http.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "id": "THE-ID", "number": 2, "state": "CLOSED", "title": "The title of the issue"} } } }`), ) http.Register( httpmock.GraphQL(`mutation IssueReopen\b`), httpmock.GraphQLMutation(`{"id": "THE-ID"}`, func(inputs map[string]interface{}) { assert.Equal(t, inputs["issueId"], "THE-ID") }), ) output, err := runCommand(http, true, "2") if err != nil { t.Fatalf("error running command `issue reopen`: %v", err) } r := regexp.MustCompile(`Reopened issue OWNER/REPO#2 \(The title of the issue\)`) if !r.MatchString(output.Stderr()) { t.Fatalf("output did not match regexp /%s/\n> output\n%q\n", r, output.Stderr()) } } func TestIssueReopen_alreadyOpen(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) http.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "number": 2, "state": "OPEN", "title": "The title of the issue"} } } }`), ) output, err := runCommand(http, true, "2") if err != nil { t.Fatalf("error running command `issue reopen`: %v", err) } r := regexp.MustCompile(`Issue OWNER/REPO#2 \(The title of the issue\) is already open`) if !r.MatchString(output.Stderr()) { t.Fatalf("output did not match regexp /%s/\n> output\n%q\n", r, output.Stderr()) } } func TestIssueReopen_issuesDisabled(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) http.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": false, "issue": null } }, "errors": [ { "type": "NOT_FOUND", "path": [ "repository", "issue" ], "message": "Could not resolve to an issue or pull request with the number of 2." } ] }`), ) _, err := runCommand(http, true, "2") if err == nil || err.Error() != "the 'OWNER/REPO' repository has disabled issues" { t.Fatalf("got error: %v", err) } } func TestIssueReopen_withComment(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) http.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "id": "THE-ID", "number": 2, "state": "CLOSED", "title": "The title of the issue"} } } }`), ) 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 IssueReopen\b`), httpmock.GraphQLMutation(`{"id": "THE-ID"}`, func(inputs map[string]interface{}) { assert.Equal(t, inputs["issueId"], "THE-ID") }), ) output, err := runCommand(http, true, "2 --comment 'reopening comment'") if err != nil { t.Fatalf("error running command `issue reopen`: %v", err) } r := regexp.MustCompile(`Reopened issue OWNER/REPO#2 \(The title of the issue\)`) if !r.MatchString(output.Stderr()) { t.Fatalf("output did not match regexp /%s/\n> output\n%q\n", r, output.Stderr()) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/issue/reopen/reopen.go
pkg/cmd/issue/reopen/reopen.go
package reopen import ( "fmt" "net/http" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/issue/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/shurcooL/githubv4" "github.com/spf13/cobra" ) type ReopenOptions struct { HttpClient func() (*http.Client, error) Config func() (gh.Config, error) IO *iostreams.IOStreams BaseRepo func() (ghrepo.Interface, error) IssueNumber int Comment string } func NewCmdReopen(f *cmdutil.Factory, runF func(*ReopenOptions) error) *cobra.Command { opts := &ReopenOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, Config: f.Config, } cmd := &cobra.Command{ Use: "reopen {<number> | <url>}", Short: "Reopen issue", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { issueNumber, baseRepo, err := shared.ParseIssueFromArg(args[0]) if err != nil { return err } // If the args provided the base repo then use that directly. if baseRepo, present := baseRepo.Value(); present { opts.BaseRepo = func() (ghrepo.Interface, error) { return baseRepo, nil } } else { // support `-R, --repo` override opts.BaseRepo = f.BaseRepo } opts.IssueNumber = issueNumber 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() httpClient, err := opts.HttpClient() if err != nil { return err } baseRepo, err := opts.BaseRepo() if err != nil { return err } issue, err := shared.FindIssueOrPR(httpClient, baseRepo, opts.IssueNumber, []string{"id", "number", "title", "state"}) if err != nil { return err } if issue.State == "OPEN" { fmt.Fprintf(opts.IO.ErrOut, "%s Issue %s#%d (%s) is already open\n", cs.Yellow("!"), ghrepo.FullName(baseRepo), issue.Number, issue.Title) return nil } if opts.Comment != "" { commentOpts := &prShared.CommentableOptions{ Body: opts.Comment, HttpClient: opts.HttpClient, InputType: prShared.InputTypeInline, Quiet: true, RetrieveCommentable: func() (prShared.Commentable, ghrepo.Interface, error) { return issue, baseRepo, nil }, } err := prShared.CommentableRun(commentOpts) if err != nil { return err } } err = apiReopen(httpClient, baseRepo, issue) if err != nil { return err } fmt.Fprintf(opts.IO.ErrOut, "%s Reopened issue %s#%d (%s)\n", cs.SuccessIconWithColor(cs.Green), ghrepo.FullName(baseRepo), issue.Number, issue.Title) return nil } func apiReopen(httpClient *http.Client, repo ghrepo.Interface, issue *api.Issue) error { if issue.IsPullRequest() { return api.PullRequestReopen(httpClient, repo, issue.ID) } var mutation struct { ReopenIssue struct { Issue struct { ID githubv4.ID } } `graphql:"reopenIssue(input: $input)"` } variables := map[string]interface{}{ "input": githubv4.ReopenIssueInput{ IssueID: issue.ID, }, } gql := api.NewClientFromHTTP(httpClient) return gql.Mutate(repo.RepoHost(), "IssueReopen", &mutation, variables) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/issue/transfer/transfer.go
pkg/cmd/issue/transfer/transfer.go
package transfer import ( "fmt" "net/http" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/issue/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/shurcooL/githubv4" "github.com/spf13/cobra" ) type TransferOptions struct { HttpClient func() (*http.Client, error) Config func() (gh.Config, error) IO *iostreams.IOStreams BaseRepo func() (ghrepo.Interface, error) IssueNumber int DestRepoSelector string } func NewCmdTransfer(f *cmdutil.Factory, runF func(*TransferOptions) error) *cobra.Command { opts := TransferOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, Config: f.Config, } cmd := &cobra.Command{ Use: "transfer {<number> | <url>} <destination-repo>", Short: "Transfer issue to another repository", Args: cmdutil.ExactArgs(2, "issue and destination repository are required"), RunE: func(cmd *cobra.Command, args []string) error { issueNumber, baseRepo, err := shared.ParseIssueFromArg(args[0]) if err != nil { return err } // If the args provided the base repo then use that directly. if baseRepo, present := baseRepo.Value(); present { opts.BaseRepo = func() (ghrepo.Interface, error) { return baseRepo, nil } } else { // support `-R, --repo` override opts.BaseRepo = f.BaseRepo } opts.IssueNumber = issueNumber opts.DestRepoSelector = args[1] if runF != nil { return runF(&opts) } return transferRun(&opts) }, } return cmd } func transferRun(opts *TransferOptions) error { httpClient, err := opts.HttpClient() if err != nil { return err } baseRepo, err := opts.BaseRepo() if err != nil { return err } issue, err := shared.FindIssueOrPR(httpClient, baseRepo, opts.IssueNumber, []string{"id", "number"}) if err != nil { return err } if issue.IsPullRequest() { return fmt.Errorf("issue %s#%d is a pull request and cannot be transferred", ghrepo.FullName(baseRepo), issue.Number) } destRepo, err := ghrepo.FromFullNameWithHost(opts.DestRepoSelector, baseRepo.RepoHost()) if err != nil { return err } url, err := issueTransfer(httpClient, issue.ID, destRepo) if err != nil { return err } _, err = fmt.Fprintln(opts.IO.Out, url) return err } func issueTransfer(httpClient *http.Client, issueID string, destRepo ghrepo.Interface) (string, error) { var destinationRepoID string if r, ok := destRepo.(*api.Repository); ok { destinationRepoID = r.ID } else { apiClient := api.NewClientFromHTTP(httpClient) r, err := api.GitHubRepo(apiClient, destRepo) if err != nil { return "", err } destinationRepoID = r.ID } var mutation struct { TransferIssue struct { Issue struct { URL string } } `graphql:"transferIssue(input: $input)"` } variables := map[string]interface{}{ "input": githubv4.TransferIssueInput{ IssueID: issueID, RepositoryID: destinationRepoID, }, } gql := api.NewClientFromHTTP(httpClient) err := gql.Mutate(destRepo.RepoHost(), "IssueTransfer", &mutation, variables) return mutation.TransferIssue.Issue.URL, err }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/issue/transfer/transfer_test.go
pkg/cmd/issue/transfer/transfer_test.go
package transfer import ( "bytes" "io" "net/http" "testing" "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/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, cli string) (*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 }, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil }, } ios.SetStdoutTTY(true) cmd := NewCmdTransfer(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 TestNewCmdTransfer(t *testing.T) { tests := []struct { name string cli string wants TransferOptions wantBaseRepo ghrepo.Interface wantErr bool }{ { name: "no argument", cli: "", wantErr: true, }, { name: "issue number argument", cli: "--repo cli/repo 23 OWNER/REPO", wants: TransferOptions{ IssueNumber: 23, DestRepoSelector: "OWNER/REPO", }, wantBaseRepo: ghrepo.New("cli", "repo"), }, { name: "argument is hash prefixed number", // Escaping is required here to avoid what I think is shellex treating it as a comment. cli: "--repo cli/repo \\#23 OWNER/REPO", wants: TransferOptions{ IssueNumber: 23, DestRepoSelector: "OWNER/REPO", }, wantBaseRepo: ghrepo.New("cli", "repo"), }, { name: "argument is a URL", cli: "https://github.com/cli/cli/issues/23 OWNER/REPO", wants: TransferOptions{ IssueNumber: 23, DestRepoSelector: "OWNER/REPO", }, wantBaseRepo: ghrepo.New("cli", "cli"), }, { name: "argument cannot be parsed to an issue", cli: "unparseable OWNER/REPO", wantErr: true, }, } 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 *TransferOptions cmd := NewCmdTransfer(f, func(opts *TransferOptions) error { gotOpts = opts return nil }) cmdutil.EnableRepoOverride(cmd, f) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, cErr := cmd.ExecuteC() if tt.wantErr { require.Error(t, cErr) return } require.NoError(t, cErr) assert.Equal(t, tt.wants.IssueNumber, gotOpts.IssueNumber) assert.Equal(t, tt.wants.DestRepoSelector, gotOpts.DestRepoSelector) actualBaseRepo, err := gotOpts.BaseRepo() require.NoError(t, err) assert.True( t, ghrepo.IsSame(tt.wantBaseRepo, actualBaseRepo), "expected base repo %+v, got %+v", tt.wantBaseRepo, actualBaseRepo, ) }) } } func Test_transferRun_noflags(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) output, err := runCommand(http, "") if err != nil { assert.Equal(t, "issue and destination repository are required", err.Error()) } assert.Equal(t, "", output.String()) } func Test_transferRunSuccessfulIssueTransfer(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) http.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "id": "THE-ID", "number": 1234, "title": "The title of the issue"} } } }`)) http.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "id": "dest-id", "name": "REPO1", "owner": { "login": "OWNER1" }, "viewerPermission": "WRITE", "hasIssuesEnabled": true }}}`)) http.Register( httpmock.GraphQL(`mutation IssueTransfer\b`), httpmock.GraphQLMutation(`{"data":{"transferIssue":{"issue":{"url":"https://github.com/OWNER1/REPO1/issues/1"}}}}`, func(input map[string]interface{}) { assert.Equal(t, input["issueId"], "THE-ID") assert.Equal(t, input["repositoryId"], "dest-id") })) output, err := runCommand(http, "1234 OWNER1/REPO1") if err != nil { t.Errorf("error running command `issue transfer`: %v", err) } assert.Equal(t, "https://github.com/OWNER1/REPO1/issues/1\n", output.String()) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/issue/develop/develop_test.go
pkg/cmd/issue/develop/develop_test.go
package develop import ( "bytes" "errors" "net/http" "testing" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/context" "github.com/cli/cli/v2/git" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/run" "github.com/cli/cli/v2/pkg/cmd/issue/argparsetest" "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 TestNewCmdDevelop(t *testing.T) { // Test shared parsing of issue number / URL. argparsetest.TestArgParsing(t, NewCmdDevelop) tests := []struct { name string input string output DevelopOptions expectedBaseRepo ghrepo.Interface wantStdout string wantStderr string wantErr bool errMsg string }{ { name: "branch-repo flag", input: "1 --branch-repo owner/repo", output: DevelopOptions{ IssueNumber: 1, BranchRepo: "owner/repo", }, }, { name: "base flag", input: "1 --base feature", output: DevelopOptions{ IssueNumber: 1, BaseBranch: "feature", }, }, { name: "checkout flag", input: "1 --checkout", output: DevelopOptions{ IssueNumber: 1, Checkout: true, }, }, { name: "list flag", input: "1 --list", output: DevelopOptions{ IssueNumber: 1, List: true, }, }, { name: "name flag", input: "1 --name feature", output: DevelopOptions{ IssueNumber: 1, Name: "feature", }, }, { name: "issue-repo flag", input: "1 --issue-repo cli/cli", output: DevelopOptions{ IssueNumber: 1, }, wantStdout: "Flag --issue-repo has been deprecated, use `--repo` instead\n", }, { name: "list and branch repo flags", input: "1 --list --branch-repo owner/repo", wantErr: true, errMsg: "specify only one of `--list` or `--branch-repo`", }, { name: "list and base flags", input: "1 --list --base feature", wantErr: true, errMsg: "specify only one of `--list` or `--base`", }, { name: "list and checkout flags", input: "1 --list --checkout", wantErr: true, errMsg: "specify only one of `--list` or `--checkout`", }, { name: "list and name flags", input: "1 --list --name my-branch", wantErr: true, errMsg: "specify only one of `--list` or `--name`", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, stdOut, stdErr := iostreams.Test() f := &cmdutil.Factory{ IOStreams: ios, } argv, err := shlex.Split(tt.input) assert.NoError(t, err) var gotOpts *DevelopOptions cmd := NewCmdDevelop(f, func(opts *DevelopOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(stdOut) cmd.SetErr(stdErr) _, err = cmd.ExecuteC() if tt.wantErr { require.EqualError(t, err, tt.errMsg) return } require.NoError(t, err) assert.Equal(t, tt.output.IssueNumber, gotOpts.IssueNumber) assert.Equal(t, tt.output.Name, gotOpts.Name) assert.Equal(t, tt.output.BaseBranch, gotOpts.BaseBranch) assert.Equal(t, tt.output.Checkout, gotOpts.Checkout) assert.Equal(t, tt.output.List, gotOpts.List) assert.Equal(t, tt.wantStdout, stdOut.String()) assert.Equal(t, tt.wantStderr, stdErr.String()) 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 TestDevelopRun(t *testing.T) { featureEnabledPayload := `{"data":{"LinkedBranch":{"fields":[{"name":"id"},{"name":"ref"}]}}}` featureDisabledPayload := `{"data":{"LinkedBranch":null}}` tests := []struct { name string opts *DevelopOptions cmdStubs func(*run.CommandStubber) runStubs func(*run.CommandStubber) remotes map[string]string httpStubs func(*httpmock.Registry, *testing.T) expectedOut string expectedErrOut string wantErr string tty bool }{ { name: "returns an error when the feature is not supported by the API", opts: &DevelopOptions{ IssueNumber: 42, List: true, }, httpStubs: func(reg *httpmock.Registry, t *testing.T) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(`{"data":{"repository":{"hasIssuesEnabled":true,"issue":{"id":"SOMEID","number":42}}}}`), ) reg.Register( httpmock.GraphQL(`query LinkedBranchFeature\b`), httpmock.StringResponse(featureDisabledPayload), ) }, wantErr: "the `gh issue develop` command is not currently available", }, { name: "list branches for an issue", opts: &DevelopOptions{ IssueNumber: 42, List: true, }, httpStubs: func(reg *httpmock.Registry, t *testing.T) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(`{"data":{"repository":{"hasIssuesEnabled":true,"issue":{"id":"SOMEID","number":42}}}}`), ) reg.Register( httpmock.GraphQL(`query LinkedBranchFeature\b`), httpmock.StringResponse(featureEnabledPayload), ) reg.Register( httpmock.GraphQL(`query ListLinkedBranches\b`), httpmock.GraphQLQuery(` {"data":{"repository":{"issue":{"linkedBranches":{"nodes":[{"ref":{"name":"foo","repository":{"url":"https://github.com/OWNER/REPO"}}},{"ref":{"name":"bar","repository":{"url":"https://github.com/OWNER/REPO"}}}]}}}}} `, func(query string, inputs map[string]interface{}) { assert.Equal(t, float64(42), inputs["number"]) assert.Equal(t, "OWNER", inputs["owner"]) assert.Equal(t, "REPO", inputs["name"]) })) }, expectedOut: "foo\thttps://github.com/OWNER/REPO/tree/foo\nbar\thttps://github.com/OWNER/REPO/tree/bar\n", }, { name: "list branches for an issue in tty", opts: &DevelopOptions{ IssueNumber: 42, List: true, }, tty: true, httpStubs: func(reg *httpmock.Registry, t *testing.T) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(`{"data":{"repository":{"hasIssuesEnabled":true,"issue":{"id":"SOMEID","number":42}}}}`), ) reg.Register( httpmock.GraphQL(`query LinkedBranchFeature\b`), httpmock.StringResponse(featureEnabledPayload), ) reg.Register( httpmock.GraphQL(`query ListLinkedBranches\b`), httpmock.GraphQLQuery(` {"data":{"repository":{"issue":{"linkedBranches":{"nodes":[{"ref":{"name":"foo","repository":{"url":"https://github.com/OWNER/REPO"}}},{"ref":{"name":"bar","repository":{"url":"https://github.com/OWNER/OTHER-REPO"}}}]}}}}} `, func(query string, inputs map[string]interface{}) { assert.Equal(t, float64(42), inputs["number"]) assert.Equal(t, "OWNER", inputs["owner"]) assert.Equal(t, "REPO", inputs["name"]) })) }, expectedOut: heredoc.Doc(` Showing linked branches for OWNER/REPO#42 BRANCH URL foo https://github.com/OWNER/REPO/tree/foo bar https://github.com/OWNER/OTHER-REPO/tree/bar `), }, { name: "develop new branch", opts: &DevelopOptions{ IssueNumber: 123, }, remotes: map[string]string{ "origin": "OWNER/REPO", }, httpStubs: func(reg *httpmock.Registry, t *testing.T) { reg.Register( httpmock.GraphQL(`query LinkedBranchFeature\b`), httpmock.StringResponse(featureEnabledPayload), ) reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(`{"data":{"repository":{"hasIssuesEnabled":true,"issue":{"id": "SOMEID","number":123,"title":"my issue"}}}}`), ) reg.Register( httpmock.GraphQL(`query FindRepoBranchID\b`), httpmock.StringResponse(`{"data":{"repository":{"id":"REPOID","defaultBranchRef":{"target":{"oid":"DEFAULTOID"}},"ref":{"target":{"oid":""}}}}}`), ) reg.Register( httpmock.GraphQL(`mutation CreateLinkedBranch\b`), httpmock.GraphQLMutation(`{"data":{"createLinkedBranch":{"linkedBranch":{"id":"2","ref":{"name":"my-issue-1"}}}}}`, func(inputs map[string]interface{}) { assert.Equal(t, "REPOID", inputs["repositoryId"]) assert.Equal(t, "SOMEID", inputs["issueId"]) assert.Equal(t, "DEFAULTOID", inputs["oid"]) }), ) }, runStubs: func(cs *run.CommandStubber) { cs.Register(`git fetch origin \+refs/heads/my-issue-1:refs/remotes/origin/my-issue-1`, 0, "") }, expectedOut: "github.com/OWNER/REPO/tree/my-issue-1\n", }, { name: "develop new branch in different repo than issue", opts: &DevelopOptions{ IssueNumber: 123, BranchRepo: "OWNER2/REPO", }, remotes: map[string]string{ "origin": "OWNER2/REPO", }, httpStubs: func(reg *httpmock.Registry, t *testing.T) { reg.Register( httpmock.GraphQL(`query LinkedBranchFeature\b`), httpmock.StringResponse(featureEnabledPayload), ) reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.GraphQLQuery(`{"data":{"repository":{"hasIssuesEnabled":true,"issue":{"id": "SOMEID","number":123,"title":"my issue"}}}}`, func(_ string, inputs map[string]interface{}) { assert.Equal(t, "OWNER", inputs["owner"]) assert.Equal(t, "REPO", inputs["repo"]) assert.Equal(t, float64(123), inputs["number"]) }), ) reg.Register( httpmock.GraphQL(`query FindRepoBranchID\b`), httpmock.GraphQLQuery(`{"data":{"repository":{"id":"REPOID","defaultBranchRef":{"target":{"oid":"DEFAULTOID"}},"ref":{"target":{"oid":""}}}}}`, func(_ string, inputs map[string]interface{}) { assert.Equal(t, "OWNER2", inputs["owner"]) assert.Equal(t, "REPO", inputs["name"]) }), ) reg.Register( httpmock.GraphQL(`mutation CreateLinkedBranch\b`), httpmock.GraphQLMutation(`{"data":{"createLinkedBranch":{"linkedBranch":{"id":"2","ref":{"name":"my-issue-1"}}}}}`, func(inputs map[string]interface{}) { assert.Equal(t, "REPOID", inputs["repositoryId"]) assert.Equal(t, "SOMEID", inputs["issueId"]) assert.Equal(t, "DEFAULTOID", inputs["oid"]) }), ) }, runStubs: func(cs *run.CommandStubber) { cs.Register(`git fetch origin \+refs/heads/my-issue-1:refs/remotes/origin/my-issue-1`, 0, "") }, expectedOut: "github.com/OWNER2/REPO/tree/my-issue-1\n", }, { name: "develop new branch with name and base specified", opts: &DevelopOptions{ Name: "my-branch", BaseBranch: "main", IssueNumber: 123, }, remotes: map[string]string{ "origin": "OWNER/REPO", }, httpStubs: func(reg *httpmock.Registry, t *testing.T) { reg.Register( httpmock.GraphQL(`query LinkedBranchFeature\b`), httpmock.StringResponse(featureEnabledPayload), ) reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(`{"data":{"repository":{ "hasIssuesEnabled":true,"issue":{"id":"SOMEID","number":123,"title":"my issue"}}}}`), ) reg.Register( httpmock.GraphQL(`query FindRepoBranchID\b`), httpmock.StringResponse(`{"data":{"repository":{"id":"REPOID","ref":{"target":{"oid":"OID"}}}}}`)) reg.Register( httpmock.GraphQL(`mutation CreateLinkedBranch\b`), httpmock.GraphQLMutation(`{"data":{"createLinkedBranch":{"linkedBranch":{"id":"2","ref":{"name":"my-branch"}}}}}`, func(inputs map[string]interface{}) { assert.Equal(t, "REPOID", inputs["repositoryId"]) assert.Equal(t, "SOMEID", inputs["issueId"]) assert.Equal(t, "OID", inputs["oid"]) assert.Equal(t, "my-branch", inputs["name"]) }), ) }, runStubs: func(cs *run.CommandStubber) { cs.Register(`git fetch origin \+refs/heads/my-branch:refs/remotes/origin/my-branch`, 0, "") cs.Register(`git config branch\.my-branch\.gh-merge-base main`, 0, "") }, expectedOut: "github.com/OWNER/REPO/tree/my-branch\n", }, { name: "develop new branch outside of local git repo", opts: &DevelopOptions{ IssueNumber: 123, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("cli", "cli"), nil }, }, httpStubs: func(reg *httpmock.Registry, t *testing.T) { reg.Register( httpmock.GraphQL(`query LinkedBranchFeature\b`), httpmock.StringResponse(featureEnabledPayload), ) reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(`{"data":{"repository":{"hasIssuesEnabled":true,"issue":{"id": "SOMEID","number":123,"title":"my issue"}}}}`), ) reg.Register( httpmock.GraphQL(`query FindRepoBranchID\b`), httpmock.StringResponse(`{"data":{"repository":{"id":"REPOID","defaultBranchRef":{"target":{"oid":"DEFAULTOID"}},"ref":{"target":{"oid":""}}}}}`), ) reg.Register( httpmock.GraphQL(`mutation CreateLinkedBranch\b`), httpmock.GraphQLMutation(`{"data":{"createLinkedBranch":{"linkedBranch":{"id":"2","ref":{"name":"my-issue-1"}}}}}`, func(inputs map[string]interface{}) { assert.Equal(t, "REPOID", inputs["repositoryId"]) assert.Equal(t, "SOMEID", inputs["issueId"]) assert.Equal(t, "DEFAULTOID", inputs["oid"]) }), ) }, expectedOut: "github.com/cli/cli/tree/my-issue-1\n", }, { name: "develop new branch with checkout when local branch exists", opts: &DevelopOptions{ Name: "my-branch", IssueNumber: 123, Checkout: true, }, remotes: map[string]string{ "origin": "OWNER/REPO", }, httpStubs: func(reg *httpmock.Registry, t *testing.T) { reg.Register( httpmock.GraphQL(`query LinkedBranchFeature\b`), httpmock.StringResponse(featureEnabledPayload), ) reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(`{"data":{"repository":{"hasIssuesEnabled":true,"issue":{"id": "SOMEID","number":123,"title":"my issue"}}}}`), ) reg.Register( httpmock.GraphQL(`query FindRepoBranchID\b`), httpmock.StringResponse(`{"data":{"repository":{"id":"REPOID","ref":{"target":{"oid":"OID"}}}}}`), ) reg.Register( httpmock.GraphQL(`mutation CreateLinkedBranch\b`), httpmock.GraphQLMutation(`{"data":{"createLinkedBranch":{"linkedBranch":{"id":"2","ref":{"name":"my-branch"}}}}}`, func(inputs map[string]interface{}) { assert.Equal(t, "REPOID", inputs["repositoryId"]) assert.Equal(t, "SOMEID", inputs["issueId"]) assert.Equal(t, "OID", inputs["oid"]) assert.Equal(t, "my-branch", inputs["name"]) }), ) }, runStubs: func(cs *run.CommandStubber) { cs.Register(`git fetch origin \+refs/heads/my-branch:refs/remotes/origin/my-branch`, 0, "") cs.Register(`git rev-parse --verify refs/heads/my-branch`, 0, "") cs.Register(`git checkout my-branch`, 0, "") cs.Register(`git pull --ff-only origin my-branch`, 0, "") }, expectedOut: "github.com/OWNER/REPO/tree/my-branch\n", }, { name: "develop new branch with checkout when local branch does not exist", opts: &DevelopOptions{ Name: "my-branch", IssueNumber: 123, Checkout: true, }, remotes: map[string]string{ "origin": "OWNER/REPO", }, httpStubs: func(reg *httpmock.Registry, t *testing.T) { reg.Register( httpmock.GraphQL(`query LinkedBranchFeature\b`), httpmock.StringResponse(featureEnabledPayload), ) reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(`{"data":{"repository":{"hasIssuesEnabled":true,"issue":{"id": "SOMEID","number":123,"title":"my issue"}}}}`), ) reg.Register( httpmock.GraphQL(`query FindRepoBranchID\b`), httpmock.StringResponse(`{"data":{"repository":{"id":"REPOID","ref":{"target":{"oid":"OID"}}}}}`), ) reg.Register( httpmock.GraphQL(`mutation CreateLinkedBranch\b`), httpmock.GraphQLMutation(`{"data":{"createLinkedBranch":{"linkedBranch":{"id":"2","ref":{"name":"my-branch"}}}}}`, func(inputs map[string]interface{}) { assert.Equal(t, "REPOID", inputs["repositoryId"]) assert.Equal(t, "SOMEID", inputs["issueId"]) assert.Equal(t, "OID", inputs["oid"]) assert.Equal(t, "my-branch", inputs["name"]) }), ) }, runStubs: func(cs *run.CommandStubber) { cs.Register(`git fetch origin \+refs/heads/my-branch:refs/remotes/origin/my-branch`, 0, "") cs.Register(`git rev-parse --verify refs/heads/my-branch`, 1, "") cs.Register(`git checkout -b my-branch --track origin/my-branch`, 0, "") }, expectedOut: "github.com/OWNER/REPO/tree/my-branch\n", }, { name: "develop with base branch which does not exist", opts: &DevelopOptions{ IssueNumber: 123, BaseBranch: "does-not-exist-branch", }, remotes: map[string]string{ "origin": "OWNER/REPO", }, httpStubs: func(reg *httpmock.Registry, t *testing.T) { reg.Register( httpmock.GraphQL(`query LinkedBranchFeature\b`), httpmock.StringResponse(featureEnabledPayload), ) reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(`{"data":{"repository":{"hasIssuesEnabled":true,"issue":{"id": "SOMEID","number":123,"title":"my issue"}}}}`), ) reg.Register( httpmock.GraphQL(`query FindRepoBranchID\b`), httpmock.StringResponse(`{"data":{"repository":{"id":"REPOID","defaultBranchRef":{"target":{"oid":"DEFAULTOID"}},"ref":null}}}`), ) }, wantErr: "could not find branch \"does-not-exist-branch\" in OWNER/REPO", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { opts := tt.opts reg := &httpmock.Registry{} defer reg.Verify(t) if tt.httpStubs != nil { tt.httpStubs(reg, t) } 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) opts.IO = ios if opts.BaseRepo == nil { opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil } } 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", } cmdStubs, cmdTeardown := run.Stub() defer cmdTeardown(t) if tt.runStubs != nil { tt.runStubs(cmdStubs) } err := developRun(opts) if tt.wantErr != "" { assert.EqualError(t, err, tt.wantErr) return } else { assert.NoError(t, err) assert.Equal(t, tt.expectedOut, stdout.String()) assert.Equal(t, tt.expectedErrOut, stderr.String()) } }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/issue/develop/develop.go
pkg/cmd/issue/develop/develop.go
package develop import ( ctx "context" "fmt" "net/http" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/context" "github.com/cli/cli/v2/git" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/tableprinter" "github.com/cli/cli/v2/pkg/cmd/issue/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type DevelopOptions struct { HttpClient func() (*http.Client, error) GitClient *git.Client IO *iostreams.IOStreams BaseRepo func() (ghrepo.Interface, error) Remotes func() (context.Remotes, error) IssueNumber int Name string BranchRepo string BaseBranch string Checkout bool List bool } func NewCmdDevelop(f *cmdutil.Factory, runF func(*DevelopOptions) error) *cobra.Command { opts := &DevelopOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, GitClient: f.GitClient, BaseRepo: f.BaseRepo, Remotes: f.Remotes, } cmd := &cobra.Command{ Use: "develop {<number> | <url>}", Short: "Manage linked branches for an issue", Long: heredoc.Docf(` Manage linked branches for an issue. When using the %[1]s--base%[1]s flag, the new development branch will be created from the specified remote branch. The new branch will be configured as the base branch for pull requests created using %[1]sgh pr create%[1]s. `, "`"), Example: heredoc.Doc(` # List branches for issue 123 $ gh issue develop --list 123 # List branches for issue 123 in repo cli/cli $ gh issue develop --list --repo cli/cli 123 # Create a branch for issue 123 based on the my-feature branch $ gh issue develop 123 --base my-feature # Create a branch for issue 123 and check it out $ gh issue develop 123 --checkout # Create a branch in repo monalisa/cli for issue 123 in repo cli/cli $ gh issue develop 123 --repo cli/cli --branch-repo monalisa/cli `), Args: cmdutil.ExactArgs(1, "issue number or url is required"), PersistentPreRunE: func(cmd *cobra.Command, args []string) error { // This is all a hack to not break the deprecated issue-repo flag. // It will be removed in the near future and this hack can be removed at the same time. flags := cmd.Flags() if flags.Changed("issue-repo") { if flags.Changed("repo") { if flags.Changed("branch-repo") { return cmdutil.FlagErrorf("specify only `--repo` and `--branch-repo`") } branchRepo, _ := flags.GetString("repo") _ = flags.Set("branch-repo", branchRepo) } repo, _ := flags.GetString("issue-repo") _ = flags.Set("repo", repo) } if cmd.Parent() != nil { return cmd.Parent().PersistentPreRunE(cmd, args) } return nil }, RunE: func(cmd *cobra.Command, args []string) error { issueNumber, baseRepo, err := shared.ParseIssueFromArg(args[0]) if err != nil { return err } // If the args provided the base repo then use that directly. if baseRepo, present := baseRepo.Value(); present { opts.BaseRepo = func() (ghrepo.Interface, error) { return baseRepo, nil } } else { // support `-R, --repo` override opts.BaseRepo = f.BaseRepo } opts.IssueNumber = issueNumber if err := cmdutil.MutuallyExclusive("specify only one of `--list` or `--branch-repo`", opts.List, opts.BranchRepo != ""); err != nil { return err } if err := cmdutil.MutuallyExclusive("specify only one of `--list` or `--base`", opts.List, opts.BaseBranch != ""); err != nil { return err } if err := cmdutil.MutuallyExclusive("specify only one of `--list` or `--checkout`", opts.List, opts.Checkout); err != nil { return err } if err := cmdutil.MutuallyExclusive("specify only one of `--list` or `--name`", opts.List, opts.Name != ""); err != nil { return err } if runF != nil { return runF(opts) } return developRun(opts) }, } fl := cmd.Flags() fl.StringVar(&opts.BranchRepo, "branch-repo", "", "Name or URL of the repository where you want to create your new branch") fl.StringVarP(&opts.BaseBranch, "base", "b", "", "Name of the remote branch you want to make your new branch from") fl.BoolVarP(&opts.Checkout, "checkout", "c", false, "Checkout the branch after creating it") fl.BoolVarP(&opts.List, "list", "l", false, "List linked branches for the issue") fl.StringVarP(&opts.Name, "name", "n", "", "Name of the branch to create") var issueRepoSelector string fl.StringVarP(&issueRepoSelector, "issue-repo", "i", "", "Name or URL of the issue's repository") _ = cmd.Flags().MarkDeprecated("issue-repo", "use `--repo` instead") return cmd } func developRun(opts *DevelopOptions) error { httpClient, err := opts.HttpClient() if err != nil { return err } baseRepo, err := opts.BaseRepo() if err != nil { return err } opts.IO.StartProgressIndicator() issue, err := shared.FindIssueOrPR(httpClient, baseRepo, opts.IssueNumber, []string{"id", "number"}) opts.IO.StopProgressIndicator() if err != nil { return err } apiClient := api.NewClientFromHTTP(httpClient) opts.IO.StartProgressIndicator() err = api.CheckLinkedBranchFeature(apiClient, baseRepo.RepoHost()) opts.IO.StopProgressIndicator() if err != nil { return err } if opts.List { return developRunList(opts, apiClient, baseRepo, issue) } return developRunCreate(opts, apiClient, baseRepo, issue) } func developRunCreate(opts *DevelopOptions, apiClient *api.Client, issueRepo ghrepo.Interface, issue *api.Issue) error { branchRepo := issueRepo var repoID string if opts.BranchRepo != "" { var err error branchRepo, err = ghrepo.FromFullName(opts.BranchRepo) if err != nil { return err } } opts.IO.StartProgressIndicator() repoID, branchID, err := api.FindRepoBranchID(apiClient, branchRepo, opts.BaseBranch) opts.IO.StopProgressIndicator() if err != nil { return err } opts.IO.StartProgressIndicator() branchName, err := api.CreateLinkedBranch(apiClient, branchRepo.RepoHost(), repoID, issue.ID, branchID, opts.Name) opts.IO.StopProgressIndicator() if err != nil { return err } // Remember which branch to target when creating a PR. if opts.BaseBranch != "" { err = opts.GitClient.SetBranchConfig(ctx.Background(), branchName, git.MergeBaseConfig, opts.BaseBranch) if err != nil { return err } } fmt.Fprintf(opts.IO.Out, "%s/%s/tree/%s\n", branchRepo.RepoHost(), ghrepo.FullName(branchRepo), branchName) return checkoutBranch(opts, branchRepo, branchName) } func developRunList(opts *DevelopOptions, apiClient *api.Client, issueRepo ghrepo.Interface, issue *api.Issue) error { opts.IO.StartProgressIndicator() branches, err := api.ListLinkedBranches(apiClient, issueRepo, issue.Number) opts.IO.StopProgressIndicator() if err != nil { return err } if len(branches) == 0 { return cmdutil.NewNoResultsError(fmt.Sprintf("no linked branches found for %s#%d", ghrepo.FullName(issueRepo), issue.Number)) } if opts.IO.IsStdoutTTY() { fmt.Fprintf(opts.IO.Out, "\nShowing linked branches for %s#%d\n\n", ghrepo.FullName(issueRepo), issue.Number) } printLinkedBranches(opts.IO, branches) return nil } func printLinkedBranches(io *iostreams.IOStreams, branches []api.LinkedBranch) { cs := io.ColorScheme() table := tableprinter.New(io, tableprinter.WithHeader("BRANCH", "URL")) for _, branch := range branches { table.AddField(branch.BranchName, tableprinter.WithColor(cs.ColorFromString("cyan"))) table.AddField(branch.URL) table.EndRow() } _ = table.Render() } func checkoutBranch(opts *DevelopOptions, branchRepo ghrepo.Interface, checkoutBranch string) (err error) { remotes, err := opts.Remotes() if err != nil { // If the user specified the branch to be checked out and no remotes are found // display an error. Otherwise bail out silently, likely the command was not // run from inside a git directory. if opts.Checkout { return err } else { return nil } } baseRemote, err := remotes.FindByRepo(branchRepo.RepoOwner(), branchRepo.RepoName()) if err != nil { // If the user specified the branch to be checked out and no remote matches the // base repo, then display an error. Otherwise bail out silently. if opts.Checkout { return err } else { return nil } } gc := opts.GitClient if err := gc.Fetch(ctx.Background(), baseRemote.Name, fmt.Sprintf("+refs/heads/%[1]s:refs/remotes/%[2]s/%[1]s", checkoutBranch, baseRemote.Name)); err != nil { return err } if !opts.Checkout { return nil } if gc.HasLocalBranch(ctx.Background(), checkoutBranch) { if err := gc.CheckoutBranch(ctx.Background(), checkoutBranch); err != nil { return err } if err := gc.Pull(ctx.Background(), baseRemote.Name, checkoutBranch); err != nil { _, _ = fmt.Fprintf(opts.IO.ErrOut, "%s warning: not possible to fast-forward to: %q\n", opts.IO.ColorScheme().WarningIcon(), checkoutBranch) } } else { if err := gc.CheckoutNewBranch(ctx.Background(), baseRemote.Name, checkoutBranch); 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/issue/list/list_test.go
pkg/cmd/issue/list/list_test.go
package list import ( "bytes" "io" "net/http" "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/config" fd "github.com/cli/cli/v2/internal/featuredetection" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/run" 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, 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 }, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil }, } fakeNow := func() time.Time { return time.Date(2022, time.August, 25, 23, 50, 0, 0, time.UTC) } cmd := NewCmdList(factory, func(opts *ListOptions) error { opts.Now = fakeNow 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, }, err } func TestIssueList_nontty(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) http.Register( httpmock.GraphQL(`query IssueList\b`), httpmock.FileResponse("./fixtures/issueList.json")) output, err := runCommand(http, false, "") if err != nil { t.Errorf("error running command `issue list`: %v", err) } assert.Equal(t, "", output.Stderr()) //nolint:staticcheck // prefer exact matchers over ExpectLines test.ExpectLines(t, output.String(), `1[\t]+number won[\t]+label[\t]+\d+`, `2[\t]+number too[\t]+label[\t]+\d+`, `4[\t]+number fore[\t]+label[\t]+\d+`) } func TestIssueList_tty(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) http.Register( httpmock.GraphQL(`query IssueList\b`), httpmock.FileResponse("./fixtures/issueList.json")) output, err := runCommand(http, true, "") if err != nil { t.Errorf("error running command `issue list`: %v", err) } assert.Equal(t, heredoc.Doc(` Showing 3 of 3 open issues in OWNER/REPO ID TITLE LABELS UPDATED #1 number won label about 1 day ago #2 number too label about 1 month ago #4 number fore label about 2 years ago `), output.String()) assert.Equal(t, ``, output.Stderr()) } func TestIssueList_tty_withFlags(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) http.Register( httpmock.GraphQL(`query IssueList\b`), httpmock.GraphQLQuery(` { "data": { "repository": { "hasIssuesEnabled": true, "issues": { "nodes": [] } } } }`, func(_ string, params map[string]interface{}) { assert.Equal(t, "probablyCher", params["assignee"].(string)) assert.Equal(t, "foo", params["author"].(string)) assert.Equal(t, "me", params["mention"].(string)) assert.Equal(t, []interface{}{"OPEN"}, params["states"].([]interface{})) })) output, err := runCommand(http, true, "-a probablyCher -s open -A foo --mention me") assert.EqualError(t, err, "no issues match your search in OWNER/REPO") assert.Equal(t, "", output.String()) assert.Equal(t, "", output.Stderr()) } func TestIssueList_tty_withAppFlag(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) http.Register( httpmock.GraphQL(`query IssueList\b`), httpmock.GraphQLQuery(` { "data": { "repository": { "hasIssuesEnabled": true, "issues": { "nodes": [] } } } }`, func(_ string, params map[string]interface{}) { assert.Equal(t, "app/dependabot", params["author"].(string)) })) output, err := runCommand(http, true, "--app dependabot") assert.EqualError(t, err, "no issues match your search in OWNER/REPO") assert.Equal(t, "", output.String()) assert.Equal(t, "", output.Stderr()) } func TestIssueList_withInvalidLimitFlag(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) _, err := runCommand(http, true, "--limit=0") if err == nil || err.Error() != "invalid limit: 0" { t.Errorf("error running command `issue list`: %v", err) } } func TestIssueList_disabledIssues(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) http.Register( httpmock.GraphQL(`query IssueList\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": false } } }`), ) _, err := runCommand(http, true, "") if err == nil || err.Error() != "the 'OWNER/REPO' repository has disabled issues" { t.Errorf("error running command `issue list`: %v", err) } } // TODO advancedIssueSearchCleanup // Simplify this test to only a single test case once GHES 3.17 support ends. func TestIssueList_web(t *testing.T) { tests := []struct { name string detector fd.Detector }{ { name: "advanced issue search not supported", detector: fd.AdvancedIssueSearchUnsupported(), }, { name: "advanced issue search supported as opt-in", detector: fd.AdvancedIssueSearchSupportedAsOptIn(), }, { name: "advanced issue search supported as only backend", detector: fd.AdvancedIssueSearchSupportedAsOnlyBackend(), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, stdout, stderr := iostreams.Test() ios.SetStdoutTTY(true) ios.SetStderrTTY(true) browser := &browser.Stub{} reg := &httpmock.Registry{} defer reg.Verify(t) _, cmdTeardown := run.Stub() defer cmdTeardown(t) opts := &ListOptions{ IO: ios, Browser: browser, HttpClient: func() (*http.Client, error) { return &http.Client{Transport: reg}, nil }, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil }, Detector: tt.detector, WebMode: true, State: "all", Assignee: "peter", Author: "john", Labels: []string{"bug", "docs"}, Mention: "frank", Milestone: "v1.1", LimitResults: 10, } err := listRun(opts) require.NoError(t, err) assert.Equal(t, "", stdout.String()) assert.Equal(t, "Opening https://github.com/OWNER/REPO/issues in your browser.\n", stderr.String()) // Since no repeated usage of special search qualifiers is possible // with our current implementation, we can assert against the same // URL for both search backend (i.e. legacy and advanced issue search). browser.Verify(t, "https://github.com/OWNER/REPO/issues?q=assignee%3Apeter+author%3Ajohn+label%3Abug+label%3Adocs+mentions%3Afrank+milestone%3Av1.1+type%3Aissue") }) } } func Test_issueList(t *testing.T) { type args struct { detector fd.Detector repo ghrepo.Interface filters prShared.FilterOptions limit int } tests := []struct { name string args args httpStubs func(*httpmock.Registry) wantErr bool }{ { name: "default", args: args{ limit: 30, repo: ghrepo.New("OWNER", "REPO"), filters: prShared.FilterOptions{ Entity: "issue", State: "open", }, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueList\b`), httpmock.GraphQLQuery(` { "data": { "repository": { "hasIssuesEnabled": true, "issues": { "nodes": [] } } } }`, func(_ string, params map[string]interface{}) { assert.Equal(t, map[string]interface{}{ "owner": "OWNER", "repo": "REPO", "limit": float64(30), "states": []interface{}{"OPEN"}, }, params) })) }, }, { name: "milestone by number", args: args{ // TODO advancedIssueSearchCleanup // No need for feature detection once GHES 3.17 support ends. detector: fd.AdvancedIssueSearchSupportedAsOptIn(), limit: 30, repo: ghrepo.New("OWNER", "REPO"), filters: prShared.FilterOptions{ Entity: "issue", State: "open", Milestone: "13", }, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryMilestoneByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "milestone": { "title": "1.x" } } } } `)) reg.Register( httpmock.GraphQL(`query IssueSearch\b`), httpmock.GraphQLQuery(` { "data": { "repository": { "hasIssuesEnabled": true }, "search": { "issueCount": 0, "nodes": [] } } }`, func(_ string, params map[string]interface{}) { assert.Equal(t, map[string]interface{}{ "owner": "OWNER", "repo": "REPO", "limit": float64(30), "query": "milestone:1.x repo:OWNER/REPO state:open type:issue", "type": "ISSUE_ADVANCED", }, params) })) }, }, { name: "milestone by title", args: args{ // TODO advancedIssueSearchCleanup // No need for feature detection once GHES 3.17 support ends. detector: fd.AdvancedIssueSearchSupportedAsOptIn(), limit: 30, repo: ghrepo.New("OWNER", "REPO"), filters: prShared.FilterOptions{ Entity: "issue", State: "open", Milestone: "1.x", }, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueSearch\b`), httpmock.GraphQLQuery(` { "data": { "repository": { "hasIssuesEnabled": true }, "search": { "issueCount": 0, "nodes": [] } } }`, func(_ string, params map[string]interface{}) { assert.Equal(t, map[string]interface{}{ "owner": "OWNER", "repo": "REPO", "limit": float64(30), "query": "milestone:1.x repo:OWNER/REPO state:open type:issue", "type": "ISSUE_ADVANCED", }, params) })) }, }, { name: "@me syntax", args: args{ limit: 30, repo: ghrepo.New("OWNER", "REPO"), filters: prShared.FilterOptions{ Entity: "issue", State: "open", Author: "@me", Assignee: "@me", Mention: "@me", }, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data": {"viewer": {"login": "monalisa"} } }`)) reg.Register( httpmock.GraphQL(`query IssueList\b`), httpmock.GraphQLQuery(` { "data": { "repository": { "hasIssuesEnabled": true, "issues": { "nodes": [] } } } }`, func(_ string, params map[string]interface{}) { assert.Equal(t, map[string]interface{}{ "owner": "OWNER", "repo": "REPO", "limit": float64(30), "states": []interface{}{"OPEN"}, "assignee": "monalisa", "author": "monalisa", "mention": "monalisa", }, params) })) }, }, { name: "@me with search", args: args{ // TODO advancedIssueSearchCleanup // No need for feature detection once GHES 3.17 support ends. detector: fd.AdvancedIssueSearchSupportedAsOptIn(), limit: 30, repo: ghrepo.New("OWNER", "REPO"), filters: prShared.FilterOptions{ Entity: "issue", State: "open", Author: "@me", Assignee: "@me", Mention: "@me", Search: "auth bug", }, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueSearch\b`), httpmock.GraphQLQuery(` { "data": { "repository": { "hasIssuesEnabled": true }, "search": { "issueCount": 0, "nodes": [] } } }`, func(_ string, params map[string]interface{}) { assert.Equal(t, map[string]interface{}{ "owner": "OWNER", "repo": "REPO", "limit": float64(30), "query": "( auth bug ) assignee:@me author:@me mentions:@me repo:OWNER/REPO state:open type:issue", "type": "ISSUE_ADVANCED", }, params) })) }, }, { name: "with labels", args: args{ // TODO advancedIssueSearchCleanup // No need for feature detection once GHES 3.17 support ends. detector: fd.AdvancedIssueSearchSupportedAsOptIn(), limit: 30, repo: ghrepo.New("OWNER", "REPO"), filters: prShared.FilterOptions{ Entity: "issue", State: "open", Labels: []string{"hello", "one world"}, }, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueSearch\b`), httpmock.GraphQLQuery(` { "data": { "repository": { "hasIssuesEnabled": true }, "search": { "issueCount": 0, "nodes": [] } } }`, func(_ string, params map[string]interface{}) { assert.Equal(t, map[string]interface{}{ "owner": "OWNER", "repo": "REPO", "limit": float64(30), "query": `label:"one world" label:hello repo:OWNER/REPO state:open type:issue`, "type": "ISSUE_ADVANCED", }, params) })) }, }, } 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) } client := &http.Client{Transport: httpreg} _, err := issueList(client, tt.args.detector, tt.args.repo, tt.args.filters, tt.args.limit) if tt.wantErr { assert.Error(t, err) } else { assert.NoError(t, err) } }) } } func TestIssueList_withProjectItems(t *testing.T) { reg := &httpmock.Registry{} defer reg.Verify(t) reg.Register( httpmock.GraphQL(`query IssueList\b`), httpmock.GraphQLQuery(`{ "data": { "repository": { "hasIssuesEnabled": true, "issues": { "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), "states": []interface{}{"OPEN"}, }, params) })) client := &http.Client{Transport: reg} issuesAndTotalCount, err := issueList( client, nil, ghrepo.New("OWNER", "REPO"), prShared.FilterOptions{ Entity: "issue", }, 30, ) require.NoError(t, err) require.Len(t, issuesAndTotalCount.Issues, 1) require.Len(t, issuesAndTotalCount.Issues[0].ProjectItems.Nodes, 1) require.Equal(t, issuesAndTotalCount.Issues[0].ProjectItems.Nodes[0].ID, "PVTI_lAHOAA3WC84AW6WNzgJ8rnQ") expectedProject := api.ProjectV2ItemProject{ ID: "PVT_kwHOAA3WC84AW6WN", Title: "Test Public Project", } require.Equal(t, issuesAndTotalCount.Issues[0].ProjectItems.Nodes[0].Project, expectedProject) expectedStatus := api.ProjectV2ItemStatus{ OptionID: "47fc9ee4", Name: "In Progress", } require.Equal(t, issuesAndTotalCount.Issues[0].ProjectItems.Nodes[0].Status, expectedStatus) } func TestIssueList_Search_withProjectItems(t *testing.T) { reg := &httpmock.Registry{} defer reg.Verify(t) reg.Register( httpmock.GraphQL(`query IssueSearch\b`), httpmock.GraphQLQuery(`{ "data": { "repository": { "hasIssuesEnabled": true }, "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{}{ "owner": "OWNER", "repo": "REPO", "type": "ISSUE_ADVANCED", "limit": float64(30), "query": "( just used to force the search API branch ) repo:OWNER/REPO type:issue", }, params) })) client := &http.Client{Transport: reg} issuesAndTotalCount, err := issueList( client, // TODO advancedIssueSearchCleanup // No need for feature detection once GHES 3.17 support ends. fd.AdvancedIssueSearchSupportedAsOptIn(), ghrepo.New("OWNER", "REPO"), prShared.FilterOptions{ Entity: "issue", Search: "just used to force the search API branch", }, 30, ) require.NoError(t, err) require.Len(t, issuesAndTotalCount.Issues, 1) require.Len(t, issuesAndTotalCount.Issues[0].ProjectItems.Nodes, 1) require.Equal(t, issuesAndTotalCount.Issues[0].ProjectItems.Nodes[0].ID, "PVTI_lAHOAA3WC84AW6WNzgJ8rl0") expectedProject := api.ProjectV2ItemProject{ ID: "PVT_kwHOAA3WC84AW6WN", Title: "Test Public Project", } require.Equal(t, issuesAndTotalCount.Issues[0].ProjectItems.Nodes[0].Project, expectedProject) expectedStatus := api.ProjectV2ItemStatus{ OptionID: "47fc9ee4", Name: "In Progress", } require.Equal(t, issuesAndTotalCount.Issues[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/issue/list/list.go
pkg/cmd/issue/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/gh" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/text" issueShared "github.com/cli/cli/v2/pkg/cmd/issue/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/shurcooL/githubv4" "github.com/spf13/cobra" ) type ListOptions struct { HttpClient func() (*http.Client, error) Config func() (gh.Config, error) IO *iostreams.IOStreams BaseRepo func() (ghrepo.Interface, error) Browser browser.Browser Assignee string Labels []string State string LimitResults int Author string Mention string Milestone string Search string WebMode bool Exporter cmdutil.Exporter Detector fd.Detector Now func() time.Time } func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Command { opts := &ListOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, Config: f.Config, Browser: f.Browser, Now: time.Now, } var appAuthor string cmd := &cobra.Command{ Use: "list", Short: "List issues in a repository", // TODO advancedIssueSearchCleanup // Update the links and remove the mention at GHES 3.17 version. Long: heredoc.Docf(` List issues in a GitHub repository. By default, this only lists open issues. 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(` $ gh issue list --label "bug" --label "help wanted" $ gh issue list --author monalisa $ gh issue list --assignee "@me" $ gh issue list --milestone "The big 1.0" $ gh issue list --search "error no:assignee sort:created-asc" $ gh issue list --state all `), 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 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 issues in the web browser") cmd.Flags().StringVarP(&opts.Assignee, "assignee", "a", "", "Filter by assignee") cmd.Flags().StringSliceVarP(&opts.Labels, "label", "l", nil, "Filter by label") cmdutil.StringEnumFlag(cmd, &opts.State, "state", "s", "open", []string{"open", "closed", "all"}, "Filter by state") cmd.Flags().IntVarP(&opts.LimitResults, "limit", "L", 30, "Maximum number of issues to fetch") cmd.Flags().StringVarP(&opts.Author, "author", "A", "", "Filter by author") cmd.Flags().StringVar(&appAuthor, "app", "", "Filter by GitHub App author") cmd.Flags().StringVar(&opts.Mention, "mention", "", "Filter by mention") cmd.Flags().StringVarP(&opts.Milestone, "milestone", "m", "", "Filter by milestone number or title") cmd.Flags().StringVarP(&opts.Search, "search", "S", "", "Search issues with `query`") cmdutil.AddJSONFlags(cmd, &opts.Exporter, api.IssueFields) return cmd } var defaultFields = []string{ "number", "title", "url", "state", "updatedAt", "labels", } func listRun(opts *ListOptions) error { httpClient, err := opts.HttpClient() if err != nil { return err } baseRepo, err := opts.BaseRepo() if err != nil { return err } issueState := strings.ToLower(opts.State) if issueState == "open" && prShared.QueryHasStateClause(opts.Search) { issueState = "" } if opts.Detector == nil { cachedClient := api.NewCachedHTTPClient(httpClient, time.Hour*24) opts.Detector = fd.NewDetector(cachedClient, baseRepo.RepoHost()) } features, err := opts.Detector.IssueFeatures() if err != nil { return err } fields := defaultFields if features.StateReason { fields = append(defaultFields, "stateReason") } filterOptions := prShared.FilterOptions{ Entity: "issue", State: issueState, Assignee: opts.Assignee, Labels: opts.Labels, Author: opts.Author, Mention: opts.Mention, Milestone: opts.Milestone, Search: opts.Search, Fields: fields, } isTerminal := opts.IO.IsStdoutTTY() if opts.WebMode { // 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, and the GUI (i.e. Issues tab of repos) already supports the // advanced syntax. searchFeatures, err := opts.Detector.SearchFeatures() if err != nil { return err } issueListURL := ghrepo.GenerateRepoURL(baseRepo, "issues") // Note that if the advanced issue search API is available, the syntax is // also supported in the Issues tab. openURL, err := prShared.ListURLWithQuery(issueListURL, filterOptions, searchFeatures.AdvancedIssueSearchAPI) if err != nil { return err } if isTerminal { fmt.Fprintf(opts.IO.ErrOut, "Opening %s in your browser.\n", text.DisplayURL(openURL)) } return opts.Browser.Browse(openURL) } if opts.Exporter != nil { filterOptions.Fields = opts.Exporter.Fields() } listResult, err := issueList(httpClient, opts.Detector, baseRepo, filterOptions, opts.LimitResults) if err != nil { return err } if len(listResult.Issues) == 0 && opts.Exporter == nil { return prShared.ListNoResults(ghrepo.FullName(baseRepo), "issue", !filterOptions.IsDefault()) } 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, listResult.Issues) } if listResult.SearchCapped { fmt.Fprintln(opts.IO.ErrOut, "warning: this query uses the Search API which is capped at 1000 results maximum") } if isTerminal { title := prShared.ListHeader(ghrepo.FullName(baseRepo), "issue", len(listResult.Issues), listResult.TotalCount, !filterOptions.IsDefault()) fmt.Fprintf(opts.IO.Out, "\n%s\n\n", title) } issueShared.PrintIssues(opts.IO, opts.Now(), "", len(listResult.Issues), listResult.Issues) return nil } func issueList(client *http.Client, detector fd.Detector, repo ghrepo.Interface, filters prShared.FilterOptions, limit int) (*api.IssuesAndTotalCount, error) { apiClient := api.NewClientFromHTTP(client) if filters.Search != "" || len(filters.Labels) > 0 || filters.Milestone != "" { if milestoneNumber, err := strconv.ParseInt(filters.Milestone, 10, 32); err == nil { milestone, err := milestoneByNumber(client, repo, int32(milestoneNumber)) if err != nil { return nil, err } filters.Milestone = milestone.Title } return searchIssues(apiClient, detector, repo, filters, limit) } var err error meReplacer := prShared.NewMeReplacer(apiClient, repo.RepoHost()) filters.Assignee, err = meReplacer.Replace(filters.Assignee) if err != nil { return nil, err } filters.Author, err = meReplacer.Replace(filters.Author) if err != nil { return nil, err } filters.Mention, err = meReplacer.Replace(filters.Mention) if err != nil { return nil, err } return listIssues(apiClient, repo, filters, limit) } func milestoneByNumber(client *http.Client, repo ghrepo.Interface, number int32) (*api.RepoMilestone, error) { var query struct { Repository struct { Milestone *api.RepoMilestone `graphql:"milestone(number: $number)"` } `graphql:"repository(owner: $owner, name: $name)"` } variables := map[string]interface{}{ "owner": githubv4.String(repo.RepoOwner()), "name": githubv4.String(repo.RepoName()), "number": githubv4.Int(number), } gql := api.NewClientFromHTTP(client) if err := gql.Query(repo.RepoHost(), "RepositoryMilestoneByNumber", &query, variables); err != nil { return nil, err } if query.Repository.Milestone == nil { return nil, fmt.Errorf("no milestone found with number '%d'", number) } return query.Repository.Milestone, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/issue/list/http_test.go
pkg/cmd/issue/list/http_test.go
package list import ( "encoding/json" "io" "net/http" "testing" "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" "github.com/cli/cli/v2/pkg/httpmock" "github.com/stretchr/testify/assert" ) func TestIssueList(t *testing.T) { reg := &httpmock.Registry{} httpClient := &http.Client{} httpmock.ReplaceTripper(httpClient, reg) client := api.NewClientFromHTTP(httpClient) reg.Register( httpmock.GraphQL(`query IssueList\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issues": { "nodes": [], "pageInfo": { "hasNextPage": true, "endCursor": "ENDCURSOR" } } } } } `), ) reg.Register( httpmock.GraphQL(`query IssueList\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issues": { "nodes": [], "pageInfo": { "hasNextPage": false, "endCursor": "ENDCURSOR" } } } } } `), ) repo, _ := ghrepo.FromFullName("OWNER/REPO") filters := prShared.FilterOptions{ Entity: "issue", State: "open", } _, err := listIssues(client, repo, filters, 251) if err != nil { t.Fatalf("unexpected error: %v", err) } if len(reg.Requests) != 2 { t.Fatalf("expected 2 HTTP requests, seen %d", len(reg.Requests)) } var reqBody struct { Query string Variables map[string]interface{} } bodyBytes, _ := io.ReadAll(reg.Requests[0].Body) _ = json.Unmarshal(bodyBytes, &reqBody) if reqLimit := reqBody.Variables["limit"].(float64); reqLimit != 100 { t.Errorf("expected 100, got %v", reqLimit) } if _, cursorPresent := reqBody.Variables["endCursor"]; cursorPresent { t.Error("did not expect first request to pass 'endCursor'") } bodyBytes, _ = io.ReadAll(reg.Requests[1].Body) _ = json.Unmarshal(bodyBytes, &reqBody) if endCursor := reqBody.Variables["endCursor"].(string); endCursor != "ENDCURSOR" { t.Errorf("expected %q, got %q", "ENDCURSOR", endCursor) } } func TestIssueList_pagination(t *testing.T) { reg := &httpmock.Registry{} httpClient := &http.Client{} httpmock.ReplaceTripper(httpClient, reg) client := api.NewClientFromHTTP(httpClient) reg.Register( httpmock.GraphQL(`query IssueList\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issues": { "nodes": [ { "title": "issue1", "labels": { "nodes": [ { "name": "bug" } ], "totalCount": 1 }, "assignees": { "nodes": [ { "login": "user1" } ], "totalCount": 1 } } ], "pageInfo": { "hasNextPage": true, "endCursor": "ENDCURSOR" }, "totalCount": 2 } } } } `), ) reg.Register( httpmock.GraphQL(`query IssueList\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issues": { "nodes": [ { "title": "issue2", "labels": { "nodes": [ { "name": "enhancement" } ], "totalCount": 1 }, "assignees": { "nodes": [ { "login": "user2" } ], "totalCount": 1 } } ], "pageInfo": { "hasNextPage": false, "endCursor": "ENDCURSOR" }, "totalCount": 2 } } } } `), ) repo := ghrepo.New("OWNER", "REPO") res, err := listIssues(client, repo, prShared.FilterOptions{}, 0) if err != nil { t.Fatalf("IssueList() error = %v", err) } assert.Equal(t, 2, res.TotalCount) assert.Equal(t, 2, len(res.Issues)) getLabels := func(i api.Issue) []string { var labels []string for _, l := range i.Labels.Nodes { labels = append(labels, l.Name) } return labels } getAssignees := func(i api.Issue) []string { var logins []string for _, u := range i.Assignees.Nodes { logins = append(logins, u.Login) } return logins } assert.Equal(t, []string{"bug"}, getLabels(res.Issues[0])) assert.Equal(t, []string{"user1"}, getAssignees(res.Issues[0])) assert.Equal(t, []string{"enhancement"}, getLabels(res.Issues[1])) assert.Equal(t, []string{"user2"}, getAssignees(res.Issues[1])) } // TODO advancedIssueSearchCleanup // Remove this test once GHES 3.17 support ends. func TestSearchIssuesAndAdvancedSearch(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 IssueSearch\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:issue", vars["query"]) })) httpClient := &http.Client{Transport: reg} client := api.NewClientFromHTTP(httpClient) searchIssues(client, 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/issue/list/http.go
pkg/cmd/issue/list/http.go
package list import ( "fmt" "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 listIssues(client *api.Client, repo ghrepo.Interface, filters prShared.FilterOptions, limit int) (*api.IssuesAndTotalCount, error) { var states []string switch filters.State { case "open", "": states = []string{"OPEN"} case "closed": states = []string{"CLOSED"} case "all": states = []string{"OPEN", "CLOSED"} default: return nil, fmt.Errorf("invalid state: %s", filters.State) } fragments := fmt.Sprintf("fragment issue on Issue {%s}", api.IssueGraphQL(filters.Fields)) query := fragments + ` query IssueList($owner: String!, $repo: String!, $limit: Int, $endCursor: String, $states: [IssueState!] = OPEN, $assignee: String, $author: String, $mention: String) { repository(owner: $owner, name: $repo) { hasIssuesEnabled issues(first: $limit, after: $endCursor, orderBy: {field: CREATED_AT, direction: DESC}, states: $states, filterBy: {assignee: $assignee, createdBy: $author, mentioned: $mention}) { totalCount nodes { ...issue } pageInfo { hasNextPage endCursor } } } } ` variables := map[string]interface{}{ "owner": repo.RepoOwner(), "repo": repo.RepoName(), "states": states, } if filters.Assignee != "" { variables["assignee"] = filters.Assignee } if filters.Author != "" { variables["author"] = filters.Author } if filters.Mention != "" { variables["mention"] = filters.Mention } if filters.Milestone != "" { // The "milestone" filter in the GraphQL connection doesn't work as documented and accepts neither a // milestone number nor a title. It does accept a numeric database ID, but we cannot obtain one // using the GraphQL API. return nil, fmt.Errorf("cannot filter by milestone using the `Repository.issues` GraphQL connection") } type responseData struct { Repository struct { Issues struct { TotalCount int Nodes []api.Issue PageInfo struct { HasNextPage bool EndCursor string } } HasIssuesEnabled bool } } var issues []api.Issue var totalCount int pageLimit := min(limit, 100) loop: for { var response responseData variables["limit"] = pageLimit err := client.GraphQL(repo.RepoHost(), query, variables, &response) if err != nil { return nil, err } if !response.Repository.HasIssuesEnabled { return nil, fmt.Errorf("the '%s' repository has disabled issues", ghrepo.FullName(repo)) } totalCount = response.Repository.Issues.TotalCount for _, issue := range response.Repository.Issues.Nodes { issues = append(issues, issue) if len(issues) == limit { break loop } } if response.Repository.Issues.PageInfo.HasNextPage { variables["endCursor"] = response.Repository.Issues.PageInfo.EndCursor pageLimit = min(pageLimit, limit-len(issues)) } else { break } } res := api.IssuesAndTotalCount{Issues: issues, TotalCount: totalCount} return &res, nil } func searchIssues(client *api.Client, detector fd.Detector, repo ghrepo.Interface, filters prShared.FilterOptions, limit int) (*api.IssuesAndTotalCount, 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 } fragments := fmt.Sprintf("fragment issue on Issue {%s}", api.IssueGraphQL(filters.Fields)) query := fragments + `query IssueSearch($repo: String!, $owner: String!, $type: SearchType!, $limit: Int, $after: String, $query: String!) { repository(name: $repo, owner: $owner) { hasIssuesEnabled } search(type: $type, last: $limit, after: $after, query: $query) { issueCount nodes { ...issue } pageInfo { hasNextPage endCursor } } }` type response struct { Repository struct { HasIssuesEnabled bool } Search struct { IssueCount int Nodes []api.Issue PageInfo struct { HasNextPage bool EndCursor string } } } perPage := min(limit, 100) variables := map[string]interface{}{ "owner": repo.RepoOwner(), "repo": repo.RepoName(), "limit": perPage, } filters.Repo = ghrepo.FullName(repo) filters.Entity = "issue" if features.AdvancedIssueSearchAPI { variables["query"] = prShared.SearchQueryBuild(filters, true) if features.AdvancedIssueSearchAPIOptIn { variables["type"] = "ISSUE_ADVANCED" } else { variables["type"] = "ISSUE" } } else { variables["query"] = prShared.SearchQueryBuild(filters, false) variables["type"] = "ISSUE" } ic := api.IssuesAndTotalCount{SearchCapped: limit > 1000} loop: for { var resp response err := client.GraphQL(repo.RepoHost(), query, variables, &resp) if err != nil { return nil, err } if !resp.Repository.HasIssuesEnabled { return nil, fmt.Errorf("the '%s' repository has disabled issues", ghrepo.FullName(repo)) } ic.TotalCount = resp.Search.IssueCount for _, issue := range resp.Search.Nodes { ic.Issues = append(ic.Issues, issue) if len(ic.Issues) == limit { break loop } } if !resp.Search.PageInfo.HasNextPage { break } variables["after"] = resp.Search.PageInfo.EndCursor variables["perPage"] = min(perPage, limit-len(ic.Issues)) } return &ic, 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/issue/close/close_test.go
pkg/cmd/issue/close/close_test.go
package close import ( "bytes" "net/http" "testing" fd "github.com/cli/cli/v2/internal/featuredetection" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/issue/argparsetest" "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 TestNewCmdClose(t *testing.T) { // Test shared parsing of issue number / URL. argparsetest.TestArgParsing(t, NewCmdClose) tests := []struct { name string input string output CloseOptions expectedBaseRepo ghrepo.Interface wantErr bool errMsg string }{ { name: "comment", input: "123 --comment 'closing comment'", output: CloseOptions{ IssueNumber: 123, Comment: "closing comment", }, }, { name: "reason", input: "123 --reason 'not planned'", output: CloseOptions{ IssueNumber: 123, Reason: "not planned", }, }, } 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 *CloseOptions cmd := NewCmdClose(f, func(opts *CloseOptions) 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 { require.Error(t, err) assert.Equal(t, tt.errMsg, err.Error()) return } require.NoError(t, err) assert.Equal(t, tt.output.IssueNumber, gotOpts.IssueNumber) assert.Equal(t, tt.output.Comment, gotOpts.Comment) assert.Equal(t, tt.output.Reason, gotOpts.Reason) 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 TestCloseRun(t *testing.T) { tests := []struct { name string opts *CloseOptions httpStubs func(*httpmock.Registry) wantStderr string wantErr bool errMsg string }{ { name: "close issue by number", opts: &CloseOptions{ IssueNumber: 13, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "id": "THE-ID", "number": 13, "title": "The title of the issue"} } } }`), ) reg.Register( httpmock.GraphQL(`mutation IssueClose\b`), httpmock.GraphQLMutation(`{"id": "THE-ID"}`, func(inputs map[string]interface{}) { assert.Equal(t, "THE-ID", inputs["issueId"]) }), ) }, wantStderr: "✓ Closed issue OWNER/REPO#13 (The title of the issue)\n", }, { name: "close issue with comment", opts: &CloseOptions{ IssueNumber: 13, Comment: "closing comment", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "id": "THE-ID", "number": 13, "title": "The title of the issue"} } } }`), ) reg.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"]) }), ) reg.Register( httpmock.GraphQL(`mutation IssueClose\b`), httpmock.GraphQLMutation(`{"id": "THE-ID"}`, func(inputs map[string]interface{}) { assert.Equal(t, "THE-ID", inputs["issueId"]) }), ) }, wantStderr: "✓ Closed issue OWNER/REPO#13 (The title of the issue)\n", }, { name: "close issue with reason", opts: &CloseOptions{ IssueNumber: 13, Reason: "not planned", Detector: &fd.EnabledDetectorMock{}, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "id": "THE-ID", "number": 13, "title": "The title of the issue"} } } }`), ) reg.Register( httpmock.GraphQL(`mutation IssueClose\b`), httpmock.GraphQLMutation(`{"id": "THE-ID"}`, func(inputs map[string]interface{}) { assert.Equal(t, 2, len(inputs)) assert.Equal(t, "THE-ID", inputs["issueId"]) assert.Equal(t, "NOT_PLANNED", inputs["stateReason"]) }), ) }, wantStderr: "✓ Closed issue OWNER/REPO#13 (The title of the issue)\n", }, { name: "close issue with reason when reason is not supported", opts: &CloseOptions{ IssueNumber: 13, Reason: "not planned", Detector: &fd.DisabledDetectorMock{}, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "id": "THE-ID", "number": 13, "title": "The title of the issue"} } } }`), ) reg.Register( httpmock.GraphQL(`mutation IssueClose\b`), httpmock.GraphQLMutation(`{"id": "THE-ID"}`, func(inputs map[string]interface{}) { assert.Equal(t, 1, len(inputs)) assert.Equal(t, "THE-ID", inputs["issueId"]) }), ) }, wantStderr: "✓ Closed issue OWNER/REPO#13 (The title of the issue)\n", }, { name: "issue already closed", opts: &CloseOptions{ IssueNumber: 13, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "number": 13, "title": "The title of the issue", "state": "CLOSED"} } } }`), ) }, wantStderr: "! Issue OWNER/REPO#13 (The title of the issue) is already closed\n", }, { name: "issues disabled", opts: &CloseOptions{ IssueNumber: 13, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(`{ "data": { "repository": { "hasIssuesEnabled": false, "issue": null } }, "errors": [ { "type": "NOT_FOUND", "path": [ "repository", "issue" ], "message": "Could not resolve to an issue or pull request with the number of 13." } ] }`), ) }, wantErr: true, errMsg: "the 'OWNER/REPO' repository has disabled issues", }, } for _, tt := range tests { reg := &httpmock.Registry{} if tt.httpStubs != nil { tt.httpStubs(reg) } tt.opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } ios, _, _, stderr := iostreams.Test() tt.opts.IO = ios tt.opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.FromFullName("OWNER/REPO") } t.Run(tt.name, func(t *testing.T) { defer reg.Verify(t) err := closeRun(tt.opts) if tt.wantErr { assert.EqualError(t, err, tt.errMsg) return } assert.NoError(t, err) 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/issue/close/close.go
pkg/cmd/issue/close/close.go
package close import ( "fmt" "net/http" "time" "github.com/cli/cli/v2/api" fd "github.com/cli/cli/v2/internal/featuredetection" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/issue/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/shurcooL/githubv4" "github.com/spf13/cobra" ) type CloseOptions struct { HttpClient func() (*http.Client, error) IO *iostreams.IOStreams BaseRepo func() (ghrepo.Interface, error) IssueNumber int Comment string Reason string Detector fd.Detector } func NewCmdClose(f *cmdutil.Factory, runF func(*CloseOptions) error) *cobra.Command { opts := &CloseOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, } cmd := &cobra.Command{ Use: "close {<number> | <url>}", Short: "Close issue", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { issueNumber, baseRepo, err := shared.ParseIssueFromArg(args[0]) if err != nil { return err } // If the args provided the base repo then use that directly. if baseRepo, present := baseRepo.Value(); present { opts.BaseRepo = func() (ghrepo.Interface, error) { return baseRepo, nil } } else { // support `-R, --repo` override opts.BaseRepo = f.BaseRepo } opts.IssueNumber = issueNumber if runF != nil { return runF(opts) } return closeRun(opts) }, } cmd.Flags().StringVarP(&opts.Comment, "comment", "c", "", "Leave a closing comment") cmdutil.StringEnumFlag(cmd, &opts.Reason, "reason", "r", "", []string{"completed", "not planned"}, "Reason for closing") return cmd } func closeRun(opts *CloseOptions) error { cs := opts.IO.ColorScheme() httpClient, err := opts.HttpClient() if err != nil { return err } baseRepo, err := opts.BaseRepo() if err != nil { return err } issue, err := shared.FindIssueOrPR(httpClient, baseRepo, opts.IssueNumber, []string{"id", "number", "title", "state"}) if err != nil { return err } if issue.State == "CLOSED" { fmt.Fprintf(opts.IO.ErrOut, "%s Issue %s#%d (%s) is already closed\n", cs.Yellow("!"), ghrepo.FullName(baseRepo), issue.Number, issue.Title) return nil } if opts.Comment != "" { commentOpts := &prShared.CommentableOptions{ Body: opts.Comment, HttpClient: opts.HttpClient, InputType: prShared.InputTypeInline, Quiet: true, RetrieveCommentable: func() (prShared.Commentable, ghrepo.Interface, error) { return issue, baseRepo, nil }, } err := prShared.CommentableRun(commentOpts) if err != nil { return err } } err = apiClose(httpClient, baseRepo, issue, opts.Detector, opts.Reason) if err != nil { return err } fmt.Fprintf(opts.IO.ErrOut, "%s Closed issue %s#%d (%s)\n", cs.SuccessIconWithColor(cs.Red), ghrepo.FullName(baseRepo), issue.Number, issue.Title) return nil } func apiClose(httpClient *http.Client, repo ghrepo.Interface, issue *api.Issue, detector fd.Detector, reason string) error { if issue.IsPullRequest() { return api.PullRequestClose(httpClient, repo, issue.ID) } if reason != "" { if detector == nil { cachedClient := api.NewCachedHTTPClient(httpClient, time.Hour*24) detector = fd.NewDetector(cachedClient, repo.RepoHost()) } features, err := detector.IssueFeatures() if err != nil { return err } if !features.StateReason { // If StateReason is not supported silently close issue without setting StateReason. reason = "" } } switch reason { case "": // If no reason is specified do not set it. case "not planned": reason = "NOT_PLANNED" default: reason = "COMPLETED" } var mutation struct { CloseIssue struct { Issue struct { ID githubv4.ID } } `graphql:"closeIssue(input: $input)"` } variables := map[string]interface{}{ "input": CloseIssueInput{ IssueID: issue.ID, StateReason: reason, }, } gql := api.NewClientFromHTTP(httpClient) return gql.Mutate(repo.RepoHost(), "IssueClose", &mutation, variables) } type CloseIssueInput struct { IssueID string `json:"issueId"` StateReason string `json:"stateReason,omitempty"` }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/issue/comment/comment.go
pkg/cmd/issue/comment/comment.go
package comment import ( "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/issue/shared" issueShared "github.com/cli/cli/v2/pkg/cmd/issue/shared" prShared "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(*prShared.CommentableOptions) error) *cobra.Command { opts := &prShared.CommentableOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, EditSurvey: prShared.CommentableEditSurvey(f.Config, f.IOStreams), InteractiveEditSurvey: prShared.CommentableInteractiveEditSurvey(f.Config, f.IOStreams), ConfirmSubmitSurvey: prShared.CommentableConfirmSubmitSurvey(f.Prompter), ConfirmCreateIfNoneSurvey: prShared.CommentableInteractiveCreateIfNoneSurvey(f.Prompter), ConfirmDeleteLastComment: prShared.CommentableConfirmDeleteLastComment(f.Prompter), OpenInBrowser: f.Browser.Browse, } var bodyFile string cmd := &cobra.Command{ Use: "comment {<number> | <url>}", Short: "Add a comment to an issue", Long: heredoc.Doc(` Add a comment to a GitHub issue. Without the body text supplied through flags, the command will interactively prompt for the comment text. `), Example: heredoc.Doc(` $ gh issue comment 12 --body "Hi from GitHub CLI" `), Args: cobra.ExactArgs(1), PreRunE: func(cmd *cobra.Command, args []string) error { opts.RetrieveCommentable = func() (prShared.Commentable, ghrepo.Interface, error) { // TODO wm: more testing issueNumber, parsedBaseRepo, err := shared.ParseIssueFromArg(args[0]) if err != nil { return nil, nil, err } // If the args provided the base repo then use that directly. var baseRepo ghrepo.Interface if parsedBaseRepo, present := parsedBaseRepo.Value(); present { baseRepo = parsedBaseRepo } else { // support `-R, --repo` override baseRepo, err = f.BaseRepo() if err != nil { return nil, nil, err } } httpClient, err := f.HttpClient() if err != nil { return nil, nil, err } fields := []string{"id", "url"} if opts.EditLast || opts.DeleteLast { fields = append(fields, "comments") } issue, err := issueShared.FindIssueOrPR(httpClient, baseRepo, issueNumber, fields) if err != nil { return nil, nil, err } return issue, baseRepo, nil } return prShared.CommentablePreRun(cmd, opts) }, RunE: func(_ *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 prShared.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/issue/comment/comment_test.go
pkg/cmd/issue/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{}, isTTY: true, wantsErr: true, }, { name: "issue number", input: "1", output: shared.CommentableOptions{ Interactive: true, InputType: 0, Body: "", }, isTTY: true, wantsErr: false, }, { name: "issue url", input: "https://github.com/OWNER/REPO/issues/12", 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 }, }, emptyComments: true, httpStubs: func(t *testing.T, reg *httpmock.Registry) { mockCommentCreate(t, reg) }, stdout: "https://github.com/OWNER/REPO/issues/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/issues/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/issues/123#issuecomment-456\n", }, { name: "creating new comment with non-interactive web opens issue 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/issues/123 in your browser.\n", }, { name: "updating last comment with non-interactive web opens issue 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/issues/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/issues/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) }, emptyComments: false, stdout: "https://github.com/OWNER/REPO/issues/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/issues/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/issues/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/issues/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/issues/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) } tt.input.IO = ios tt.input.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } comments := api.Comments{Nodes: []api.Comment{ {ID: "id1", Author: api.CommentAuthor{Login: "octocat"}, URL: "https://github.com/OWNER/REPO/issues/123#issuecomment-111", ViewerDidAuthor: true}, {ID: "id2", Author: api.CommentAuthor{Login: "monalisa"}, URL: "https://github.com/OWNER/REPO/issues/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.Issue{ ID: "ISSUE-ID", URL: "https://github.com/OWNER/REPO/issues/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/issues/123#issuecomment-456" } } } } }`, func(inputs map[string]interface{}) { assert.Equal(t, "ISSUE-ID", inputs["subjectId"]) 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/issues/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/issue/edit/edit.go
pkg/cmd/issue/edit/edit.go
package edit import ( "fmt" "net/http" "sort" "sync" "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" "github.com/cli/cli/v2/internal/text" shared "github.com/cli/cli/v2/pkg/cmd/issue/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" ) type EditOptions struct { HttpClient func() (*http.Client, error) IO *iostreams.IOStreams BaseRepo func() (ghrepo.Interface, error) Prompter prShared.EditPrompter Detector fd.Detector DetermineEditor func() (string, error) FieldsToEditSurvey func(prShared.EditPrompter, *prShared.Editable) error EditFieldsSurvey func(prShared.EditPrompter, *prShared.Editable, string) error FetchOptions func(*api.Client, ghrepo.Interface, *prShared.Editable, gh.ProjectsV1Support) error IssueNumbers []int Interactive bool prShared.Editable } func NewCmdEdit(f *cmdutil.Factory, runF func(*EditOptions) error) *cobra.Command { opts := &EditOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, DetermineEditor: func() (string, error) { return cmdutil.DetermineEditor(f.Config) }, FieldsToEditSurvey: prShared.FieldsToEditSurvey, EditFieldsSurvey: prShared.EditFieldsSurvey, FetchOptions: prShared.FetchOptions, Prompter: f.Prompter, } var bodyFile string var removeMilestone bool cmd := &cobra.Command{ Use: "edit {<numbers> | <urls>}", Short: "Edit issues", Long: heredoc.Docf(` Edit one or more issues within the same repository. Editing issues' 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) `, "`"), Example: heredoc.Doc(` $ gh issue edit 23 --title "I found a bug" --body "Nothing works" $ gh issue edit 23 --add-label "bug,help wanted" --remove-label "core" $ gh issue edit 23 --add-assignee "@me" --remove-assignee monalisa,hubot $ gh issue edit 23 --add-assignee "@copilot" $ gh issue edit 23 --add-project "Roadmap" --remove-project v1,v2 $ gh issue edit 23 --milestone "Version 1" $ gh issue edit 23 --remove-milestone $ gh issue edit 23 --body-file body.txt $ gh issue edit 23 34 --add-label "help wanted" `), Args: cobra.MinimumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { issueNumbers, baseRepo, err := shared.ParseIssuesFromArgs(args) if err != nil { return err } // If the args provided the base repo then use that directly. if baseRepo, present := baseRepo.Value(); present { opts.BaseRepo = func() (ghrepo.Interface, error) { return baseRepo, nil } } else { // support `-R, --repo` override opts.BaseRepo = f.BaseRepo } opts.IssueNumbers = issueNumbers 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("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("field to edit flag required when not running interactively") } if opts.Interactive && len(opts.IssueNumbers) > 1 { return cmdutil.FlagErrorf("multiple issues cannot be edited 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().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 issue to projects by `title`") cmd.Flags().StringSliceVar(&opts.Editable.Projects.Remove, "remove-project", nil, "Remove the issue from projects by `title`") cmd.Flags().StringVarP(&opts.Editable.Milestone.Value, "milestone", "m", "", "Edit the milestone the issue belongs to by `name`") cmd.Flags().BoolVar(&removeMilestone, "remove-milestone", false, "Remove the milestone association from the issue") return cmd } func editRun(opts *EditOptions) error { httpClient, err := opts.HttpClient() if err != nil { return err } baseRepo, err := opts.BaseRepo() if err != nil { return err } // Prompt the user which fields they'd like to edit. editable := opts.Editable if opts.Interactive { err = opts.FieldsToEditSurvey(opts.Prompter, &editable) if err != nil { return err } } if opts.Detector == nil { cachedClient := api.NewCachedHTTPClient(httpClient, time.Hour*24) opts.Detector = fd.NewDetector(cachedClient, baseRepo.RepoHost()) } issueFeatures, err := opts.Detector.IssueFeatures() if err != nil { return err } lookupFields := []string{"id", "number", "title", "body", "url"} if editable.Assignees.Edited { if issueFeatures.ActorIsAssignable { editable.Assignees.ActorAssignees = true lookupFields = append(lookupFields, "assignedActors") } else { lookupFields = append(lookupFields, "assignees") } } if editable.Labels.Edited { lookupFields = append(lookupFields, "labels") } if editable.Projects.Edited { // TODO projectsV1Deprecation // Remove this section as we should no longer add projectCards projectsV1Support := opts.Detector.ProjectsV1() if projectsV1Support == gh.ProjectsV1Supported { lookupFields = append(lookupFields, "projectCards") } lookupFields = append(lookupFields, "projectItems") } if editable.Milestone.Edited { lookupFields = append(lookupFields, "milestone") } // Get all specified issues and make sure they are within the same repo. issues, err := shared.FindIssuesOrPRs(httpClient, baseRepo, opts.IssueNumbers, lookupFields) if err != nil { return err } // Fetch editable shared fields once for all issues. apiClient := api.NewClientFromHTTP(httpClient) opts.IO.StartProgressIndicatorWithLabel("Fetching repository information") err = opts.FetchOptions(apiClient, baseRepo, &editable, opts.Detector.ProjectsV1()) opts.IO.StopProgressIndicator() if err != nil { return err } // Update all issues in parallel. editedIssueChan := make(chan string, len(issues)) failedIssueChan := make(chan string, len(issues)) g := sync.WaitGroup{} // Only show progress if we will not prompt below or the survey will break up the progress indicator. if !opts.Interactive { opts.IO.StartProgressIndicatorWithLabel(fmt.Sprintf("Updating %d issues", len(issues))) } for _, issue := range issues { // Copy variables to capture in the go routine below. editable := editable.Clone() editable.Title.Default = issue.Title editable.Body.Default = issue.Body // We use Actors as the default assignees if Actors are assignable // on this GitHub host. if editable.Assignees.ActorAssignees { editable.Assignees.Default = issue.AssignedActors.DisplayNames() editable.Assignees.DefaultLogins = issue.AssignedActors.Logins() } else { editable.Assignees.Default = issue.Assignees.Logins() } editable.Labels.Default = issue.Labels.Names() editable.Projects.Default = append(issue.ProjectCards.ProjectNames(), issue.ProjectItems.ProjectTitles()...) projectItems := map[string]string{} for _, n := range issue.ProjectItems.Nodes { projectItems[n.Project.ID] = n.ID } editable.Projects.ProjectItems = projectItems if issue.Milestone != nil { editable.Milestone.Default = issue.Milestone.Title } // Allow interactive prompts for one issue; failed earlier if multiple issues specified. if opts.Interactive { editorCommand, err := opts.DetermineEditor() if err != nil { return err } err = opts.EditFieldsSurvey(opts.Prompter, &editable, editorCommand) if err != nil { return err } } g.Add(1) go func(issue *api.Issue) { defer g.Done() err := prShared.UpdateIssue(httpClient, baseRepo, issue.ID, issue.IsPullRequest(), editable) if err != nil { failedIssueChan <- fmt.Sprintf("failed to update %s: %s", issue.URL, err) return } editedIssueChan <- issue.URL }(issue) } g.Wait() close(editedIssueChan) close(failedIssueChan) // Does nothing if progress was not started above. opts.IO.StopProgressIndicator() // Print a sorted list of successfully edited issue URLs to stdout. editedIssueURLs := make([]string, 0, len(issues)) for editedIssueURL := range editedIssueChan { editedIssueURLs = append(editedIssueURLs, editedIssueURL) } sort.Strings(editedIssueURLs) for _, editedIssueURL := range editedIssueURLs { fmt.Fprintln(opts.IO.Out, editedIssueURL) } // Print a sorted list of failures to stderr. failedIssueErrors := make([]string, 0, len(issues)) for failedIssueError := range failedIssueChan { failedIssueErrors = append(failedIssueErrors, failedIssueError) } sort.Strings(failedIssueErrors) for _, failedIssueError := range failedIssueErrors { fmt.Fprintln(opts.IO.ErrOut, failedIssueError) } if len(failedIssueErrors) > 0 { return fmt.Errorf("failed to update %s", text.Pluralize(len(failedIssueErrors), "issue")) } return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/issue/edit/edit_test.go
pkg/cmd/issue/edit/edit_test.go
package edit import ( "bytes" "fmt" "net/http" "os" "path/filepath" "testing" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/api" 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/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{}, wantsErr: true, }, { name: "issue number argument", input: "23", output: EditOptions{ IssueNumbers: []int{23}, Interactive: true, }, wantsErr: false, }, { name: "title flag", input: "23 --title test", output: EditOptions{ IssueNumbers: []int{23}, Editable: prShared.Editable{ Title: prShared.EditableString{ Value: "test", Edited: true, }, }, }, wantsErr: false, }, { name: "body flag", input: "23 --body test", output: EditOptions{ IssueNumbers: []int{23}, Editable: prShared.Editable{ Body: prShared.EditableString{ Value: "test", Edited: true, }, }, }, wantsErr: false, }, { name: "body from stdin", input: "23 --body-file -", stdin: "this is on standard input", output: EditOptions{ IssueNumbers: []int{23}, Editable: prShared.Editable{ Body: prShared.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{ IssueNumbers: []int{23}, Editable: prShared.Editable{ Body: prShared.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: "add-assignee flag", input: "23 --add-assignee monalisa,hubot", output: EditOptions{ IssueNumbers: []int{23}, Editable: prShared.Editable{ Assignees: prShared.EditableAssignees{ EditableSlice: prShared.EditableSlice{ Add: []string{"monalisa", "hubot"}, Edited: true, }, }, }, }, wantsErr: false, }, { name: "remove-assignee flag", input: "23 --remove-assignee monalisa,hubot", output: EditOptions{ IssueNumbers: []int{23}, Editable: prShared.Editable{ Assignees: prShared.EditableAssignees{ EditableSlice: prShared.EditableSlice{ Remove: []string{"monalisa", "hubot"}, Edited: true, }, }, }, }, wantsErr: false, }, { name: "add-label flag", input: "23 --add-label feature,TODO,bug", output: EditOptions{ IssueNumbers: []int{23}, Editable: prShared.Editable{ Labels: prShared.EditableSlice{ Add: []string{"feature", "TODO", "bug"}, Edited: true, }, }, }, wantsErr: false, }, { name: "remove-label flag", input: "23 --remove-label feature,TODO,bug", output: EditOptions{ IssueNumbers: []int{23}, Editable: prShared.Editable{ Labels: prShared.EditableSlice{ Remove: []string{"feature", "TODO", "bug"}, Edited: true, }, }, }, wantsErr: false, }, { name: "add-project flag", input: "23 --add-project Cleanup,Roadmap", output: EditOptions{ IssueNumbers: []int{23}, Editable: prShared.Editable{ Projects: prShared.EditableProjects{ EditableSlice: prShared.EditableSlice{ Add: []string{"Cleanup", "Roadmap"}, Edited: true, }, }, }, }, wantsErr: false, }, { name: "remove-project flag", input: "23 --remove-project Cleanup,Roadmap", output: EditOptions{ IssueNumbers: []int{23}, Editable: prShared.Editable{ Projects: prShared.EditableProjects{ EditableSlice: prShared.EditableSlice{ Remove: []string{"Cleanup", "Roadmap"}, Edited: true, }, }, }, }, wantsErr: false, }, { name: "milestone flag", input: "23 --milestone GA", output: EditOptions{ IssueNumbers: []int{23}, Editable: prShared.Editable{ Milestone: prShared.EditableString{ Value: "GA", Edited: true, }, }, }, wantsErr: false, }, { name: "remove-milestone flag", input: "23 --remove-milestone", output: EditOptions{ IssueNumbers: []int{23}, Editable: prShared.Editable{ Milestone: prShared.EditableString{ Value: "", Edited: true, }, }, }, wantsErr: false, }, { name: "both milestone and remove-milestone flags", input: "23 --milestone foo --remove-milestone", wantsErr: true, }, { name: "add label to multiple issues", input: "23 34 --add-label bug", output: EditOptions{ IssueNumbers: []int{23, 34}, Editable: prShared.Editable{ Labels: prShared.EditableSlice{ Add: []string{"bug"}, Edited: true, }, }, }, wantsErr: false, }, { name: "argument is hash prefixed number", // Escaping is required here to avoid what I think is shellex treating it as a comment. input: "\\#23", output: EditOptions{ IssueNumbers: []int{23}, Interactive: true, }, wantsErr: false, }, { name: "argument is a URL", input: "https://example.com/cli/cli/issues/23", output: EditOptions{ IssueNumbers: []int{23}, Interactive: true, }, expectedBaseRepo: ghrepo.NewWithHost("cli", "cli", "example.com"), wantsErr: false, }, { name: "URL arguments parse as different repos", input: "https://github.com/cli/cli/issues/23 https://github.com/cli/go-gh/issues/23", wantsErr: true, }, { name: "interactive multiple issues", input: "23 34", 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 { require.Error(t, err) return } require.NoError(t, err) assert.Equal(t, tt.output.IssueNumbers, gotOpts.IssueNumbers) 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 wantErr bool }{ { name: "non-interactive", input: &EditOptions{ Detector: &fd.EnabledDetectorMock{}, IssueNumbers: []int{123}, Interactive: false, Editable: prShared.Editable{ Title: prShared.EditableString{ Value: "new title", Edited: true, }, Body: prShared.EditableString{ Value: "new body", Edited: true, }, Assignees: prShared.EditableAssignees{ EditableSlice: prShared.EditableSlice{ Add: []string{"monalisa", "hubot"}, Remove: []string{"octocat"}, Edited: true, }, }, Labels: prShared.EditableSlice{ Add: []string{"feature", "TODO", "bug"}, Remove: []string{"docs"}, Edited: true, }, Projects: prShared.EditableProjects{ EditableSlice: prShared.EditableSlice{ Add: []string{"Cleanup", "CleanupV2"}, Remove: []string{"Roadmap", "RoadmapV2"}, Edited: true, }, }, Milestone: prShared.EditableString{ Value: "GA", Edited: true, }, Metadata: api.RepoMetadataResult{ Labels: []api.RepoLabel{ {Name: "docs", ID: "DOCSID"}, }, }, }, FetchOptions: prShared.FetchOptions, }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { mockIssueGet(t, reg) mockIssueProjectItemsGet(t, reg) mockRepoMetadata(t, reg) mockIssueUpdate(t, reg) mockIssueUpdateActorAssignees(t, reg) mockIssueUpdateLabels(t, reg) mockProjectV2ItemUpdate(t, reg) }, stdout: "https://github.com/OWNER/REPO/issue/123\n", }, { name: "non-interactive multiple issues", input: &EditOptions{ Detector: &fd.EnabledDetectorMock{}, IssueNumbers: []int{456, 123}, Interactive: false, Editable: prShared.Editable{ Assignees: prShared.EditableAssignees{ EditableSlice: prShared.EditableSlice{ Add: []string{"monalisa", "hubot"}, Remove: []string{"octocat"}, Edited: true, }, }, Labels: prShared.EditableSlice{ Add: []string{"feature", "TODO", "bug"}, Remove: []string{"docs"}, Edited: true, }, Projects: prShared.EditableProjects{ EditableSlice: prShared.EditableSlice{ Add: []string{"Cleanup", "CleanupV2"}, Remove: []string{"Roadmap", "RoadmapV2"}, Edited: true, }, }, Milestone: prShared.EditableString{ Value: "GA", Edited: true, }, }, FetchOptions: prShared.FetchOptions, }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { // Should only be one fetch of metadata. mockRepoMetadata(t, reg) // All other queries and mutations should be doubled. mockIssueNumberGet(t, reg, 123) mockIssueNumberGet(t, reg, 456) mockIssueProjectItemsGet(t, reg) mockIssueProjectItemsGet(t, reg) mockIssueUpdate(t, reg) mockIssueUpdate(t, reg) mockIssueUpdateActorAssignees(t, reg) mockIssueUpdateActorAssignees(t, reg) mockIssueUpdateLabels(t, reg) mockIssueUpdateLabels(t, reg) mockProjectV2ItemUpdate(t, reg) mockProjectV2ItemUpdate(t, reg) }, stdout: heredoc.Doc(` https://github.com/OWNER/REPO/issue/123 https://github.com/OWNER/REPO/issue/456 `), }, { name: "non-interactive multiple issues with fetch failures", input: &EditOptions{ Detector: &fd.EnabledDetectorMock{}, IssueNumbers: []int{123, 9999}, Interactive: false, Editable: prShared.Editable{ Assignees: prShared.EditableAssignees{ EditableSlice: prShared.EditableSlice{ Add: []string{"monalisa", "hubot"}, Remove: []string{"octocat"}, Edited: true, }, }, Labels: prShared.EditableSlice{ Add: []string{"feature", "TODO", "bug"}, Remove: []string{"docs"}, Edited: true, }, Projects: prShared.EditableProjects{ EditableSlice: prShared.EditableSlice{ Add: []string{"Cleanup", "CleanupV2"}, Remove: []string{"Roadmap", "RoadmapV2"}, Edited: true, }, }, Milestone: prShared.EditableString{ Value: "GA", Edited: true, }, }, FetchOptions: prShared.FetchOptions, }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { mockIssueNumberGet(t, reg, 123) reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "errors": [ { "type": "NOT_FOUND", "message": "Could not resolve to an Issue with the number of 9999." } ] }`), ) }, wantErr: true, }, { name: "non-interactive multiple issues with update failures", input: &EditOptions{ Detector: &fd.EnabledDetectorMock{}, IssueNumbers: []int{123, 456}, Interactive: false, Editable: prShared.Editable{ Assignees: prShared.EditableAssignees{ EditableSlice: prShared.EditableSlice{ Add: []string{"monalisa", "hubot"}, Remove: []string{"octocat"}, Edited: true, }, }, Milestone: prShared.EditableString{ Value: "GA", Edited: true, }, }, FetchOptions: prShared.FetchOptions, }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { // Should only be one fetch of metadata. reg.Register( httpmock.GraphQL(`query RepositoryAssignableActors\b`), httpmock.StringResponse(` { "data": { "repository": { "suggestedActors": { "nodes": [ { "login": "hubot", "id": "HUBOTID", "__typename": "Bot" }, { "login": "MonaLisa", "id": "MONAID", "__typename": "User" } ], "pageInfo": { "hasNextPage": false, "endCursor": "Mg" } } } } } `)) 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 } } } } } `)) // All other queries should be doubled. mockIssueNumberGet(t, reg, 123) mockIssueNumberGet(t, reg, 456) // Updating 123 should succeed. reg.Register( httpmock.GraphQLMutationMatcher(`mutation ReplaceActorsForAssignable\b`, func(m map[string]interface{}) bool { return m["assignableId"] == "123" }), httpmock.GraphQLMutation(` { "data": { "replaceActorsForAssignable": { "__typename": "" } } }`, func(inputs map[string]interface{}) {}), ) reg.Register( httpmock.GraphQLMutationMatcher(`mutation IssueUpdate\b`, func(m map[string]interface{}) bool { return m["id"] == "123" }), httpmock.GraphQLMutation(` { "data": { "updateIssue": { "__typename": "" } } }`, func(inputs map[string]interface{}) {}), ) // Updating 456 should fail. reg.Register( httpmock.GraphQLMutationMatcher(`mutation ReplaceActorsForAssignable\b`, func(m map[string]interface{}) bool { return m["assignableId"] == "456" }), httpmock.GraphQLMutation(` { "errors": [ { "message": "test error" } ] }`, func(inputs map[string]interface{}) {}), ) }, stdout: heredoc.Doc(` https://github.com/OWNER/REPO/issue/123 `), stderr: `failed to update https://github.com/OWNER/REPO/issue/456:.*test error`, wantErr: true, }, { name: "interactive", input: &EditOptions{ Detector: &fd.EnabledDetectorMock{}, IssueNumbers: []int{123}, Interactive: true, FieldsToEditSurvey: func(p prShared.EditPrompter, eo *prShared.Editable) error { eo.Title.Edited = true eo.Body.Edited = true eo.Assignees.Edited = true eo.Labels.Edited = true eo.Projects.Edited = true eo.Milestone.Edited = true return nil }, EditFieldsSurvey: func(p prShared.EditPrompter, eo *prShared.Editable, _ string) error { eo.Title.Value = "new title" eo.Body.Value = "new body" eo.Assignees.Value = []string{"monalisa", "hubot"} eo.Labels.Value = []string{"feature", "TODO", "bug"} eo.Labels.Add = []string{"feature", "TODO", "bug"} eo.Labels.Remove = []string{"docs"} eo.Projects.Value = []string{"Cleanup", "CleanupV2"} eo.Milestone.Value = "GA" return nil }, FetchOptions: prShared.FetchOptions, DetermineEditor: func() (string, error) { return "vim", nil }, }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { mockIssueGet(t, reg) mockIssueProjectItemsGet(t, reg) mockRepoMetadata(t, reg) mockIssueUpdate(t, reg) mockIssueUpdateActorAssignees(t, reg) mockIssueUpdateLabels(t, reg) mockProjectV2ItemUpdate(t, reg) }, stdout: "https://github.com/OWNER/REPO/issue/123\n", }, { name: "interactive prompts with actor assignee display names when actors available", input: &EditOptions{ Detector: &fd.EnabledDetectorMock{}, IssueNumbers: []int{123}, Interactive: true, FieldsToEditSurvey: func(p prShared.EditPrompter, eo *prShared.Editable) error { eo.Assignees.Edited = true return nil }, EditFieldsSurvey: func(p prShared.EditPrompter, eo *prShared.Editable, _ string) error { // Checking that the display name is being used in the prompt. require.Equal(t, []string{"hubot"}, eo.Assignees.Default) require.Equal(t, []string{"hubot"}, eo.Assignees.DefaultLogins) // Adding MonaLisa as PR assignee, should preserve hubot. eo.Assignees.Value = []string{"hubot", "MonaLisa (Mona Display Name)"} return nil }, FetchOptions: prShared.FetchOptions, DetermineEditor: func() (string, error) { return "vim", nil }, }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { mockIsssueNumberGetWithAssignedActors(t, reg, 123) 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 } } } } } `)) mockIssueUpdate(t, 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/issue/123\n", }, { name: "interactive prompts with user assignee logins when actors unavailable", input: &EditOptions{ IssueNumbers: []int{123}, Interactive: true, FieldsToEditSurvey: func(p prShared.EditPrompter, eo *prShared.Editable) error { eo.Assignees.Edited = true return nil }, EditFieldsSurvey: func(p prShared.EditPrompter, eo *prShared.Editable, _ string) error { // Checking that only the login is used in the prompt (no display name) require.Equal(t, eo.Assignees.Default, []string{"hubot", "MonaLisa"}) // Mocking a selection of only MonaLisa in the prompt. eo.Assignees.Value = []string{"MonaLisa"} return nil }, FetchOptions: prShared.FetchOptions, DetermineEditor: func() (string, error) { return "vim", nil }, Detector: &fd.DisabledDetectorMock{}, }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(fmt.Sprintf(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "id": "%[1]d", "number": %[1]d, "url": "https://github.com/OWNER/REPO/issue/123", "assignees": { "nodes": [ { "id": "HUBOTID", "login": "hubot", "name": "" }, { "id": "MONAID", "login": "MonaLisa", "name": "Mona Display Name" } ], "totalCount": 2 } } } } }`, 123)), ) reg.Register( httpmock.GraphQL(`query RepositoryAssignableUsers\b`), httpmock.StringResponse(` { "data": { "repository": { "assignableUsers": { "nodes": [ { "login": "hubot", "id": "HUBOTID", "name": "" }, { "login": "MonaLisa", "id": "MONAID", "name": "Mona Display Name" } ], "pageInfo": { "hasNextPage": false } } } } } `)) reg.Register( httpmock.GraphQL(`mutation IssueUpdate\b`), httpmock.GraphQLMutation(` { "data": { "updateIssue": { "__typename": "" } } }`, func(inputs map[string]interface{}) { // Checking that we still assigned the expected ID. require.Contains(t, inputs["assigneeIds"], "MONAID") }), ) }, stdout: "https://github.com/OWNER/REPO/issue/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) if tt.wantErr { assert.Error(t, err) } else { assert.NoError(t, err) } assert.Equal(t, tt.stdout, stdout.String()) // Use regex match since mock errors and service errors will differ. assert.Regexp(t, tt.stderr, stderr.String()) }) } } func mockIssueGet(_ *testing.T, reg *httpmock.Registry) { mockIssueNumberGet(nil, reg, 123) } func mockIssueNumberGet(_ *testing.T, reg *httpmock.Registry, number int) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(fmt.Sprintf(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "id": "%[1]d", "number": %[1]d, "url": "https://github.com/OWNER/REPO/issue/%[1]d", "labels": { "nodes": [ { "id": "DOCSID", "name": "docs" } ], "totalCount": 1 }, "projectCards": { "nodes": [ { "project": { "name": "Roadmap" } } ], "totalCount": 1 } } } } }`, number)), ) } func mockIsssueNumberGetWithAssignedActors(_ *testing.T, reg *httpmock.Registry, number int) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(fmt.Sprintf(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "id": "%[1]d", "number": %[1]d, "url": "https://github.com/OWNER/REPO/issue/%[1]d", "assignedActors": { "nodes": [ { "id": "HUBOTID", "login": "hubot", "__typename": "Bot" } ], "totalCount": 1 } } } } }`, number)), ) } func mockIssueProjectItemsGet(_ *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueProjectItems\b`), httpmock.StringResponse(` { "data": { "repository": { "issue": { "projectItems": { "nodes": [ { "id": "ITEMID", "project": { "title": "RoadmapV2" } } ] } } } } }`), ) } func mockRepoMetadata(_ *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 } } } } } `)) 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 } } } } } `)) reg.Register( httpmock.GraphQL(`query RepositoryMilestoneList\b`), httpmock.StringResponse(` { "data": { "repository": { "milestones": { "nodes": [ { "title": "GA", "id": "GAID" }, { "title": "Big One.oh", "id": "BIGONEID" } ], "pageInfo": { "hasNextPage": false } } } } } `)) reg.Register( httpmock.GraphQL(`query 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": [ { "name": "Triage", "id": "TRIAGEID" } ], "pageInfo": { "hasNextPage": false } } } } } `)) 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 } } } } } `)) } func mockIssueUpdate(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`mutation IssueUpdate\b`), httpmock.GraphQLMutation(` { "data": { "updateIssue": { "__typename": "" } } }`, func(inputs map[string]interface{}) {}), ) } func mockIssueUpdateActorAssignees(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`mutation ReplaceActorsForAssignable\b`), httpmock.GraphQLMutation(` { "data": { "replaceActorsForAssignable": { "__typename": "" } } }`, func(inputs map[string]interface{}) {}), ) } func mockIssueUpdateLabels(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`mutation LabelAdd\b`), httpmock.GraphQLMutation(` { "data": { "addLabelsToLabelable": { "__typename": "" } } }`, func(inputs map[string]interface{}) {}), ) reg.Register( httpmock.GraphQL(`mutation LabelRemove\b`), httpmock.GraphQLMutation(` { "data": { "removeLabelsFromLabelable": { "__typename": "" } } }`, func(inputs map[string]interface{}) {}), ) } func mockProjectV2ItemUpdate(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`mutation UpdateProjectV2Items\b`), httpmock.GraphQLMutation(` { "data": { "add_000": { "item": { "id": "1" } }, "delete_001": { "item": { "id": "2" } } } }`, func(inputs map[string]interface{}) {}), ) } func TestActorIsAssignable(t *testing.T) { t.Run("when actors are assignable, query includes assignedActors", func(t *testing.T) { ios, _, _, _ := iostreams.Test() reg := &httpmock.Registry{} reg.Register( httpmock.GraphQL(`assignedActors`), // Simulate a GraphQL error to early exit the test. httpmock.StatusStringResponse(500, ""), ) _, cmdTeardown := run.Stub() defer cmdTeardown(t) // Ignore the error because we don't care. _ = editRun(&EditOptions{ IO: ios, HttpClient: func() (*http.Client, error) { return &http.Client{Transport: reg}, nil }, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil }, Detector: &fd.EnabledDetectorMock{}, IssueNumbers: []int{123}, Editable: prShared.Editable{ Assignees: prShared.EditableAssignees{ EditableSlice: prShared.EditableSlice{ Add: []string{"monalisa", "octocat"}, Edited: true, }, }, }, }) reg.Verify(t) }) t.Run("when actors are not assignable, query includes assignees instead", func(t *testing.T) { ios, _, _, _ := iostreams.Test() reg := &httpmock.Registry{} // This test should NOT include assignedActors in the query reg.Exclude(t, httpmock.GraphQL(`assignedActors`)) // It should include the regular assignees field reg.Register( httpmock.GraphQL(`assignees`), // Simulate a GraphQL error to early exit the test. httpmock.StatusStringResponse(500, ""), ) _, cmdTeardown := run.Stub() defer cmdTeardown(t) // Ignore the error because we're not really interested in it. _ = editRun(&EditOptions{ IO: ios, HttpClient: func() (*http.Client, error) { return &http.Client{Transport: reg}, nil }, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil }, Detector: &fd.DisabledDetectorMock{}, IssueNumbers: []int{123}, Editable: prShared.Editable{ Assignees: prShared.EditableAssignees{ EditableSlice: prShared.EditableSlice{ Add: []string{"monalisa", "octocat"}, Edited: true, }, }, }, }) reg.Verify(t) }) } // 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, ""), ) _, 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. _ = editRun(&EditOptions{ IO: ios, HttpClient: func() (*http.Client, error) { return &http.Client{Transport: reg}, nil }, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil }, Detector: &fd.EnabledDetectorMock{}, IssueNumbers: []int{123}, Editable: prShared.Editable{ Projects: prShared.EditableProjects{ EditableSlice: prShared.EditableSlice{ Add: []string{"Test Project"}, Edited: true, }, }, }, }) // 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`)) reg.Register( httpmock.GraphQL(`.*`), // Simulate a GraphQL error to early exit the test. httpmock.StatusStringResponse(500, ""), ) _, cmdTeardown := run.Stub() defer cmdTeardown(t) // Ignore the error because we're not really interested in it. _ = editRun(&EditOptions{ IO: ios, HttpClient: func() (*http.Client, error) { return &http.Client{Transport: reg}, nil }, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil }, Detector: &fd.DisabledDetectorMock{}, IssueNumbers: []int{123}, Editable: prShared.Editable{ Projects: prShared.EditableProjects{ EditableSlice: prShared.EditableSlice{ Add: []string{"Test Project"}, Edited: true, }, }, }, }) // 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/issue/pin/pin_test.go
pkg/cmd/issue/pin/pin_test.go
package pin import ( "net/http" "testing" "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/pkg/cmd/issue/argparsetest" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/stretchr/testify/assert" ) func TestNewCmdPin(t *testing.T) { // Test shared parsing of issue number / URL. argparsetest.TestArgParsing(t, NewCmdPin) } func TestPinRun(t *testing.T) { tests := []struct { name string tty bool opts *PinOptions httpStubs func(*httpmock.Registry) wantStdout string wantStderr string }{ { name: "pin issue", tty: true, opts: &PinOptions{IssueNumber: 20}, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "issue": { "id": "ISSUE-ID", "number": 20, "title": "Issue Title", "isPinned": false} } } }`), ) reg.Register( httpmock.GraphQL(`mutation IssuePin\b`), httpmock.GraphQLMutation(`{"id": "ISSUE-ID"}`, func(inputs map[string]interface{}) { assert.Equal(t, inputs["issueId"], "ISSUE-ID") }, ), ) }, wantStdout: "", wantStderr: "✓ Pinned issue OWNER/REPO#20 (Issue Title)\n", }, { name: "issue already pinned", tty: true, opts: &PinOptions{IssueNumber: 20}, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "issue": { "id": "ISSUE-ID", "number": 20, "title": "Issue Title", "isPinned": true} } } }`), ) }, wantStderr: "! Issue OWNER/REPO#20 (Issue Title) is already pinned\n", }, } for _, tt := range tests { 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.SetStdinTTY(tt.tty) ios.SetStdoutTTY(tt.tty) tt.opts.IO = ios tt.opts.Config = func() (gh.Config, error) { return config.NewBlankConfig(), nil } tt.opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil } t.Run(tt.name, func(t *testing.T) { defer reg.Verify(t) err := pinRun(tt.opts) 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/issue/pin/pin.go
pkg/cmd/issue/pin/pin.go
package pin import ( "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/pkg/cmd/issue/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/shurcooL/githubv4" "github.com/spf13/cobra" ) type PinOptions struct { HttpClient func() (*http.Client, error) Config func() (gh.Config, error) IO *iostreams.IOStreams BaseRepo func() (ghrepo.Interface, error) IssueNumber int } func NewCmdPin(f *cmdutil.Factory, runF func(*PinOptions) error) *cobra.Command { opts := &PinOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, Config: f.Config, BaseRepo: f.BaseRepo, } cmd := &cobra.Command{ Use: "pin {<number> | <url>}", Short: "Pin a issue", Long: heredoc.Doc(` Pin an issue to a repository. The issue can be specified by issue number or URL. `), Example: heredoc.Doc(` # Pin an issue to the current repository $ gh issue pin 23 # Pin an issue by URL $ gh issue pin https://github.com/owner/repo/issues/23 # Pin an issue to specific repository $ gh issue pin 23 --repo owner/repo `), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { issueNumber, baseRepo, err := shared.ParseIssueFromArg(args[0]) if err != nil { return err } // If the args provided the base repo then use that directly. if baseRepo, present := baseRepo.Value(); present { opts.BaseRepo = func() (ghrepo.Interface, error) { return baseRepo, nil } } else { // support `-R, --repo` override opts.BaseRepo = f.BaseRepo } opts.IssueNumber = issueNumber if runF != nil { return runF(opts) } return pinRun(opts) }, } return cmd } func pinRun(opts *PinOptions) error { cs := opts.IO.ColorScheme() httpClient, err := opts.HttpClient() if err != nil { return err } baseRepo, err := opts.BaseRepo() if err != nil { return err } issue, err := shared.FindIssueOrPR(httpClient, baseRepo, opts.IssueNumber, []string{"id", "number", "title", "isPinned"}) if err != nil { return err } if issue.IsPinned { fmt.Fprintf(opts.IO.ErrOut, "%s Issue %s#%d (%s) is already pinned\n", cs.Yellow("!"), ghrepo.FullName(baseRepo), issue.Number, issue.Title) return nil } err = pinIssue(httpClient, baseRepo, issue) if err != nil { return err } fmt.Fprintf(opts.IO.ErrOut, "%s Pinned issue %s#%d (%s)\n", cs.SuccessIcon(), ghrepo.FullName(baseRepo), issue.Number, issue.Title) return nil } func pinIssue(httpClient *http.Client, repo ghrepo.Interface, issue *api.Issue) error { var mutation struct { PinIssue struct { Issue struct { ID githubv4.ID } } `graphql:"pinIssue(input: $input)"` } variables := map[string]interface{}{ "input": githubv4.PinIssueInput{ IssueID: issue.ID, }, } gql := api.NewClientFromHTTP(httpClient) return gql.Mutate(repo.RepoHost(), "IssuePin", &mutation, variables) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/issue/view/view.go
pkg/cmd/issue/view/view.go
package view import ( "fmt" "io" "net/http" "sort" "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/gh" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/text" "github.com/cli/cli/v2/pkg/cmd/issue/shared" issueShared "github.com/cli/cli/v2/pkg/cmd/issue/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/cli/cli/v2/pkg/markdown" "github.com/cli/cli/v2/pkg/set" "github.com/spf13/cobra" ) type ViewOptions struct { HttpClient func() (*http.Client, error) IO *iostreams.IOStreams BaseRepo func() (ghrepo.Interface, error) Browser browser.Browser Detector fd.Detector IssueNumber int WebMode bool Comments bool Exporter cmdutil.Exporter Now func() time.Time } func NewCmdView(f *cmdutil.Factory, runF func(*ViewOptions) error) *cobra.Command { opts := &ViewOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, Browser: f.Browser, Now: time.Now, } cmd := &cobra.Command{ Use: "view {<number> | <url>}", Short: "View an issue", Long: heredoc.Docf(` Display the title, body, and other information about an issue. With %[1]s--web%[1]s flag, open the issue in a web browser instead. `, "`"), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { issueNumber, baseRepo, err := shared.ParseIssueFromArg(args[0]) if err != nil { return err } // If the args provided the base repo then use that directly. if baseRepo, present := baseRepo.Value(); present { opts.BaseRepo = func() (ghrepo.Interface, error) { return baseRepo, nil } } else { // support `-R, --repo` override opts.BaseRepo = f.BaseRepo } opts.IssueNumber = issueNumber if runF != nil { return runF(opts) } return viewRun(opts) }, } cmd.Flags().BoolVarP(&opts.WebMode, "web", "w", false, "Open an issue in the browser") cmd.Flags().BoolVarP(&opts.Comments, "comments", "c", false, "View issue comments") cmdutil.AddJSONFlags(cmd, &opts.Exporter, api.IssueFields) return cmd } var defaultFields = []string{ "number", "url", "state", "createdAt", "title", "body", "author", "milestone", "assignees", "labels", "reactionGroups", "lastComment", "stateReason", } func viewRun(opts *ViewOptions) error { httpClient, err := opts.HttpClient() if err != nil { return err } baseRepo, err := opts.BaseRepo() if err != nil { return err } lookupFields := set.NewStringSet() if opts.Exporter != nil { lookupFields.AddValues(opts.Exporter.Fields()) } else if opts.WebMode { lookupFields.Add("url") } else { lookupFields.AddValues(defaultFields) if opts.Comments { lookupFields.Add("comments") lookupFields.Remove("lastComment") } // TODO projectsV1Deprecation // Remove this section as we should no longer add projectCards if opts.Detector == nil { cachedClient := api.NewCachedHTTPClient(httpClient, time.Hour*24) opts.Detector = fd.NewDetector(cachedClient, baseRepo.RepoHost()) } lookupFields.Add("projectItems") projectsV1Support := opts.Detector.ProjectsV1() if projectsV1Support == gh.ProjectsV1Supported { lookupFields.Add("projectCards") } } opts.IO.DetectTerminalTheme() opts.IO.StartProgressIndicator() defer opts.IO.StopProgressIndicator() lookupFields.Add("id") issue, err := issueShared.FindIssueOrPR(httpClient, baseRepo, opts.IssueNumber, lookupFields.ToSlice()) if err != nil { return err } if lookupFields.Contains("comments") { // FIXME: this re-fetches the comments connection even though the initial set of 100 were // fetched in the previous request. err := preloadIssueComments(httpClient, baseRepo, issue) if err != nil { return err } } if lookupFields.Contains("closedByPullRequestsReferences") { err := preloadClosedByPullRequestsReferences(httpClient, baseRepo, issue) if err != nil { return err } } opts.IO.StopProgressIndicator() if opts.WebMode { openURL := issue.URL if opts.IO.IsStdoutTTY() { fmt.Fprintf(opts.IO.ErrOut, "Opening %s in your browser.\n", text.DisplayURL(openURL)) } return opts.Browser.Browse(openURL) } if err := opts.IO.StartPager(); 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, issue) } if opts.IO.IsStdoutTTY() { return printHumanIssuePreview(opts, baseRepo, issue) } if opts.Comments { fmt.Fprint(opts.IO.Out, prShared.RawCommentList(issue.Comments, api.PullRequestReviews{})) return nil } return printRawIssuePreview(opts.IO.Out, issue) } func printRawIssuePreview(out io.Writer, issue *api.Issue) error { assignees := issueAssigneeList(*issue) labels := issueLabelList(issue, nil) projects := issueProjectList(*issue) // Print empty strings for empty values so the number of metadata lines is consistent when // processing many issues with head and grep. fmt.Fprintf(out, "title:\t%s\n", issue.Title) fmt.Fprintf(out, "state:\t%s\n", issue.State) fmt.Fprintf(out, "author:\t%s\n", issue.Author.Login) fmt.Fprintf(out, "labels:\t%s\n", labels) fmt.Fprintf(out, "comments:\t%d\n", issue.Comments.TotalCount) fmt.Fprintf(out, "assignees:\t%s\n", assignees) fmt.Fprintf(out, "projects:\t%s\n", projects) var milestoneTitle string if issue.Milestone != nil { milestoneTitle = issue.Milestone.Title } fmt.Fprintf(out, "milestone:\t%s\n", milestoneTitle) fmt.Fprintf(out, "number:\t%d\n", issue.Number) fmt.Fprintln(out, "--") fmt.Fprintln(out, issue.Body) return nil } func printHumanIssuePreview(opts *ViewOptions, baseRepo ghrepo.Interface, issue *api.Issue) error { out := opts.IO.Out cs := opts.IO.ColorScheme() // Header (Title and State) fmt.Fprintf(out, "%s %s#%d\n", cs.Bold(issue.Title), ghrepo.FullName(baseRepo), issue.Number) fmt.Fprintf(out, "%s • %s opened %s • %s\n", issueStateTitleWithColor(cs, issue), issue.Author.Login, text.FuzzyAgo(opts.Now(), issue.CreatedAt), text.Pluralize(issue.Comments.TotalCount, "comment"), ) // Reactions if reactions := prShared.ReactionGroupList(issue.ReactionGroups); reactions != "" { fmt.Fprint(out, reactions) fmt.Fprintln(out) } // Metadata if assignees := issueAssigneeList(*issue); assignees != "" { fmt.Fprint(out, cs.Bold("Assignees: ")) fmt.Fprintln(out, assignees) } if labels := issueLabelList(issue, cs); labels != "" { fmt.Fprint(out, cs.Bold("Labels: ")) fmt.Fprintln(out, labels) } if projects := issueProjectList(*issue); projects != "" { fmt.Fprint(out, cs.Bold("Projects: ")) fmt.Fprintln(out, projects) } if issue.Milestone != nil { fmt.Fprint(out, cs.Bold("Milestone: ")) fmt.Fprintln(out, issue.Milestone.Title) } // Body var md string var err error if issue.Body == "" { md = fmt.Sprintf("\n %s\n\n", cs.Muted("No description provided")) } else { md, err = markdown.Render(issue.Body, markdown.WithTheme(opts.IO.TerminalTheme()), markdown.WithWrap(opts.IO.TerminalWidth())) if err != nil { return err } } fmt.Fprintf(out, "\n%s\n", md) // Comments if issue.Comments.TotalCount > 0 { preview := !opts.Comments comments, err := prShared.CommentList(opts.IO, issue.Comments, api.PullRequestReviews{}, preview) if err != nil { return err } fmt.Fprint(out, comments) } // Footer fmt.Fprintf(out, cs.Muted("View this issue on GitHub: %s\n"), issue.URL) return nil } func issueStateTitleWithColor(cs *iostreams.ColorScheme, issue *api.Issue) string { colorFunc := cs.ColorFromString(prShared.ColorForIssueState(*issue)) state := "Open" if issue.State == "CLOSED" { state = "Closed" } return colorFunc(state) } func issueAssigneeList(issue api.Issue) string { if len(issue.Assignees.Nodes) == 0 { return "" } AssigneeNames := make([]string, 0, len(issue.Assignees.Nodes)) for _, assignee := range issue.Assignees.Nodes { AssigneeNames = append(AssigneeNames, assignee.Login) } list := strings.Join(AssigneeNames, ", ") if issue.Assignees.TotalCount > len(issue.Assignees.Nodes) { list += ", …" } return list } func issueProjectList(issue api.Issue) string { totalCount := issue.ProjectCards.TotalCount + issue.ProjectItems.TotalCount count := len(issue.ProjectCards.Nodes) + len(issue.ProjectItems.Nodes) if count == 0 { return "" } projectNames := make([]string, 0, count) for _, project := range issue.ProjectItems.Nodes { colName := project.Status.Name if colName == "" { colName = "No Status" } projectNames = append(projectNames, fmt.Sprintf("%s (%s)", project.Project.Title, colName)) } // TODO: Remove v1 classic project logic when completely deprecated for _, project := range issue.ProjectCards.Nodes { 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 issueLabelList(issue *api.Issue, cs *iostreams.ColorScheme) string { if len(issue.Labels.Nodes) == 0 { return "" } // ignore case sort sort.SliceStable(issue.Labels.Nodes, func(i, j int) bool { return strings.ToLower(issue.Labels.Nodes[i].Name) < strings.ToLower(issue.Labels.Nodes[j].Name) }) labelNames := make([]string, len(issue.Labels.Nodes)) for i, label := range issue.Labels.Nodes { if cs == nil { labelNames[i] = label.Name } else { labelNames[i] = cs.Label(label.Color, label.Name) } } return strings.Join(labelNames, ", ") }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/issue/view/http.go
pkg/cmd/issue/view/http.go
package view import ( "net/http" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghrepo" "github.com/shurcooL/githubv4" ) func preloadIssueComments(client *http.Client, repo ghrepo.Interface, issue *api.Issue) error { type response struct { Node struct { Issue struct { Comments *api.Comments `graphql:"comments(first: 100, after: $endCursor)"` } `graphql:"...on Issue"` PullRequest struct { Comments *api.Comments `graphql:"comments(first: 100, after: $endCursor)"` } `graphql:"...on PullRequest"` } `graphql:"node(id: $id)"` } variables := map[string]interface{}{ "id": githubv4.ID(issue.ID), "endCursor": (*githubv4.String)(nil), } if issue.Comments.PageInfo.HasNextPage { variables["endCursor"] = githubv4.String(issue.Comments.PageInfo.EndCursor) } else { issue.Comments.Nodes = issue.Comments.Nodes[0:0] } gql := api.NewClientFromHTTP(client) for { var query response err := gql.Query(repo.RepoHost(), "CommentsForIssue", &query, variables) if err != nil { return err } comments := query.Node.Issue.Comments if comments == nil { comments = query.Node.PullRequest.Comments } issue.Comments.Nodes = append(issue.Comments.Nodes, comments.Nodes...) if !comments.PageInfo.HasNextPage { break } variables["endCursor"] = githubv4.String(comments.PageInfo.EndCursor) } issue.Comments.PageInfo.HasNextPage = false return nil } func preloadClosedByPullRequestsReferences(client *http.Client, repo ghrepo.Interface, issue *api.Issue) error { if !issue.ClosedByPullRequestsReferences.PageInfo.HasNextPage { return nil } type response struct { Node struct { Issue struct { ClosedByPullRequestsReferences api.ClosedByPullRequestsReferences `graphql:"closedByPullRequestsReferences(first: 100, after: $endCursor)"` } `graphql:"...on Issue"` } `graphql:"node(id: $id)"` } variables := map[string]interface{}{ "id": githubv4.ID(issue.ID), "endCursor": githubv4.String(issue.ClosedByPullRequestsReferences.PageInfo.EndCursor), } gql := api.NewClientFromHTTP(client) for { var query response err := gql.Query(repo.RepoHost(), "closedByPullRequestsReferences", &query, variables) if err != nil { return err } issue.ClosedByPullRequestsReferences.Nodes = append(issue.ClosedByPullRequestsReferences.Nodes, query.Node.Issue.ClosedByPullRequestsReferences.Nodes...) if !query.Node.Issue.ClosedByPullRequestsReferences.PageInfo.HasNextPage { break } variables["endCursor"] = githubv4.String(query.Node.Issue.ClosedByPullRequestsReferences.PageInfo.EndCursor) } issue.ClosedByPullRequestsReferences.PageInfo.HasNextPage = false return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/issue/view/view_test.go
pkg/cmd/issue/view/view_test.go
package view import ( "bytes" "io" "net/http" "testing" "time" "github.com/cli/cli/v2/internal/browser" "github.com/cli/cli/v2/internal/config" fd "github.com/cli/cli/v2/internal/featuredetection" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/run" "github.com/cli/cli/v2/pkg/cmd/issue/argparsetest" "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" ) func TestJSONFields(t *testing.T) { jsonfieldstest.ExpectCommandToSupportJSONFields(t, NewCmdView, []string{ "assignees", "author", "body", "closed", "comments", "closedByPullRequestsReferences", "createdAt", "closedAt", "id", "labels", "milestone", "number", "projectCards", "projectItems", "reactionGroups", "state", "title", "updatedAt", "url", "isPinned", "stateReason", }) } func TestNewCmdView(t *testing.T) { // Test shared parsing of issue number / URL. argparsetest.TestArgParsing(t, NewCmdView) } 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 }, Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), 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, }, err } func TestIssueView_web(t *testing.T) { ios, _, stdout, stderr := iostreams.Test() ios.SetStdoutTTY(true) ios.SetStderrTTY(true) browser := &browser.Stub{} reg := &httpmock.Registry{} defer reg.Verify(t) reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "number": 123, "url": "https://github.com/OWNER/REPO/issues/123" } } } } `)) _, cmdTeardown := run.Stub() defer cmdTeardown(t) err := viewRun(&ViewOptions{ IO: ios, Browser: browser, HttpClient: func() (*http.Client, error) { return &http.Client{Transport: reg}, nil }, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil }, WebMode: true, IssueNumber: 123, }) if err != nil { t.Errorf("error running command `issue view`: %v", err) } assert.Equal(t, "", stdout.String()) assert.Equal(t, "Opening https://github.com/OWNER/REPO/issues/123 in your browser.\n", stderr.String()) browser.Verify(t, "https://github.com/OWNER/REPO/issues/123") } func TestIssueView_nontty_Preview(t *testing.T) { tests := map[string]struct { httpStubs func(*httpmock.Registry) expectedOutputs []string }{ "Open issue without metadata": { httpStubs: func(r *httpmock.Registry) { r.Register(httpmock.GraphQL(`query IssueByNumber\b`), httpmock.FileResponse("./fixtures/issueView_preview.json")) mockEmptyV2ProjectItems(t, r) }, expectedOutputs: []string{ `title:\tix of coins`, `state:\tOPEN`, `comments:\t9`, `author:\tmarseilles`, `assignees:`, `number:\t123\n`, `\*\*bold story\*\*`, }, }, "Open issue with metadata": { httpStubs: func(r *httpmock.Registry) { r.Register(httpmock.GraphQL(`query IssueByNumber\b`), httpmock.FileResponse("./fixtures/issueView_previewWithMetadata.json")) mockV2ProjectItems(t, r) }, expectedOutputs: []string{ `title:\tix of coins`, `assignees:\tmarseilles, monaco`, `author:\tmarseilles`, `state:\tOPEN`, `comments:\t9`, `labels:\tClosed: Duplicate, Closed: Won't Fix, help wanted, Status: In Progress, Type: Bug`, `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`, `number:\t123\n`, `\*\*bold story\*\*`, }, }, "Open issue with empty body": { httpStubs: func(r *httpmock.Registry) { r.Register(httpmock.GraphQL(`query IssueByNumber\b`), httpmock.FileResponse("./fixtures/issueView_previewWithEmptyBody.json")) mockEmptyV2ProjectItems(t, r) }, expectedOutputs: []string{ `title:\tix of coins`, `state:\tOPEN`, `author:\tmarseilles`, `labels:\ttarot`, `number:\t123\n`, }, }, "Closed issue": { httpStubs: func(r *httpmock.Registry) { r.Register(httpmock.GraphQL(`query IssueByNumber\b`), httpmock.FileResponse("./fixtures/issueView_previewClosedState.json")) mockEmptyV2ProjectItems(t, r) }, expectedOutputs: []string{ `title:\tix of coins`, `state:\tCLOSED`, `\*\*bold story\*\*`, `author:\tmarseilles`, `labels:\ttarot`, `number:\t123\n`, `\*\*bold story\*\*`, }, }, } for name, tc := range tests { t.Run(name, func(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) if tc.httpStubs != nil { tc.httpStubs(http) } output, err := runCommand(http, false, "123") if err != nil { t.Errorf("error running `issue view`: %v", err) } assert.Equal(t, "", output.Stderr()) //nolint:staticcheck // prefer exact matchers over ExpectLines test.ExpectLines(t, output.String(), tc.expectedOutputs...) }) } } func TestIssueView_tty_Preview(t *testing.T) { tests := map[string]struct { httpStubs func(*httpmock.Registry) expectedOutputs []string }{ "Open issue without metadata": { httpStubs: func(r *httpmock.Registry) { r.Register(httpmock.GraphQL(`query IssueByNumber\b`), httpmock.FileResponse("./fixtures/issueView_preview.json")) mockEmptyV2ProjectItems(t, r) }, expectedOutputs: []string{ `ix of coins OWNER/REPO#123`, `Open.*marseilles opened about 9 years ago.*9 comments`, `bold story`, `View this issue on GitHub: https://github.com/OWNER/REPO/issues/123`, }, }, "Open issue with metadata": { httpStubs: func(r *httpmock.Registry) { r.Register(httpmock.GraphQL(`query IssueByNumber\b`), httpmock.FileResponse("./fixtures/issueView_previewWithMetadata.json")) mockV2ProjectItems(t, r) }, expectedOutputs: []string{ `ix of coins OWNER/REPO#123`, `Open.*marseilles opened about 9 years ago.*9 comments`, `8 \x{1f615} • 7 \x{1f440} • 6 \x{2764}\x{fe0f} • 5 \x{1f389} • 4 \x{1f604} • 3 \x{1f680} • 2 \x{1f44e} • 1 \x{1f44d}`, `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`, `bold story`, `View this issue on GitHub: https://github.com/OWNER/REPO/issues/123`, }, }, "Open issue with empty body": { httpStubs: func(r *httpmock.Registry) { r.Register(httpmock.GraphQL(`query IssueByNumber\b`), httpmock.FileResponse("./fixtures/issueView_previewWithEmptyBody.json")) mockEmptyV2ProjectItems(t, r) }, expectedOutputs: []string{ `ix of coins OWNER/REPO#123`, `Open.*marseilles opened about 9 years ago.*9 comments`, `No description provided`, `View this issue on GitHub: https://github.com/OWNER/REPO/issues/123`, }, }, "Closed issue": { httpStubs: func(r *httpmock.Registry) { r.Register(httpmock.GraphQL(`query IssueByNumber\b`), httpmock.FileResponse("./fixtures/issueView_previewClosedState.json")) mockEmptyV2ProjectItems(t, r) }, expectedOutputs: []string{ `ix of coins OWNER/REPO#123`, `Closed.*marseilles opened about 9 years ago.*9 comments`, `bold story`, `View this issue on GitHub: https://github.com/OWNER/REPO/issues/123`, }, }, } for name, tc := range tests { t.Run(name, func(t *testing.T) { ios, _, stdout, stderr := iostreams.Test() ios.SetStdoutTTY(true) ios.SetStdinTTY(true) ios.SetStderrTTY(true) httpReg := &httpmock.Registry{} defer httpReg.Verify(t) if tc.httpStubs != nil { tc.httpStubs(httpReg) } opts := ViewOptions{ IO: ios, Now: func() time.Time { t, _ := time.Parse(time.RFC822, "03 Nov 20 15:04 UTC") return t }, HttpClient: func() (*http.Client, error) { return &http.Client{Transport: httpReg}, nil }, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil }, IssueNumber: 123, } err := viewRun(&opts) assert.NoError(t, err) assert.Equal(t, "", stderr.String()) //nolint:staticcheck // prefer exact matchers over ExpectLines test.ExpectLines(t, stdout.String(), tc.expectedOutputs...) }) } } func TestIssueView_web_notFound(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) http.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "errors": [ { "message": "Could not resolve to an Issue with the number of 9999." } ] } `), ) _, cmdTeardown := run.Stub() defer cmdTeardown(t) _, err := runCommand(http, true, "-w 9999") if err == nil || err.Error() != "GraphQL: Could not resolve to an Issue with the number of 9999." { t.Errorf("error running command `issue view`: %v", err) } } func TestIssueView_disabledIssues(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) http.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "id": "REPOID", "hasIssuesEnabled": false } }, "errors": [ { "type": "NOT_FOUND", "path": [ "repository", "issue" ], "message": "Could not resolve to an issue or pull request with the number of 6666." } ] } `), ) _, err := runCommand(http, true, `6666`) if err == nil || err.Error() != "the 'OWNER/REPO' repository has disabled issues" { t.Errorf("error running command `issue view`: %v", err) } } func TestIssueView_tty_Comments(t *testing.T) { tests := map[string]struct { cli string httpStubs func(*httpmock.Registry) expectedOutputs []string wantsErr bool }{ "without comments flag": { cli: "123", httpStubs: func(r *httpmock.Registry) { r.Register(httpmock.GraphQL(`query IssueByNumber\b`), httpmock.FileResponse("./fixtures/issueView_previewSingleComment.json")) mockEmptyV2ProjectItems(t, r) }, expectedOutputs: []string{ `some title OWNER/REPO#123`, `some body`, `———————— Not showing 5 comments ————————`, `marseilles \(Collaborator\) • Jan 1, 2020 • Newest comment`, `Comment 5`, `Use --comments to view the full conversation`, `View this issue on GitHub: https://github.com/OWNER/REPO/issues/123`, }, }, "with comments flag": { cli: "123 --comments", httpStubs: func(r *httpmock.Registry) { r.Register(httpmock.GraphQL(`query IssueByNumber\b`), httpmock.FileResponse("./fixtures/issueView_previewSingleComment.json")) r.Register(httpmock.GraphQL(`query CommentsForIssue\b`), httpmock.FileResponse("./fixtures/issueView_previewFullComments.json")) mockEmptyV2ProjectItems(t, r) }, expectedOutputs: []string{ `some title OWNER/REPO#123`, `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`, `johnnytest \(Contributor\) • Jan 1, 2020`, `Comment 2`, `elvisp \(Member\) • Jan 1, 2020`, `Comment 3`, `loislane \(Owner\) • Jan 1, 2020`, `Comment 4`, `sam-spam • This comment has been marked as spam`, `marseilles \(Collaborator\) • Jan 1, 2020 • Newest comment`, `Comment 5`, `View this issue on GitHub: https://github.com/OWNER/REPO/issues/123`, }, }, "with invalid comments flag": { cli: "123 --comments 3", wantsErr: true, }, } for name, tc := range tests { t.Run(name, func(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) if tc.httpStubs != nil { tc.httpStubs(http) } output, err := runCommand(http, true, tc.cli) if tc.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(), tc.expectedOutputs...) }) } } func TestIssueView_nontty_Comments(t *testing.T) { tests := map[string]struct { cli string httpStubs func(*httpmock.Registry) expectedOutputs []string wantsErr bool }{ "without comments flag": { cli: "123", httpStubs: func(r *httpmock.Registry) { r.Register(httpmock.GraphQL(`query IssueByNumber\b`), httpmock.FileResponse("./fixtures/issueView_previewSingleComment.json")) mockEmptyV2ProjectItems(t, r) }, expectedOutputs: []string{ `title:\tsome title`, `state:\tOPEN`, `author:\tmarseilles`, `comments:\t6`, `number:\t123`, `some body`, }, }, "with comments flag": { cli: "123 --comments", httpStubs: func(r *httpmock.Registry) { r.Register(httpmock.GraphQL(`query IssueByNumber\b`), httpmock.FileResponse("./fixtures/issueView_previewSingleComment.json")) r.Register(httpmock.GraphQL(`query CommentsForIssue\b`), httpmock.FileResponse("./fixtures/issueView_previewFullComments.json")) mockEmptyV2ProjectItems(t, r) }, expectedOutputs: []string{ `author:\tmonalisa`, `association:\t`, `edited:\ttrue`, `Comment 1`, `author:\tjohnnytest`, `association:\tcontributor`, `edited:\tfalse`, `Comment 2`, `author:\telvisp`, `association:\tmember`, `edited:\tfalse`, `Comment 3`, `author:\tloislane`, `association:\towner`, `edited:\tfalse`, `Comment 4`, `author:\tmarseilles`, `association:\tcollaborator`, `edited:\tfalse`, `Comment 5`, }, }, "with invalid comments flag": { cli: "123 --comments 3", wantsErr: true, }, } for name, tc := range tests { t.Run(name, func(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) if tc.httpStubs != nil { tc.httpStubs(http) } output, err := runCommand(http, false, tc.cli) if tc.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(), tc.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, ""), ) _, 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, HttpClient: func() (*http.Client, error) { return &http.Client{Transport: reg}, nil }, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil }, Detector: &fd.EnabledDetectorMock{}, IssueNumber: 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`)) _, cmdTeardown := run.Stub() defer cmdTeardown(t) // Ignore the error because we're not really interested in it. _ = viewRun(&ViewOptions{ IO: ios, HttpClient: func() (*http.Client, error) { return &http.Client{Transport: reg}, nil }, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil }, Detector: &fd.DisabledDetectorMock{}, IssueNumber: 123, }) // Verify that our request contained projectCards reg.Verify(t) }) } // mockEmptyV2ProjectItems registers GraphQL queries to report an issue is not contained on any v2 projects. func mockEmptyV2ProjectItems(t *testing.T, r *httpmock.Registry) { r.Register(httpmock.GraphQL(`query IssueProjectItems\b`), httpmock.StringResponse(` { "data": { "repository": { "issue": { "projectItems": { "totalCount": 0, "nodes": [] } } } } } `)) } // mockV2ProjectItems registers GraphQL queries to report an issue on multiple v2 projects in various states // - `NO_STATUS_ITEM`: emulates this issue is on a project but is not given a status // - `DONE_STATUS_ITEM`: emulates this issue is on a project and considered done func mockV2ProjectItems(t *testing.T, r *httpmock.Registry) { r.Register(httpmock.GraphQL(`query IssueProjectItems\b`), httpmock.StringResponse(` { "data": { "repository": { "issue": { "projectItems": { "totalCount": 2, "nodes": [ { "id": "NO_STATUS_ITEM", "project": { "id": "PROJECT1", "title": "v2 Project 1" }, "status": { "optionId": "", "name": "" } }, { "id": "DONE_STATUS_ITEM", "project": { "id": "PROJECT2", "title": "v2 Project 2" }, "status": { "optionId": "PROJECTITEMFIELD1", "name": "Done" } } ] } } } } } `)) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/issue/status/status.go
pkg/cmd/issue/status/status.go
package status import ( "fmt" "net/http" "time" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghrepo" issueShared "github.com/cli/cli/v2/pkg/cmd/issue/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" ) type StatusOptions struct { HttpClient func() (*http.Client, error) Config func() (gh.Config, error) IO *iostreams.IOStreams BaseRepo func() (ghrepo.Interface, error) Exporter cmdutil.Exporter } func NewCmdStatus(f *cmdutil.Factory, runF func(*StatusOptions) error) *cobra.Command { opts := &StatusOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, Config: f.Config, } cmd := &cobra.Command{ Use: "status", Short: "Show status of relevant issues", Args: cmdutil.NoArgsQuoteReminder, RunE: func(cmd *cobra.Command, args []string) error { // support `-R, --repo` override opts.BaseRepo = f.BaseRepo if runF != nil { return runF(opts) } return statusRun(opts) }, } cmdutil.AddJSONFlags(cmd, &opts.Exporter, api.IssueFields) return cmd } var defaultFields = []string{ "number", "title", "url", "state", "updatedAt", "labels", } func statusRun(opts *StatusOptions) error { httpClient, err := opts.HttpClient() if err != nil { return err } apiClient := api.NewClientFromHTTP(httpClient) baseRepo, err := opts.BaseRepo() if err != nil { return err } currentUser, err := api.CurrentLoginName(apiClient, baseRepo.RepoHost()) if err != nil { return err } options := api.IssueStatusOptions{ Username: currentUser, Fields: defaultFields, } if opts.Exporter != nil { options.Fields = opts.Exporter.Fields() } issuePayload, err := api.IssueStatus(apiClient, baseRepo, 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{}{ "createdBy": issuePayload.Authored.Issues, "assigned": issuePayload.Assigned.Issues, "mentioned": issuePayload.Mentioned.Issues, } return opts.Exporter.Write(opts.IO, data) } out := opts.IO.Out fmt.Fprintln(out, "") fmt.Fprintf(out, "Relevant issues in %s\n", ghrepo.FullName(baseRepo)) fmt.Fprintln(out, "") prShared.PrintHeader(opts.IO, "Issues assigned to you") if issuePayload.Assigned.TotalCount > 0 { issueShared.PrintIssues(opts.IO, time.Now(), " ", issuePayload.Assigned.TotalCount, issuePayload.Assigned.Issues) } else { message := " There are no issues assigned to you" prShared.PrintMessage(opts.IO, message) } fmt.Fprintln(out) prShared.PrintHeader(opts.IO, "Issues mentioning you") if issuePayload.Mentioned.TotalCount > 0 { issueShared.PrintIssues(opts.IO, time.Now(), " ", issuePayload.Mentioned.TotalCount, issuePayload.Mentioned.Issues) } else { prShared.PrintMessage(opts.IO, " There are no issues mentioning you") } fmt.Fprintln(out) prShared.PrintHeader(opts.IO, "Issues opened by you") if issuePayload.Authored.TotalCount > 0 { issueShared.PrintIssues(opts.IO, time.Now(), " ", issuePayload.Authored.TotalCount, issuePayload.Authored.Issues) } else { prShared.PrintMessage(opts.IO, " There are no issues opened by you") } fmt.Fprintln(out) return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/issue/status/status_test.go
pkg/cmd/issue/status/status_test.go
package status import ( "bytes" "io" "net/http" "regexp" "testing" "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/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" ) 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 }, Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil }, } cmd := NewCmdStatus(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 TestIssueStatus(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) http.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data":{"viewer":{"login":"octocat"}}}`)) http.Register( httpmock.GraphQL(`query IssueStatus\b`), httpmock.FileResponse("./fixtures/issueStatus.json")) output, err := runCommand(http, true, "") if err != nil { t.Errorf("error running command `issue status`: %v", err) } expectedIssues := []*regexp.Regexp{ regexp.MustCompile(`(?m)8.*carrots.*about.*ago`), regexp.MustCompile(`(?m)9.*squash.*about.*ago`), regexp.MustCompile(`(?m)10.*broccoli.*about.*ago`), regexp.MustCompile(`(?m)11.*swiss chard.*about.*ago`), } for _, r := range expectedIssues { if !r.MatchString(output.String()) { t.Errorf("output did not match regexp /%s/\n> output\n%s\n", r, output) return } } } func TestIssueStatus_blankSlate(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) http.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data":{"viewer":{"login":"octocat"}}}`)) http.Register( httpmock.GraphQL(`query IssueStatus\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "assigned": { "nodes": [] }, "mentioned": { "nodes": [] }, "authored": { "nodes": [] } } } }`)) output, err := runCommand(http, true, "") if err != nil { t.Errorf("error running command `issue status`: %v", err) } expectedOutput := ` Relevant issues in OWNER/REPO Issues assigned to you There are no issues assigned to you Issues mentioning you There are no issues mentioning you Issues opened by you There are no issues opened by you ` if output.String() != expectedOutput { t.Errorf("expected %q, got %q", expectedOutput, output) } } func TestIssueStatus_disabledIssues(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) http.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data":{"viewer":{"login":"octocat"}}}`)) http.Register( httpmock.GraphQL(`query IssueStatus\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": false } } }`)) _, err := runCommand(http, true, "") if err == nil || err.Error() != "the 'OWNER/REPO' repository has disabled issues" { t.Errorf("error running command `issue status`: %v", err) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/issue/argparsetest/argparsetest.go
pkg/cmd/issue/argparsetest/argparsetest.go
package argparsetest import ( "bytes" "reflect" "testing" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/google/shlex" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // newCmdFunc represents the typical function signature we use for creating commands e.g. `NewCmdView`. // // It is generic over `T` as each command construction has their own Options type e.g. `ViewOptions` type newCmdFunc[T any] func(f *cmdutil.Factory, runF func(*T) error) *cobra.Command // TestArgParsing is a test helper that verifies that issue commands correctly parse the `{issue number | url}` // positional arg into an issue number and base repo. // // Looking through the existing tests, I noticed that the coverage was pretty smattered. // Since nearly all issue commands only accept a single positional argument, we are able to reuse this test helper. // Commands with no further flags or args can use this solely. // Commands with extra flags use this and further table tests. // Commands with extra required positional arguments (like `transfer`) cannot use this. They duplicate these cases inline. func TestArgParsing[T any](t *testing.T, fn newCmdFunc[T]) { tests := []struct { name string input string expectedissueNumber int expectedBaseRepo ghrepo.Interface expectErr bool }{ { name: "no argument", input: "", expectErr: true, }, { name: "issue number argument", input: "23 --repo owner/repo", expectedissueNumber: 23, expectedBaseRepo: ghrepo.New("owner", "repo"), }, { name: "argument is hash prefixed number", // Escaping is required here to avoid what I think is shellex treating it as a comment. input: "\\#23 --repo owner/repo", expectedissueNumber: 23, expectedBaseRepo: ghrepo.New("owner", "repo"), }, { name: "argument is a URL", input: "https://github.com/cli/cli/issues/23", expectedissueNumber: 23, expectedBaseRepo: ghrepo.New("cli", "cli"), }, { name: "argument cannot be parsed to an issue", input: "unparseable", expectErr: true, }, } 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 T cmd := fn(f, func(opts *T) error { gotOpts = *opts return nil }) cmdutil.EnableRepoOverride(cmd, f) // TODO: remember why we do this 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.expectErr { require.Error(t, err) return } else { require.NoError(t, err) } actualIssueNumber := issueNumberFromOpts(t, gotOpts) assert.Equal(t, tt.expectedissueNumber, actualIssueNumber) actualBaseRepo := baseRepoFromOpts(t, gotOpts) assert.True( t, ghrepo.IsSame(tt.expectedBaseRepo, actualBaseRepo), "expected base repo %+v, got %+v", tt.expectedBaseRepo, actualBaseRepo, ) }) } } func issueNumberFromOpts(t *testing.T, v any) int { rv := reflect.ValueOf(v) field := rv.FieldByName("IssueNumber") if !field.IsValid() || field.Kind() != reflect.Int { t.Fatalf("Type %T does not have IssueNumber int field", v) } return int(field.Int()) } func baseRepoFromOpts(t *testing.T, v any) ghrepo.Interface { rv := reflect.ValueOf(v) field := rv.FieldByName("BaseRepo") // check whether the field is valid and of type func() (ghrepo.Interface, error) if !field.IsValid() || field.Kind() != reflect.Func { t.Fatalf("Type %T does not have BaseRepo func field", v) } // call the function and check the return value results := field.Call([]reflect.Value{}) if len(results) != 2 { t.Fatalf("%T.BaseRepo() does not return two values", v) } if !results[1].IsNil() { t.Fatalf("%T.BaseRepo() returned an error: %v", v, results[1].Interface()) } return results[0].Interface().(ghrepo.Interface) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/issue/create/create.go
pkg/cmd/issue/create/create.go
package create import ( "errors" "fmt" "net/http" "time" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/browser" fd "github.com/cli/cli/v2/internal/featuredetection" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/text" 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/cli/cli/v2/pkg/set" "github.com/spf13/cobra" ) type CreateOptions struct { HttpClient func() (*http.Client, error) Config func() (gh.Config, error) IO *iostreams.IOStreams BaseRepo func() (ghrepo.Interface, error) Browser browser.Browser Prompter prShared.Prompt Detector fd.Detector TitledEditSurvey func(string, string) (string, string, error) RootDirOverride string HasRepoOverride bool EditorMode bool WebMode bool RecoverFile string Title string Body string Interactive bool Assignees []string Labels []string Projects []string Milestone string Template string } func NewCmdCreate(f *cmdutil.Factory, runF func(*CreateOptions) error) *cobra.Command { opts := &CreateOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, Config: f.Config, Browser: f.Browser, Prompter: f.Prompter, TitledEditSurvey: prShared.TitledEditSurvey(&prShared.UserEditor{Config: f.Config, IO: f.IOStreams}), } var bodyFile string cmd := &cobra.Command{ Use: "create", Short: "Create a new issue", Long: heredoc.Docf(` Create an issue on GitHub. Adding an issue to projects requires authorization with the %[1]sproject%[1]s scope. To authorize, run %[1]sgh auth refresh -s project%[1]s. The %[1]s--assignee%[1]s flag supports the following special values: - %[1]s@me%[1]s: assign yourself - %[1]s@copilot%[1]s: assign Copilot (not supported on GitHub Enterprise Server) `, "`"), Example: heredoc.Doc(` $ gh issue create --title "I found a bug" --body "Nothing works" $ gh issue create --label "bug,help wanted" $ gh issue create --label bug --label "help wanted" $ gh issue create --assignee monalisa,hubot $ gh issue create --assignee "@me" $ gh issue create --assignee "@copilot" $ gh issue create --project "Roadmap" $ gh issue create --template "Bug Report" `), Args: cmdutil.NoArgsQuoteReminder, Aliases: []string{"new"}, RunE: func(cmd *cobra.Command, args []string) error { // support `-R, --repo` override opts.BaseRepo = f.BaseRepo opts.HasRepoOverride = cmd.Flags().Changed("repo") var err error opts.EditorMode, err = prShared.InitEditorMode(f, opts.EditorMode, opts.WebMode, opts.IO.CanPrompt()) if err != nil { return err } titleProvided := cmd.Flags().Changed("title") bodyProvided := cmd.Flags().Changed("body") if bodyFile != "" { b, err := cmdutil.ReadFile(bodyFile, opts.IO.In) if err != nil { return err } opts.Body = string(b) bodyProvided = true } if !opts.IO.CanPrompt() && opts.RecoverFile != "" { return cmdutil.FlagErrorf("`--recover` only supported when running interactively") } if opts.Template != "" && bodyProvided { return errors.New("`--template` is not supported when using `--body` or `--body-file`") } opts.Interactive = !opts.EditorMode && !(titleProvided && bodyProvided) if opts.Interactive && !opts.IO.CanPrompt() { return cmdutil.FlagErrorf("must provide `--title` and `--body` when not running interactively") } if runF != nil { return runF(opts) } return createRun(opts) }, } cmd.Flags().StringVarP(&opts.Title, "title", "t", "", "Supply a title. Will prompt for one otherwise.") cmd.Flags().StringVarP(&opts.Body, "body", "b", "", "Supply a body. Will prompt for one otherwise.") cmd.Flags().StringVarP(&bodyFile, "body-file", "F", "", "Read body text from `file` (use \"-\" to read from standard input)") cmd.Flags().BoolVarP(&opts.EditorMode, "editor", "e", false, "Skip prompts and open the text editor to write the title and body in. The first line is the title and the remaining text is the body.") cmd.Flags().BoolVarP(&opts.WebMode, "web", "w", false, "Open the browser to create an issue") cmd.Flags().StringSliceVarP(&opts.Assignees, "assignee", "a", nil, "Assign people by their `login`. Use \"@me\" to self-assign.") cmd.Flags().StringSliceVarP(&opts.Labels, "label", "l", nil, "Add labels by `name`") cmd.Flags().StringSliceVarP(&opts.Projects, "project", "p", nil, "Add the issue to projects by `title`") cmd.Flags().StringVarP(&opts.Milestone, "milestone", "m", "", "Add the issue to a milestone by `name`") cmd.Flags().StringVar(&opts.RecoverFile, "recover", "", "Recover input from a failed run of create") cmd.Flags().StringVarP(&opts.Template, "template", "T", "", "Template `name` to use as starting body text") return cmd } func createRun(opts *CreateOptions) (err error) { httpClient, err := opts.HttpClient() if err != nil { return } apiClient := api.NewClientFromHTTP(httpClient) baseRepo, err := opts.BaseRepo() if err != nil { return } // TODO projectsV1Deprecation // Remove this section as we should no longer need to detect if opts.Detector == nil { cachedClient := api.NewCachedHTTPClient(httpClient, time.Hour*24) opts.Detector = fd.NewDetector(cachedClient, baseRepo.RepoHost()) } projectsV1Support := opts.Detector.ProjectsV1() issueFeatures, err := opts.Detector.IssueFeatures() if err != nil { return err } isTerminal := opts.IO.IsStdoutTTY() var milestones []string if opts.Milestone != "" { milestones = []string{opts.Milestone} } // Replace special values in assignees // For web mode, @copilot should be replaced by name; otherwise, login. assigneeSet := set.NewStringSet() meReplacer := prShared.NewMeReplacer(apiClient, baseRepo.RepoHost()) copilotReplacer := prShared.NewCopilotReplacer(!opts.WebMode) assignees, err := meReplacer.ReplaceSlice(opts.Assignees) if err != nil { return err } if issueFeatures.ActorIsAssignable { assignees = copilotReplacer.ReplaceSlice(assignees) } assigneeSet.AddValues(assignees) tb := prShared.IssueMetadataState{ Type: prShared.IssueMetadata, ActorAssignees: issueFeatures.ActorIsAssignable, Assignees: assigneeSet.ToSlice(), Labels: opts.Labels, ProjectTitles: opts.Projects, Milestones: milestones, Title: opts.Title, Body: opts.Body, } if opts.RecoverFile != "" { err = prShared.FillFromJSON(opts.IO, opts.RecoverFile, &tb) if err != nil { err = fmt.Errorf("failed to recover input: %w", err) return } } tpl := prShared.NewTemplateManager(httpClient, baseRepo, opts.Prompter, opts.RootDirOverride, !opts.HasRepoOverride, false) if opts.WebMode { var openURL string if opts.Title != "" || opts.Body != "" || tb.HasMetadata() { openURL, err = generatePreviewURL(apiClient, baseRepo, tb, projectsV1Support) if err != nil { return } if !prShared.ValidURL(openURL) { err = fmt.Errorf("cannot open in browser: maximum URL length exceeded") return } } else if ok, _ := tpl.HasTemplates(); ok { openURL = ghrepo.GenerateRepoURL(baseRepo, "issues/new/choose") } else { openURL = ghrepo.GenerateRepoURL(baseRepo, "issues/new") } if isTerminal { fmt.Fprintf(opts.IO.ErrOut, "Opening %s in your browser.\n", text.DisplayURL(openURL)) } return opts.Browser.Browse(openURL) } if isTerminal { fmt.Fprintf(opts.IO.ErrOut, "\nCreating issue in %s\n\n", ghrepo.FullName(baseRepo)) } repo, err := api.GitHubRepo(apiClient, baseRepo) if err != nil { return } if !repo.HasIssuesEnabled { err = fmt.Errorf("the '%s' repository has disabled issues", ghrepo.FullName(baseRepo)) return } action := prShared.SubmitAction templateNameForSubmit := "" var openURL string if opts.Interactive { defer prShared.PreserveInput(opts.IO, &tb, &err)() if opts.Title == "" { err = prShared.TitleSurvey(opts.Prompter, opts.IO, &tb) if err != nil { return } } if opts.Body == "" { templateContent := "" if opts.RecoverFile == "" { var template prShared.Template if opts.Template != "" { template, err = tpl.Select(opts.Template) if err != nil { return } } else { template, err = tpl.Choose() if err != nil { return } } if template != nil { templateContent = string(template.Body()) templateNameForSubmit = template.NameForSubmit() } else { templateContent = string(tpl.LegacyBody()) } } err = prShared.BodySurvey(opts.Prompter, &tb, templateContent) if err != nil { return } } openURL, err = generatePreviewURL(apiClient, baseRepo, tb, projectsV1Support) if err != nil { return } allowPreview := !tb.HasMetadata() && prShared.ValidURL(openURL) action, err = prShared.ConfirmIssueSubmission(opts.Prompter, allowPreview, repo.ViewerCanTriage()) if err != nil { err = fmt.Errorf("unable to confirm: %w", err) return } if action == prShared.MetadataAction { fetcher := &prShared.MetadataFetcher{ IO: opts.IO, APIClient: apiClient, Repo: baseRepo, State: &tb, } err = prShared.MetadataSurvey(opts.Prompter, opts.IO, baseRepo, fetcher, &tb, projectsV1Support) if err != nil { return } action, err = prShared.ConfirmIssueSubmission(opts.Prompter, !tb.HasMetadata(), false) if err != nil { return } } if action == prShared.CancelAction { fmt.Fprintln(opts.IO.ErrOut, "Discarding.") err = cmdutil.CancelError return } } else { if opts.EditorMode { if opts.Template != "" { var template prShared.Template template, err = tpl.Select(opts.Template) if err != nil { return } if tb.Title == "" { tb.Title = template.Title() } templateNameForSubmit = template.NameForSubmit() tb.Body = string(template.Body()) } tb.Title, tb.Body, err = opts.TitledEditSurvey(tb.Title, tb.Body) if err != nil { return } } if tb.Title == "" { err = fmt.Errorf("title can't be blank") return } } if action == prShared.PreviewAction { if isTerminal { fmt.Fprintf(opts.IO.ErrOut, "Opening %s in your browser.\n", text.DisplayURL(openURL)) } return opts.Browser.Browse(openURL) } else if action == prShared.SubmitAction { params := map[string]interface{}{ "title": tb.Title, "body": tb.Body, } if templateNameForSubmit != "" { params["issueTemplate"] = templateNameForSubmit } err = prShared.AddMetadataToIssueParams(apiClient, baseRepo, params, &tb, projectsV1Support) if err != nil { return } var newIssue *api.Issue newIssue, err = api.IssueCreate(apiClient, repo, params) if err != nil { return } fmt.Fprintln(opts.IO.Out, newIssue.URL) } else { panic("Unreachable state") } return } func generatePreviewURL(apiClient *api.Client, baseRepo ghrepo.Interface, tb prShared.IssueMetadataState, projectsV1Support gh.ProjectsV1Support) (string, error) { openURL := ghrepo.GenerateRepoURL(baseRepo, "issues/new") return prShared.WithPrAndIssueQueryParams(apiClient, baseRepo, openURL, tb, projectsV1Support) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/issue/create/create_test.go
pkg/cmd/issue/create/create_test.go
package create import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" "path/filepath" "strings" "testing" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/browser" "github.com/cli/cli/v2/internal/config" fd "github.com/cli/cli/v2/internal/featuredetection" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/internal/run" 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 TestNewCmdCreate(t *testing.T) { tmpFile := filepath.Join(t.TempDir(), "my-body.md") err := os.WriteFile(tmpFile, []byte("a body from file"), 0600) require.NoError(t, err) tests := []struct { name string tty bool stdin string cli string config string wantsErr bool wantsOpts CreateOptions }{ { name: "empty non-tty", tty: false, cli: "", wantsErr: true, }, { name: "only title non-tty", tty: false, cli: "-t mytitle", wantsErr: true, }, { name: "empty tty", tty: true, cli: "", wantsErr: false, wantsOpts: CreateOptions{ Title: "", Body: "", RecoverFile: "", WebMode: false, Interactive: true, }, }, { name: "body from stdin", tty: false, stdin: "this is on standard input", cli: "-t mytitle -F -", wantsErr: false, wantsOpts: CreateOptions{ Title: "mytitle", Body: "this is on standard input", RecoverFile: "", WebMode: false, Interactive: false, }, }, { name: "body from file", tty: false, cli: fmt.Sprintf("-t mytitle -F '%s'", tmpFile), wantsErr: false, wantsOpts: CreateOptions{ Title: "mytitle", Body: "a body from file", RecoverFile: "", WebMode: false, Interactive: false, }, }, { name: "template from name tty", tty: true, cli: `-t mytitle --template "bug report"`, wantsErr: false, wantsOpts: CreateOptions{ Title: "mytitle", Body: "", RecoverFile: "", WebMode: false, Template: "bug report", Interactive: true, }, }, { name: "template from name non-tty", tty: false, cli: `-t mytitle --template "bug report"`, wantsErr: true, }, { name: "template and body", tty: false, cli: `-t mytitle --template "bug report" --body "issue body"`, wantsErr: true, }, { name: "template and body file", tty: false, cli: `-t mytitle --template "bug report" --body-file "body_file.md"`, wantsErr: true, }, { name: "editor by cli", tty: true, cli: "--editor", wantsErr: false, wantsOpts: CreateOptions{ Title: "", Body: "", RecoverFile: "", WebMode: false, EditorMode: true, Interactive: false, }, }, { name: "editor by config", tty: true, cli: "", config: "prefer_editor_prompt: enabled", wantsErr: false, wantsOpts: CreateOptions{ Title: "", Body: "", RecoverFile: "", WebMode: false, EditorMode: true, Interactive: false, }, }, { name: "editor and template", tty: true, cli: `--editor --template "bug report"`, wantsErr: false, wantsOpts: CreateOptions{ Title: "", Body: "", RecoverFile: "", WebMode: false, EditorMode: true, Template: "bug report", Interactive: false, }, }, { name: "editor and web", tty: true, cli: "--editor --web", wantsErr: true, }, { name: "can use web even though editor is enabled by config", tty: true, cli: `--web --title mytitle --body "issue body"`, config: "prefer_editor_prompt: enabled", wantsErr: false, wantsOpts: CreateOptions{ Title: "mytitle", Body: "issue body", RecoverFile: "", WebMode: true, EditorMode: false, Interactive: false, }, }, { name: "editor with non-tty", tty: false, cli: "--editor", wantsErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, stdin, stdout, stderr := iostreams.Test() if tt.stdin != "" { _, _ = stdin.WriteString(tt.stdin) } else if tt.tty { ios.SetStdinTTY(true) ios.SetStdoutTTY(true) } f := &cmdutil.Factory{ IOStreams: ios, Config: func() (gh.Config, error) { if tt.config != "" { return config.NewFromString(tt.config), nil } return config.NewBlankConfig(), nil }, } var opts *CreateOptions cmd := NewCmdCreate(f, func(o *CreateOptions) error { opts = o return nil }) args, err := shlex.Split(tt.cli) require.NoError(t, err) cmd.SetArgs(args) cmd.SetOut(io.Discard) cmd.SetErr(io.Discard) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) return } else { require.NoError(t, err) } assert.Equal(t, "", stdout.String()) assert.Equal(t, "", stderr.String()) assert.Equal(t, tt.wantsOpts.Body, opts.Body) assert.Equal(t, tt.wantsOpts.Title, opts.Title) assert.Equal(t, tt.wantsOpts.RecoverFile, opts.RecoverFile) assert.Equal(t, tt.wantsOpts.WebMode, opts.WebMode) assert.Equal(t, tt.wantsOpts.Interactive, opts.Interactive) assert.Equal(t, tt.wantsOpts.Template, opts.Template) }) } } func Test_createRun(t *testing.T) { tests := []struct { name string opts CreateOptions httpStubs func(*httpmock.Registry) promptStubs func(*prompter.PrompterMock) wantsStdout string wantsStderr string wantsBrowse string wantsErr string }{ { name: "no args", opts: CreateOptions{ Detector: &fd.EnabledDetectorMock{}, WebMode: true, }, wantsBrowse: "https://github.com/OWNER/REPO/issues/new", wantsStderr: "Opening https://github.com/OWNER/REPO/issues/new in your browser.\n", }, { name: "title and body", opts: CreateOptions{ Detector: &fd.EnabledDetectorMock{}, WebMode: true, Title: "myissue", Body: "hello cli", }, wantsBrowse: "https://github.com/OWNER/REPO/issues/new?body=hello+cli&title=myissue", wantsStderr: "Opening https://github.com/OWNER/REPO/issues/new in your browser.\n", }, { name: "assignee", opts: CreateOptions{ Detector: &fd.EnabledDetectorMock{}, WebMode: true, Assignees: []string{"monalisa"}, }, wantsBrowse: "https://github.com/OWNER/REPO/issues/new?assignees=monalisa&body=", wantsStderr: "Opening https://github.com/OWNER/REPO/issues/new in your browser.\n", }, { name: "@me", opts: CreateOptions{ Detector: &fd.EnabledDetectorMock{}, WebMode: true, Assignees: []string{"@me"}, }, httpStubs: func(r *httpmock.Registry) { r.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(` { "data": { "viewer": { "login": "MonaLisa" } } }`)) }, wantsBrowse: "https://github.com/OWNER/REPO/issues/new?assignees=MonaLisa&body=", wantsStderr: "Opening https://github.com/OWNER/REPO/issues/new in your browser.\n", }, { name: "@copilot", opts: CreateOptions{ Detector: &fd.EnabledDetectorMock{}, WebMode: true, Assignees: []string{"@copilot"}, }, wantsBrowse: "https://github.com/OWNER/REPO/issues/new?assignees=Copilot&body=", wantsStderr: "Opening https://github.com/OWNER/REPO/issues/new in your browser.\n", }, { name: "project", opts: CreateOptions{ Detector: &fd.EnabledDetectorMock{}, WebMode: true, Projects: []string{"cleanup"}, }, httpStubs: func(r *httpmock.Registry) { r.Register( httpmock.GraphQL(`query RepositoryProjectList\b`), httpmock.StringResponse(` { "data": { "repository": { "projects": { "nodes": [ { "name": "Cleanup", "id": "CLEANUPID", "resourcePath": "/OWNER/REPO/projects/1" } ], "pageInfo": { "hasNextPage": false } } } } }`)) r.Register( httpmock.GraphQL(`query OrganizationProjectList\b`), httpmock.StringResponse(` { "data": { "organization": { "projects": { "nodes": [ { "name": "Triage", "id": "TRIAGEID", "resourcePath": "/orgs/ORG/projects/1" } ], "pageInfo": { "hasNextPage": false } } } } }`)) r.Register( httpmock.GraphQL(`query RepositoryProjectV2List\b`), httpmock.StringResponse(` { "data": { "repository": { "projectsV2": { "nodes": [ { "title": "CleanupV2", "id": "CLEANUPV2ID", "resourcePath": "/OWNER/REPO/projects/2" } ], "pageInfo": { "hasNextPage": false } } } } }`)) r.Register( httpmock.GraphQL(`query OrganizationProjectV2List\b`), httpmock.StringResponse(` { "data": { "organization": { "projectsV2": { "nodes": [ { "title": "Triage", "id": "TRIAGEID", "resourcePath": "/orgs/ORG/projects/2" } ], "pageInfo": { "hasNextPage": false } } } } }`)) r.Register( httpmock.GraphQL(`query UserProjectV2List\b`), httpmock.StringResponse(` { "data": { "viewer": { "projectsV2": { "nodes": [ { "title": "Monalisa", "id": "MONALISAID", "resourcePath": "/users/MONALISA/projects/1" } ], "pageInfo": { "hasNextPage": false } } } } }`)) }, wantsBrowse: "https://github.com/OWNER/REPO/issues/new?body=&projects=OWNER%2FREPO%2F1", wantsStderr: "Opening https://github.com/OWNER/REPO/issues/new in your browser.\n", }, { name: "has templates", opts: CreateOptions{ Detector: &fd.EnabledDetectorMock{}, WebMode: true, }, httpStubs: func(r *httpmock.Registry) { r.Register( httpmock.GraphQL(`query IssueTemplates\b`), httpmock.StringResponse(` { "data": { "repository": { "issueTemplates": [ { "name": "Bug report", "body": "Does not work :((" }, { "name": "Submit a request", "body": "I have a suggestion for an enhancement" } ] } } }`), ) }, wantsBrowse: "https://github.com/OWNER/REPO/issues/new/choose", wantsStderr: "Opening https://github.com/OWNER/REPO/issues/new/choose in your browser.\n", }, { name: "too long body", opts: CreateOptions{ Detector: &fd.EnabledDetectorMock{}, WebMode: true, Body: strings.Repeat("A", 9216), }, wantsErr: "cannot open in browser: maximum URL length exceeded", }, { name: "editor", httpStubs: func(r *httpmock.Registry) { r.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "id": "REPOID", "hasIssuesEnabled": true } } }`)) r.Register( httpmock.GraphQL(`mutation IssueCreate\b`), httpmock.GraphQLMutation(` { "data": { "createIssue": { "issue": { "URL": "https://github.com/OWNER/REPO/issues/12" } } } } `, func(inputs map[string]interface{}) { assert.Equal(t, "title", inputs["title"]) assert.Equal(t, "body", inputs["body"]) })) }, opts: CreateOptions{ Detector: &fd.EnabledDetectorMock{}, EditorMode: true, TitledEditSurvey: func(string, string) (string, string, error) { return "title", "body", nil }, }, wantsStdout: "https://github.com/OWNER/REPO/issues/12\n", wantsStderr: "\nCreating issue in OWNER/REPO\n\n", }, { name: "editor and template", httpStubs: func(r *httpmock.Registry) { r.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "id": "REPOID", "hasIssuesEnabled": true } } }`)) r.Register( httpmock.GraphQL(`query IssueTemplates\b`), httpmock.StringResponse(` { "data": { "repository": { "issueTemplates": [ { "name": "Bug report", "title": "bug: ", "body": "Does not work :((" } ] } } }`), ) r.Register( httpmock.GraphQL(`mutation IssueCreate\b`), httpmock.GraphQLMutation(` { "data": { "createIssue": { "issue": { "URL": "https://github.com/OWNER/REPO/issues/12" } } } } `, func(inputs map[string]interface{}) { assert.Equal(t, "bug: ", inputs["title"]) assert.Equal(t, "Does not work :((", inputs["body"]) })) }, opts: CreateOptions{ Detector: &fd.EnabledDetectorMock{}, EditorMode: true, Template: "Bug report", TitledEditSurvey: func(title string, body string) (string, string, error) { return title, body, nil }, }, wantsStdout: "https://github.com/OWNER/REPO/issues/12\n", wantsStderr: "\nCreating issue in OWNER/REPO\n\n", }, { name: "interactive prompts with actor assignee display names when actors available", opts: CreateOptions{ Interactive: true, Detector: &fd.EnabledDetectorMock{}, Title: "test `gh issue create` actor assignees", Body: "Actor assignees allow users and bots to be assigned to issues", }, promptStubs: func(pm *prompter.PrompterMock) { firstConfirmSubmission := true pm.InputFunc = func(message, defaultValue string) (string, error) { switch message { default: return "", fmt.Errorf("unexpected input prompt: %s", message) } } pm.MultiSelectFunc = func(message string, defaults []string, options []string) ([]int, error) { switch message { case "What would you like to add?": return prompter.IndexesFor(options, "Assignees") case "Assignees": return prompter.IndexesFor(options, "Copilot (AI)", "MonaLisa (Mona Display Name)") default: return nil, fmt.Errorf("unexpected multi-select prompt: %s", message) } } pm.SelectFunc = func(message, defaultValue string, options []string) (int, error) { switch message { case "What's next?": if firstConfirmSubmission { firstConfirmSubmission = false return prompter.IndexFor(options, "Add metadata") } return prompter.IndexFor(options, "Submit") default: return 0, fmt.Errorf("unexpected select prompt: %s", message) } } }, httpStubs: func(r *httpmock.Registry) { r.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "id": "REPOID", "hasIssuesEnabled": true, "viewerPermission": "WRITE" } } } `)) r.Register( httpmock.GraphQL(`query RepositoryAssignableActors\b`), httpmock.StringResponse(` { "data": { "repository": { "suggestedActors": { "nodes": [ { "login": "copilot-swe-agent", "id": "COPILOTID", "name": "Copilot (AI)", "__typename": "Bot" }, { "login": "MonaLisa", "id": "MONAID", "name": "Mona Display Name", "__typename": "User" } ], "pageInfo": { "hasNextPage": false } } } } } `)) r.Register( httpmock.GraphQL(`mutation IssueCreate\b`), httpmock.GraphQLMutation(` { "data": { "createIssue": { "issue": { "URL": "https://github.com/OWNER/REPO/issues/12" } } } } `, func(inputs map[string]interface{}) { assert.Equal(t, []interface{}{"COPILOTID", "MONAID"}, inputs["assigneeIds"]) })) }, wantsStdout: "https://github.com/OWNER/REPO/issues/12\n", wantsStderr: "\nCreating issue in OWNER/REPO\n\n", }, { name: "interactive prompts with user assignee logins when actors unavailable", opts: CreateOptions{ Interactive: true, Detector: &fd.DisabledDetectorMock{}, Title: "test `gh issue create` user assignees", Body: "User assignees allow only users to be assigned to issues", }, promptStubs: func(pm *prompter.PrompterMock) { firstConfirmSubmission := true pm.InputFunc = func(message, defaultValue string) (string, error) { switch message { default: return "", fmt.Errorf("unexpected input prompt: %s", message) } } pm.MultiSelectFunc = func(message string, defaults []string, options []string) ([]int, error) { switch message { case "What would you like to add?": return prompter.IndexesFor(options, "Assignees") case "Assignees": return prompter.IndexesFor(options, "hubot", "MonaLisa (Mona Display Name)") default: return nil, fmt.Errorf("unexpected multi-select prompt: %s", message) } } pm.SelectFunc = func(message, defaultValue string, options []string) (int, error) { switch message { case "What's next?": if firstConfirmSubmission { firstConfirmSubmission = false return prompter.IndexFor(options, "Add metadata") } return prompter.IndexFor(options, "Submit") default: return 0, fmt.Errorf("unexpected select prompt: %s", message) } } }, httpStubs: func(r *httpmock.Registry) { r.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "id": "REPOID", "hasIssuesEnabled": true, "viewerPermission": "WRITE" } } } `)) r.Register( httpmock.GraphQL(`query RepositoryAssignableUsers\b`), httpmock.StringResponse(` { "data": { "repository": { "assignableUsers": { "nodes": [ { "login": "hubot", "id": "HUBOTID", "name": "" }, { "login": "MonaLisa", "id": "MONAID", "name": "Mona Display Name" } ], "pageInfo": { "hasNextPage": false } } } } } `)) r.Register( httpmock.GraphQL(`mutation IssueCreate\b`), httpmock.GraphQLMutation(` { "data": { "createIssue": { "issue": { "URL": "https://github.com/OWNER/REPO/issues/12" } } } } `, func(inputs map[string]interface{}) { assert.Equal(t, []interface{}{"HUBOTID", "MONAID"}, inputs["assigneeIds"]) })) }, wantsStdout: "https://github.com/OWNER/REPO/issues/12\n", wantsStderr: "\nCreating issue in OWNER/REPO\n\n", }, } 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) } ios, _, stdout, stderr := iostreams.Test() ios.SetStdoutTTY(true) opts := &tt.opts opts.IO = ios opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: httpReg}, nil } opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil } browser := &browser.Stub{} opts.Browser = browser prompterMock := &prompter.PrompterMock{} opts.Prompter = prompterMock if tt.promptStubs != nil { tt.promptStubs(prompterMock) } err := createRun(opts) if tt.wantsErr == "" { require.NoError(t, err) } else { assert.EqualError(t, err, tt.wantsErr) return } assert.Equal(t, tt.wantsStdout, stdout.String()) assert.Equal(t, tt.wantsStderr, stderr.String()) browser.Verify(t, tt.wantsBrowse) }) } } /*** LEGACY TESTS ***/ func runCommand(rt http.RoundTripper, isTTY bool, cli string, pm *prompter.PrompterMock) (*test.CmdOut, error) { return runCommandWithRootDirOverridden(rt, isTTY, cli, "", pm) } func runCommandWithRootDirOverridden(rt http.RoundTripper, isTTY bool, cli string, rootDir string, pm *prompter.PrompterMock) (*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, HttpClient: func() (*http.Client, error) { return &http.Client{Transport: rt}, nil }, Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil }, Browser: browser, Prompter: pm, } cmd := NewCmdCreate(factory, func(opts *CreateOptions) error { opts.RootDirOverride = rootDir opts.Detector = &fd.EnabledDetectorMock{} return createRun(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 TestIssueCreate(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) http.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "id": "REPOID", "hasIssuesEnabled": true } } }`), ) http.Register( httpmock.GraphQL(`mutation IssueCreate\b`), httpmock.GraphQLMutation(` { "data": { "createIssue": { "issue": { "URL": "https://github.com/OWNER/REPO/issues/12" } } } }`, func(inputs map[string]interface{}) { assert.Equal(t, inputs["repositoryId"], "REPOID") assert.Equal(t, inputs["title"], "hello") assert.Equal(t, inputs["body"], "cash rules everything around me") }), ) output, err := runCommand(http, true, `-t hello -b "cash rules everything around me"`, nil) if err != nil { t.Errorf("error running command `issue create`: %v", err) } assert.Equal(t, "https://github.com/OWNER/REPO/issues/12\n", output.String()) } func TestIssueCreate_recover(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) http.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "id": "REPOID", "hasIssuesEnabled": true } } }`)) // Should only be one fetch of metadata. http.Register( httpmock.GraphQL(`query RepositoryLabelList\b`), httpmock.StringResponse(` { "data": { "repository": { "labels": { "nodes": [ { "name": "TODO", "id": "TODOID" }, { "name": "bug", "id": "BUGID" } ], "pageInfo": { "hasNextPage": false } } } } } `)) http.Register( httpmock.GraphQL(`mutation IssueCreate\b`), httpmock.GraphQLMutation(` { "data": { "createIssue": { "issue": { "URL": "https://github.com/OWNER/REPO/issues/12" } } } } `, func(inputs map[string]interface{}) { assert.Equal(t, "recovered title", inputs["title"]) assert.Equal(t, "recovered body", inputs["body"]) assert.Equal(t, []interface{}{"BUGID", "TODOID"}, inputs["labelIds"]) })) pm := &prompter.PrompterMock{} pm.InputFunc = func(p, d string) (string, error) { if p == "Title (required)" { return d, nil } else { return "", prompter.NoSuchPromptErr(p) } } pm.MarkdownEditorFunc = func(p, d string, ba bool) (string, error) { if p == "Body" { return d, nil } else { return "", prompter.NoSuchPromptErr(p) } } pm.SelectFunc = func(p, _ string, opts []string) (int, error) { if p == "What's next?" { return prompter.IndexFor(opts, "Submit") } else { return -1, prompter.NoSuchPromptErr(p) } } tmpfile, err := os.CreateTemp(t.TempDir(), "testrecover*") assert.NoError(t, err) defer tmpfile.Close() state := prShared.IssueMetadataState{ Title: "recovered title", Body: "recovered body", Labels: []string{"bug", "TODO"}, } data, err := json.Marshal(state) assert.NoError(t, err) _, err = tmpfile.Write(data) assert.NoError(t, err) args := fmt.Sprintf("--recover '%s'", tmpfile.Name()) output, err := runCommandWithRootDirOverridden(http, true, args, "", pm) if err != nil { t.Errorf("error running command `issue create`: %v", err) } assert.Equal(t, "https://github.com/OWNER/REPO/issues/12\n", output.String()) } func TestIssueCreate_nonLegacyTemplate(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) http.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "id": "REPOID", "hasIssuesEnabled": true } } }`), ) http.Register( httpmock.GraphQL(`query IssueTemplates\b`), httpmock.StringResponse(` { "data": { "repository": { "issueTemplates": [ { "name": "Bug report", "body": "Does not work :((" }, { "name": "Submit a request", "body": "I have a suggestion for an enhancement" } ] } } }`), ) http.Register( httpmock.GraphQL(`mutation IssueCreate\b`), httpmock.GraphQLMutation(` { "data": { "createIssue": { "issue": { "URL": "https://github.com/OWNER/REPO/issues/12" } } } }`, func(inputs map[string]interface{}) { assert.Equal(t, inputs["repositoryId"], "REPOID") assert.Equal(t, inputs["title"], "hello") assert.Equal(t, inputs["body"], "I have a suggestion for an enhancement") }), ) pm := &prompter.PrompterMock{} pm.MarkdownEditorFunc = func(p, d string, ba bool) (string, error) { if p == "Body" { return d, nil } else { return "", prompter.NoSuchPromptErr(p) } } pm.SelectFunc = func(p, _ string, opts []string) (int, error) { switch p { case "What's next?": return prompter.IndexFor(opts, "Submit") case "Choose a template": return prompter.IndexFor(opts, "Submit a request") default: return -1, prompter.NoSuchPromptErr(p) } } output, err := runCommandWithRootDirOverridden(http, true, `-t hello`, "./fixtures/repoWithNonLegacyIssueTemplates", pm) if err != nil { t.Errorf("error running command `issue create`: %v", err) } assert.Equal(t, "https://github.com/OWNER/REPO/issues/12\n", output.String()) assert.Equal(t, "", output.BrowsedURL) } func TestIssueCreate_continueInBrowser(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) http.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "id": "REPOID", "hasIssuesEnabled": true } } }`), ) pm := &prompter.PrompterMock{} pm.InputFunc = func(p, d string) (string, error) { if p == "Title (required)" { return "hello", nil } else { return "", prompter.NoSuchPromptErr(p) } } pm.SelectFunc = func(p, _ string, opts []string) (int, error) { if p == "What's next?" { return prompter.IndexFor(opts, "Continue in browser") } else { return -1, prompter.NoSuchPromptErr(p) } } _, cmdTeardown := run.Stub() defer cmdTeardown(t) output, err := runCommand(http, true, `-b body`, pm) if err != nil { t.Errorf("error running command `issue create`: %v", err) } assert.Equal(t, "", output.String()) assert.Equal(t, heredoc.Doc(` Creating issue in OWNER/REPO Opening https://github.com/OWNER/REPO/issues/new in your browser. `), output.Stderr()) assert.Equal(t, "https://github.com/OWNER/REPO/issues/new?body=body&title=hello", output.BrowsedURL) } func TestIssueCreate_metadata(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) http.StubRepoInfoResponse("OWNER", "REPO", "main") http.Register( httpmock.GraphQL(`query RepositoryAssignableActors\b`), httpmock.StringResponse(` { "data": { "repository": { "suggestedActors": { "nodes": [ { "login": "MonaLisa", "id": "MONAID", "name": "Mona Display Name", "__typename": "User" } ], "pageInfo": { "hasNextPage": false } } } } } `)) http.Register( httpmock.GraphQL(`query RepositoryLabelList\b`), httpmock.StringResponse(` { "data": { "repository": { "labels": { "nodes": [ { "name": "TODO", "id": "TODOID" }, { "name": "bug", "id": "BUGID" } ], "pageInfo": { "hasNextPage": false } } } } } `)) http.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 } } } } } `)) http.Register( httpmock.GraphQL(`query RepositoryProjectList\b`), httpmock.StringResponse(` { "data": { "repository": { "projects": { "nodes": [ { "name": "Cleanup", "id": "CLEANUPID" }, { "name": "Roadmap", "id": "ROADMAPID" } ], "pageInfo": { "hasNextPage": false } } } } } `)) http.Register( httpmock.GraphQL(`query OrganizationProjectList\b`), httpmock.StringResponse(` { "data": { "organization": null }, "errors": [{ "type": "NOT_FOUND", "path": [ "organization" ], "message": "Could not resolve to an Organization with the login of 'OWNER'." }] } `)) http.Register( httpmock.GraphQL(`query RepositoryProjectV2List\b`), httpmock.StringResponse(` { "data": { "repository": { "projectsV2": { "nodes": [], "pageInfo": { "hasNextPage": false } } } } } `)) http.Register( httpmock.GraphQL(`query OrganizationProjectV2List\b`), httpmock.StringResponse(` { "data": { "organization": { "projectsV2": { "nodes": [], "pageInfo": { "hasNextPage": false } } } } } `)) http.Register( httpmock.GraphQL(`query UserProjectV2List\b`), httpmock.StringResponse(` { "data": { "viewer": { "projectsV2": { "nodes": [], "pageInfo": { "hasNextPage": false } } } } } `)) http.Register( httpmock.GraphQL(`mutation IssueCreate\b`), httpmock.GraphQLMutation(` { "data": { "createIssue": { "issue": { "URL": "https://github.com/OWNER/REPO/issues/12" } } } } `, func(inputs map[string]interface{}) { assert.Equal(t, "TITLE", inputs["title"]) assert.Equal(t, "BODY", inputs["body"]) assert.Equal(t, []interface{}{"MONAID"}, inputs["assigneeIds"]) assert.Equal(t, []interface{}{"BUGID", "TODOID"}, inputs["labelIds"]) assert.Equal(t, []interface{}{"ROADMAPID"}, inputs["projectIds"]) assert.Equal(t, "BIGONEID", inputs["milestoneId"]) assert.NotContains(t, inputs, "userIds") assert.NotContains(t, inputs, "teamIds") assert.NotContains(t, inputs, "projectV2Ids") })) output, err := runCommand(http, true, `-t TITLE -b BODY -a monalisa -l bug -l todo -p roadmap -m 'big one.oh'`, nil) if err != nil { t.Errorf("error running command `issue create`: %v", err) } assert.Equal(t, "https://github.com/OWNER/REPO/issues/12\n", output.String()) } func TestIssueCreate_disabledIssues(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) http.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "id": "REPOID", "hasIssuesEnabled": false } } }`), ) _, err := runCommand(http, true, `-t heres -b johnny`, nil) if err == nil || err.Error() != "the 'OWNER/REPO' repository has disabled issues" { t.Errorf("error running command `issue create`: %v", err) } } func TestIssueCreate_AtMeAssignee(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) http.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(` { "data": { "viewer": { "login": "MonaLisa" } } } `), ) http.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "id": "REPOID", "hasIssuesEnabled": true } } } `)) http.Register( httpmock.GraphQL(`query RepositoryAssignableActors\b`), httpmock.StringResponse(` { "data": { "repository": { "suggestedActors": { "nodes": [ { "login": "MonaLisa", "id": "MONAID", "name": "Mona Display Name", "__typename": "User" }, { "login": "SomeOneElse", "id": "SOMEID", "name": "Someone else", "__typename": "User" } ], "pageInfo": { "hasNextPage": false } } } } } `)) http.Register( httpmock.GraphQL(`mutation IssueCreate\b`), httpmock.GraphQLMutation(` { "data": { "createIssue": { "issue": { "URL": "https://github.com/OWNER/REPO/issues/12" } } } } `, func(inputs map[string]interface{}) { assert.Equal(t, "hello", inputs["title"]) assert.Equal(t, "cash rules everything around me", inputs["body"]) assert.Equal(t, []interface{}{"MONAID", "SOMEID"}, inputs["assigneeIds"]) })) output, err := runCommand(http, true, `-a @me -a someoneelse -t hello -b "cash rules everything around me"`, nil) if err != nil { t.Errorf("error running command `issue create`: %v", err) } assert.Equal(t, "https://github.com/OWNER/REPO/issues/12\n", output.String()) } func TestIssueCreate_AtCopilotAssignee(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) http.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "id": "REPOID", "hasIssuesEnabled": true } } } `)) http.Register( httpmock.GraphQL(`query RepositoryAssignableActors\b`), httpmock.StringResponse(`
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
true
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/issue/lock/lock.go
pkg/cmd/issue/lock/lock.go
// Package lock locks and unlocks conversations on both GitHub issues and pull // requests. // // Every pull request is an issue, but not every issue is a pull request. // Therefore, this package is used in `cmd/pr` as well. // // A note on nomenclature for "comments", "conversations", and "discussions": // The GitHub documentation refers to a set of comments on an issue or pull // request as a conversation. A GitHub discussion refers to the "message board" // for a project where announcements, questions, and answers can be posted. package lock import ( "errors" "fmt" "net/http" "strings" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/issue/shared" issueShared "github.com/cli/cli/v2/pkg/cmd/issue/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/shurcooL/githubv4" "github.com/spf13/cobra" ) type iprompter interface { Confirm(string, bool) (bool, error) Select(string, string, []string) (int, error) } // reasons contains all possible lock reasons allowed by GitHub. // // We don't directly construct a map so that we can maintain the reasons in // alphabetical order. var reasons = []string{"off_topic", "resolved", "spam", "too_heated"} var reasonsString = strings.Join(reasons, ", ") var reasonsApi = []githubv4.LockReason{ githubv4.LockReasonOffTopic, githubv4.LockReasonResolved, githubv4.LockReasonSpam, githubv4.LockReasonTooHeated, } // If no reason is given (an empty string), reasonsMap will return the nil // value, since it is not contained in the map. This, in turn, sets lock_reason // to null in GraphQL. var reasonsMap map[string]*githubv4.LockReason func init() { reasonsMap = make(map[string]*githubv4.LockReason) for i, reason := range reasons { reasonsMap[reason] = &reasonsApi[i] } } type command struct { Name string // actual command name FullName string // complete name for the command Typename string // return value from issue.Typename } // The `FullName` should be capitalized as if starting a sentence since it is // used in print and error statements. It's easier to manually capitalize and // call `ToLower`, when needed, than the other way around. var aliasIssue = command{"issue", "Issue", api.TypeIssue} var aliasPr = command{"pr", "Pull request", api.TypePullRequest} var alias map[string]*command = map[string]*command{ "issue": &aliasIssue, "pr": &aliasPr, api.TypeIssue: &aliasIssue, api.TypePullRequest: &aliasPr, } // Acceptable lock states for conversations. These are used in print // statements, hence the use of strings instead of booleans. const ( Lock = "Lock" Unlock = "Unlock" ) func fields() []string { return []string{ "activeLockReason", "id", "locked", "number", "title", "url", } } type LockOptions struct { HttpClient func() (*http.Client, error) Config func() (gh.Config, error) IO *iostreams.IOStreams BaseRepo func() (ghrepo.Interface, error) Prompter iprompter ParentCmd string Reason string IssueNumber int Interactive bool } func (opts *LockOptions) setCommonOptions(f *cmdutil.Factory, args []string) error { opts.IO = f.IOStreams opts.HttpClient = f.HttpClient opts.Config = f.Config issueNumber, baseRepo, err := shared.ParseIssueFromArg(args[0]) if err != nil { return err } // If the args provided the base repo then use that directly. if baseRepo, present := baseRepo.Value(); present { opts.BaseRepo = func() (ghrepo.Interface, error) { return baseRepo, nil } } else { // support `-R, --repo` override opts.BaseRepo = f.BaseRepo } opts.IssueNumber = issueNumber return nil } func NewCmdLock(f *cmdutil.Factory, parentName string, runF func(string, *LockOptions) error) *cobra.Command { opts := &LockOptions{ ParentCmd: parentName, Prompter: f.Prompter, } c := alias[opts.ParentCmd] short := fmt.Sprintf("Lock %s conversation", strings.ToLower(c.FullName)) cmd := &cobra.Command{ Use: "lock {<number> | <url>}", Short: short, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { if err := opts.setCommonOptions(f, args); err != nil { return err } reasonProvided := cmd.Flags().Changed("reason") if reasonProvided { _, ok := reasonsMap[opts.Reason] if !ok { if opts.IO.IsStdoutTTY() { cs := opts.IO.ColorScheme() return cmdutil.FlagErrorf("%s Invalid reason: %v\n", cs.FailureIconWithColor(cs.Red), opts.Reason) } else { return fmt.Errorf("invalid reason %s", opts.Reason) } } } else if opts.IO.CanPrompt() { opts.Interactive = true } if runF != nil { return runF(Lock, opts) } return lockRun(Lock, opts) }, } msg := fmt.Sprintf("Optional reason for locking conversation (%v).", reasonsString) cmd.Flags().StringVarP(&opts.Reason, "reason", "r", "", msg) return cmd } func NewCmdUnlock(f *cmdutil.Factory, parentName string, runF func(string, *LockOptions) error) *cobra.Command { opts := &LockOptions{ParentCmd: parentName} c := alias[opts.ParentCmd] short := fmt.Sprintf("Unlock %s conversation", strings.ToLower(c.FullName)) cmd := &cobra.Command{ Use: "unlock {<number> | <url>}", Short: short, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { if err := opts.setCommonOptions(f, args); err != nil { return err } if runF != nil { return runF(Unlock, opts) } return lockRun(Unlock, opts) }, } return cmd } // reason creates a sentence fragment so that the lock reason can be used in a // sentence. // // e.g. "resolved" -> " as RESOLVED" func reason(reason string) string { result := "" if reason != "" { result = fmt.Sprintf(" as %s", strings.ToUpper(reason)) } return result } // status creates a string showing the result of a successful lock/unlock that // is parameterized on a bunch of options. // // Example output: "Locked as RESOLVED: Issue #31 (Title of issue)" func status(state string, lockable *api.Issue, baseRepo ghrepo.Interface, opts *LockOptions) string { return fmt.Sprintf("%sed%s: %s %s#%d (%s)", state, reason(opts.Reason), alias[opts.ParentCmd].FullName, ghrepo.FullName(baseRepo), lockable.Number, lockable.Title) } // lockRun will lock or unlock a conversation. func lockRun(state string, opts *LockOptions) error { cs := opts.IO.ColorScheme() httpClient, err := opts.HttpClient() if err != nil { return err } baseRepo, err := opts.BaseRepo() if err != nil { return err } issuePr, err := issueShared.FindIssueOrPR(httpClient, baseRepo, opts.IssueNumber, fields()) if err != nil { return err } parent := alias[opts.ParentCmd] if parent.Typename != issuePr.Typename { currentType := alias[parent.Typename] correctType := alias[issuePr.Typename] return fmt.Errorf("%s %s %s#%d not found, but found %s %s#%d. Use `gh %s %s %d` instead", cs.FailureIconWithColor(cs.Red), currentType.FullName, ghrepo.FullName(baseRepo), issuePr.Number, strings.ToLower(correctType.FullName), ghrepo.FullName(baseRepo), issuePr.Number, correctType.Name, strings.ToLower(state), issuePr.Number) } if opts.Interactive { options := []string{"None", "Off topic", "Resolved", "Spam", "Too heated"} selected, err := opts.Prompter.Select("Lock reason?", "", options) if err != nil { return err } if selected > 0 { opts.Reason = reasons[selected-1] } } successMsg := fmt.Sprintf("%s %s\n", cs.SuccessIconWithColor(cs.Green), status(state, issuePr, baseRepo, opts)) switch state { case Lock: if !issuePr.Locked { err = lockLockable(httpClient, baseRepo, issuePr, opts) } else { var relocked bool relocked, err = relockLockable(httpClient, baseRepo, issuePr, opts) if !relocked { successMsg = fmt.Sprintf("%s %s#%d already locked%s. Nothing changed.\n", parent.FullName, ghrepo.FullName(baseRepo), issuePr.Number, reason(issuePr.ActiveLockReason)) } } case Unlock: if issuePr.Locked { err = unlockLockable(httpClient, baseRepo, issuePr) } else { successMsg = fmt.Sprintf("%s %s#%d already unlocked. Nothing changed.\n", parent.FullName, ghrepo.FullName(baseRepo), issuePr.Number) } default: panic("bad state") } if err != nil { return err } if opts.IO.IsStdoutTTY() { fmt.Fprint(opts.IO.Out, successMsg) } return nil } // lockLockable will lock an issue or pull request func lockLockable(httpClient *http.Client, repo ghrepo.Interface, lockable *api.Issue, opts *LockOptions) error { var mutation struct { LockLockable struct { LockedRecord struct { Locked bool } } `graphql:"lockLockable(input: $input)"` } variables := map[string]interface{}{ "input": githubv4.LockLockableInput{ LockableID: lockable.ID, LockReason: reasonsMap[opts.Reason], }, } gql := api.NewClientFromHTTP(httpClient) return gql.Mutate(repo.RepoHost(), "LockLockable", &mutation, variables) } // unlockLockable will unlock an issue or pull request func unlockLockable(httpClient *http.Client, repo ghrepo.Interface, lockable *api.Issue) error { var mutation struct { UnlockLockable struct { UnlockedRecord struct { Locked bool } } `graphql:"unlockLockable(input: $input)"` } variables := map[string]interface{}{ "input": githubv4.UnlockLockableInput{ LockableID: lockable.ID, }, } gql := api.NewClientFromHTTP(httpClient) return gql.Mutate(repo.RepoHost(), "UnlockLockable", &mutation, variables) } // relockLockable will unlock then lock an issue or pull request. A common use // case would be to change the reason for locking. // // The current api doesn't allow you to send a single lock request to update a // lockable item that is already locked; it will just ignore that request. You // need to first unlock then lock with a new reason. func relockLockable(httpClient *http.Client, repo ghrepo.Interface, lockable *api.Issue, opts *LockOptions) (bool, error) { if !opts.IO.CanPrompt() { return false, errors.New("already locked") } prompt := fmt.Sprintf("%s %s#%d already locked%s. Unlock and lock again%s?", alias[opts.ParentCmd].FullName, ghrepo.FullName(repo), lockable.Number, reason(lockable.ActiveLockReason), reason(opts.Reason)) relocked, err := opts.Prompter.Confirm(prompt, true) if err != nil { return false, err } else if !relocked { return relocked, nil } err = unlockLockable(httpClient, repo, lockable) if err != nil { return relocked, err } err = lockLockable(httpClient, repo, lockable, opts) if err != nil { return relocked, err } return relocked, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/issue/lock/lock_test.go
pkg/cmd/issue/lock/lock_test.go
package lock import ( "bytes" "io" "net/http" "strings" "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/cli/cli/v2/test" "github.com/google/shlex" "github.com/stretchr/testify/assert" ) func Test_NewCmdLock(t *testing.T) { cases := []struct { name string args string want LockOptions wantErr string tty bool }{ { name: "sets reason", args: "--reason off_topic 451", want: LockOptions{ Reason: "off_topic", IssueNumber: 451, }, }, { name: "no args", wantErr: "accepts 1 arg(s), received 0", }, { name: "no flags", args: "451", want: LockOptions{ IssueNumber: 451, }, }, { name: "issue number argument", args: "451 --repo owner/repo", want: LockOptions{ IssueNumber: 451, }, }, { name: "argument is hash prefixed number", // Escaping is required here to avoid what I think is shellex treating it as a comment. args: "\\#451 --repo owner/repo", want: LockOptions{ IssueNumber: 451, }, }, { name: "argument is a URL", args: "https://github.com/cli/cli/issues/451", want: LockOptions{ IssueNumber: 451, }, }, { name: "argument cannot be parsed to an issue", args: "unparseable", wantErr: "invalid issue format: \"unparseable\"", }, { name: "bad reason", args: "--reason bad 451", wantErr: "invalid reason bad", }, { name: "bad reason tty", args: "--reason bad 451", tty: true, wantErr: "X Invalid reason: bad\n", }, { name: "interactive", args: "451", tty: true, want: LockOptions{ IssueNumber: 451, Interactive: true, }, }, } for _, tt := range cases { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() ios.SetStdoutTTY(tt.tty) ios.SetStdinTTY(tt.tty) ios.SetStderrTTY(tt.tty) f := &cmdutil.Factory{ IOStreams: ios, } var opts *LockOptions cmd := NewCmdLock(f, "issue", func(_ string, o *LockOptions) error { opts = o return nil }) cmd.PersistentFlags().StringP("repo", "R", "", "") argv, err := shlex.Split(tt.args) assert.NoError(t, err) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(io.Discard) cmd.SetErr(io.Discard) _, err = cmd.ExecuteC() if tt.wantErr != "" { assert.EqualError(t, err, tt.wantErr) return } else { assert.NoError(t, err) } assert.Equal(t, tt.want.Reason, opts.Reason) assert.Equal(t, tt.want.IssueNumber, opts.IssueNumber) assert.Equal(t, tt.want.Interactive, opts.Interactive) }) } } func Test_NewCmdUnlock(t *testing.T) { cases := []struct { name string args string want LockOptions wantErr string tty bool }{ { name: "no args", wantErr: "accepts 1 arg(s), received 0", }, { name: "no flags", args: "451", want: LockOptions{ IssueNumber: 451, }, }, { name: "issue number argument", args: "451 --repo owner/repo", want: LockOptions{ IssueNumber: 451, }, }, { name: "argument is hash prefixed number", // Escaping is required here to avoid what I think is shellex treating it as a comment. args: "\\#451 --repo owner/repo", want: LockOptions{ IssueNumber: 451, }, }, { name: "argument is a URL", args: "https://github.com/cli/cli/issues/451", want: LockOptions{ IssueNumber: 451, }, }, { name: "argument cannot be parsed to an issue", args: "unparseable", wantErr: "invalid issue format: \"unparseable\"", }, } for _, tt := range cases { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() ios.SetStdoutTTY(tt.tty) ios.SetStdinTTY(tt.tty) ios.SetStderrTTY(tt.tty) f := &cmdutil.Factory{ IOStreams: ios, } var opts *LockOptions cmd := NewCmdUnlock(f, "issue", func(_ string, o *LockOptions) error { opts = o return nil }) cmd.PersistentFlags().StringP("repo", "R", "", "") argv, err := shlex.Split(tt.args) assert.NoError(t, err) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(io.Discard) cmd.SetErr(io.Discard) _, err = cmd.ExecuteC() if tt.wantErr != "" { assert.EqualError(t, err, tt.wantErr) return } else { assert.NoError(t, err) } assert.Equal(t, tt.want.IssueNumber, opts.IssueNumber) }) } } func Test_runLock(t *testing.T) { cases := []struct { name string opts LockOptions promptStubs func(*testing.T, *prompter.PrompterMock) httpStubs func(*testing.T, *httpmock.Registry) wantOut string wantErrOut string wantErr string tty bool state string }{ { name: "lock issue nontty", state: Lock, opts: LockOptions{ IssueNumber: 451, ParentCmd: "issue", }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "number": 451, "__typename": "Issue" }}}}`)) reg.Register( httpmock.GraphQL(`mutation LockLockable\b`), httpmock.StringResponse(` { "data": { "lockLockable": { "lockedRecord": { "locked": true }}}}`)) }, }, { name: "lock issue tty", tty: true, opts: LockOptions{ Interactive: true, IssueNumber: 451, ParentCmd: "issue", }, state: Lock, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "number": 451, "title": "traverse the library", "__typename": "Issue" }}}}`)) reg.Register( httpmock.GraphQL(`mutation LockLockable\b`), httpmock.StringResponse(` { "data": { "lockLockable": { "lockedRecord": { "locked": true }}}}`)) }, promptStubs: func(t *testing.T, pm *prompter.PrompterMock) { pm.SelectFunc = func(p, d string, opts []string) (int, error) { if p == "Lock reason?" { assert.Equal(t, []string{"None", "Off topic", "Resolved", "Spam", "Too heated"}, opts) return prompter.IndexFor(opts, "Too heated") } return -1, prompter.NoSuchPromptErr(p) } }, wantOut: "✓ Locked as TOO_HEATED: Issue OWNER/REPO#451 (traverse the library)\n", }, { name: "lock issue with explicit reason tty", tty: true, state: Lock, opts: LockOptions{ IssueNumber: 451, ParentCmd: "issue", Reason: "off_topic", }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "number": 451, "title": "traverse the library", "__typename": "Issue" }}}}`)) reg.Register( httpmock.GraphQL(`mutation LockLockable\b`), httpmock.StringResponse(` { "data": { "lockLockable": { "lockedRecord": { "locked": true }}}}`)) }, wantOut: "✓ Locked as OFF_TOPIC: Issue OWNER/REPO#451 (traverse the library)\n", }, { name: "unlock issue tty", tty: true, state: Unlock, opts: LockOptions{ IssueNumber: 451, ParentCmd: "issue", }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "number": 451, "locked": true, "title": "traverse the library", "__typename": "Issue" }}}}`)) reg.Register( httpmock.GraphQL(`mutation UnlockLockable\b`), httpmock.StringResponse(` { "data": { "unlockLockable": { "unlockedRecord": { "locked": false }}}}`)) }, wantOut: "✓ Unlocked: Issue OWNER/REPO#451 (traverse the library)\n", }, { name: "unlock issue nontty", state: Unlock, opts: LockOptions{ IssueNumber: 451, ParentCmd: "issue", }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "number": 451, "locked": true, "title": "traverse the library", "__typename": "Issue" }}}}`)) reg.Register( httpmock.GraphQL(`mutation UnlockLockable\b`), httpmock.StringResponse(` { "data": { "unlockLockable": { "unlockedRecord": { "locked": false }}}}`)) }, }, { name: "lock issue with explicit reason nontty", state: Lock, opts: LockOptions{ IssueNumber: 451, ParentCmd: "issue", Reason: "off_topic", }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "number": 451, "title": "traverse the library", "__typename": "Issue" }}}}`)) reg.Register( httpmock.GraphQL(`mutation LockLockable\b`), httpmock.StringResponse(` { "data": { "lockLockable": { "lockedRecord": { "locked": true }}}}`)) }, }, { name: "relock issue tty", state: Lock, opts: LockOptions{ IssueNumber: 451, ParentCmd: "issue", Reason: "off_topic", }, tty: true, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "number": 451, "locked": true, "title": "traverse the library", "__typename": "Issue" }}}}`)) reg.Register( httpmock.GraphQL(`mutation UnlockLockable\b`), httpmock.StringResponse(` { "data": { "unlockLockable": { "unlockedRecord": { "locked": false }}}}`)) reg.Register( httpmock.GraphQL(`mutation LockLockable\b`), httpmock.StringResponse(` { "data": { "lockLockable": { "lockedRecord": { "locked": true }}}}`)) }, promptStubs: func(t *testing.T, pm *prompter.PrompterMock) { pm.ConfirmFunc = func(p string, d bool) (bool, error) { if p == "Issue OWNER/REPO#451 already locked. Unlock and lock again as OFF_TOPIC?" { return true, nil } return false, prompter.NoSuchPromptErr(p) } }, wantOut: "✓ Locked as OFF_TOPIC: Issue OWNER/REPO#451 (traverse the library)\n", }, { name: "relock issue nontty", state: Lock, opts: LockOptions{ IssueNumber: 451, ParentCmd: "issue", Reason: "off_topic", }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "number": 451, "locked": true, "title": "traverse the library", "__typename": "Issue" }}}}`)) }, wantErr: "already locked", }, { name: "lock pr nontty", state: Lock, opts: LockOptions{ IssueNumber: 451, ParentCmd: "pr", }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "number": 451, "__typename": "PullRequest" }}}}`)) reg.Register( httpmock.GraphQL(`mutation LockLockable\b`), httpmock.StringResponse(` { "data": { "lockLockable": { "lockedRecord": { "locked": true }}}}`)) }, }, { name: "lock pr tty", tty: true, opts: LockOptions{ Interactive: true, IssueNumber: 451, ParentCmd: "pr", }, state: Lock, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "number": 451, "title": "traverse the library", "__typename": "PullRequest" }}}}`)) reg.Register( httpmock.GraphQL(`mutation LockLockable\b`), httpmock.StringResponse(` { "data": { "lockLockable": { "lockedRecord": { "locked": true }}}}`)) }, promptStubs: func(t *testing.T, pm *prompter.PrompterMock) { pm.SelectFunc = func(p, d string, opts []string) (int, error) { if p == "Lock reason?" { return prompter.IndexFor(opts, "Too heated") } return -1, prompter.NoSuchPromptErr(p) } }, wantOut: "✓ Locked as TOO_HEATED: Pull request OWNER/REPO#451 (traverse the library)\n", }, { name: "lock pr with explicit reason tty", tty: true, state: Lock, opts: LockOptions{ IssueNumber: 451, ParentCmd: "pr", Reason: "off_topic", }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "number": 451, "title": "traverse the library", "__typename": "PullRequest" }}}}`)) reg.Register( httpmock.GraphQL(`mutation LockLockable\b`), httpmock.StringResponse(` { "data": { "lockLockable": { "lockedRecord": { "locked": true }}}}`)) }, wantOut: "✓ Locked as OFF_TOPIC: Pull request OWNER/REPO#451 (traverse the library)\n", }, { name: "lock pr with explicit nontty", state: Lock, opts: LockOptions{ IssueNumber: 451, ParentCmd: "pr", Reason: "off_topic", }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "number": 451, "title": "traverse the library", "__typename": "PullRequest" }}}}`)) reg.Register( httpmock.GraphQL(`mutation LockLockable\b`), httpmock.StringResponse(` { "data": { "lockLockable": { "lockedRecord": { "locked": true }}}}`)) }, }, { name: "unlock pr tty", state: Unlock, opts: LockOptions{ IssueNumber: 451, ParentCmd: "pr", }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "number": 451, "locked": true, "title": "traverse the library", "__typename": "PullRequest" }}}}`)) reg.Register( httpmock.GraphQL(`mutation UnlockLockable\b`), httpmock.StringResponse(` { "data": { "unlockLockable": { "unlockedRecord": { "locked": false }}}}`)) }, }, { name: "unlock pr nontty", tty: true, state: Unlock, opts: LockOptions{ IssueNumber: 451, ParentCmd: "pr", }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "number": 451, "locked": true, "title": "traverse the library", "__typename": "PullRequest" }}}}`)) reg.Register( httpmock.GraphQL(`mutation UnlockLockable\b`), httpmock.StringResponse(` { "data": { "unlockLockable": { "unlockedRecord": { "locked": false }}}}`)) }, wantOut: "✓ Unlocked: Pull request OWNER/REPO#451 (traverse the library)\n", }, { name: "relock pr tty", state: Lock, opts: LockOptions{ IssueNumber: 451, ParentCmd: "pr", Reason: "off_topic", }, tty: true, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "number": 451, "locked": true, "title": "traverse the library", "__typename": "PullRequest" }}}}`)) reg.Register( httpmock.GraphQL(`mutation UnlockLockable\b`), httpmock.StringResponse(` { "data": { "unlockLockable": { "unlockedRecord": { "locked": false }}}}`)) reg.Register( httpmock.GraphQL(`mutation LockLockable\b`), httpmock.StringResponse(` { "data": { "lockLockable": { "lockedRecord": { "locked": true }}}}`)) }, promptStubs: func(t *testing.T, pm *prompter.PrompterMock) { pm.ConfirmFunc = func(p string, d bool) (bool, error) { if p == "Pull request OWNER/REPO#451 already locked. Unlock and lock again as OFF_TOPIC?" { return true, nil } return false, prompter.NoSuchPromptErr(p) } }, wantOut: "✓ Locked as OFF_TOPIC: Pull request OWNER/REPO#451 (traverse the library)\n", }, { name: "relock pr nontty", state: Lock, opts: LockOptions{ IssueNumber: 451, ParentCmd: "pr", Reason: "off_topic", }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(` { "data": { "repository": { "hasIssuesEnabled": true, "issue": { "number": 451, "locked": true, "title": "traverse the library", "__typename": "PullRequest" }}}}`)) }, wantErr: "already locked", }, } for _, tt := range cases { t.Run(tt.name, func(t *testing.T) { reg := &httpmock.Registry{} defer reg.Verify(t) if tt.httpStubs != nil { tt.httpStubs(t, reg) } pm := &prompter.PrompterMock{} if tt.promptStubs != nil { tt.promptStubs(t, pm) } ios, _, stdout, stderr := iostreams.Test() ios.SetStdoutTTY(tt.tty) ios.SetStdinTTY(tt.tty) ios.SetStderrTTY(tt.tty) tt.opts.Prompter = pm 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 } err := lockRun(tt.state, &tt.opts) output := &test.CmdOut{ OutBuf: stdout, ErrBuf: stderr, } if tt.wantErr != "" { assert.EqualError(t, err, tt.wantErr) } else { assert.NoError(t, err) assert.Equal(t, tt.wantOut, output.String()) assert.Equal(t, tt.wantErrOut, output.Stderr()) } }) } } func TestReasons(t *testing.T) { assert.Equal(t, len(reasons), len(reasonsApi)) for _, reason := range reasons { assert.Equal(t, strings.ToUpper(reason), string(*reasonsMap[reason])) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/issue/shared/display.go
pkg/cmd/issue/shared/display.go
package shared import ( "fmt" "strconv" "strings" "time" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/tableprinter" "github.com/cli/cli/v2/internal/text" prShared "github.com/cli/cli/v2/pkg/cmd/pr/shared" "github.com/cli/cli/v2/pkg/iostreams" ) func PrintIssues(io *iostreams.IOStreams, now time.Time, prefix string, totalCount int, issues []api.Issue) { cs := io.ColorScheme() isTTY := io.IsStdoutTTY() headers := []string{"ID"} if !isTTY { headers = append(headers, "STATE") } headers = append(headers, "TITLE", "LABELS", "UPDATED", ) table := tableprinter.New(io, tableprinter.WithHeader(headers...)) for _, issue := range issues { issueNum := strconv.Itoa(issue.Number) if isTTY { issueNum = "#" + issueNum } issueNum = prefix + issueNum table.AddField(issueNum, tableprinter.WithColor(cs.ColorFromString(prShared.ColorForIssueState(issue)))) if !isTTY { table.AddField(issue.State) } table.AddField(text.RemoveExcessiveWhitespace(issue.Title)) table.AddField(issueLabelList(&issue, cs, isTTY)) table.AddTimeField(now, issue.UpdatedAt, cs.Muted) table.EndRow() } _ = table.Render() remaining := totalCount - len(issues) if remaining > 0 { fmt.Fprintf(io.Out, cs.Muted("%sAnd %d more\n"), prefix, remaining) } } func issueLabelList(issue *api.Issue, cs *iostreams.ColorScheme, colorize bool) string { if len(issue.Labels.Nodes) == 0 { return "" } labelNames := make([]string, 0, len(issue.Labels.Nodes)) for _, label := range issue.Labels.Nodes { if colorize { labelNames = append(labelNames, cs.Label(label.Color, label.Name)) } else { labelNames = append(labelNames, label.Name) } } return strings.Join(labelNames, ", ") }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/issue/shared/lookup_test.go
pkg/cmd/issue/shared/lookup_test.go
package shared import ( "net/http" "testing" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/httpmock" o "github.com/cli/cli/v2/pkg/option" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestParseIssuesFromArgs(t *testing.T) { tests := []struct { behavior string args []string expectedIssueNumbers []int expectedRepo o.Option[ghrepo.Interface] expectedErr bool }{ { behavior: "when given issue numbers, returns them with no repo", args: []string{"1", "2"}, expectedIssueNumbers: []int{1, 2}, expectedRepo: o.None[ghrepo.Interface](), }, { behavior: "when given # prefixed issue numbers, returns them with no repo", args: []string{"#1", "#2"}, expectedIssueNumbers: []int{1, 2}, expectedRepo: o.None[ghrepo.Interface](), }, { behavior: "when given URLs, returns them with the repo", args: []string{ "https://github.com/OWNER/REPO/issues/1", "https://github.com/OWNER/REPO/issues/2", }, expectedIssueNumbers: []int{1, 2}, expectedRepo: o.Some(ghrepo.New("OWNER", "REPO")), }, { behavior: "when given URLs in different repos, errors", args: []string{ "https://github.com/OWNER/REPO/issues/1", "https://github.com/OWNER/OTHERREPO/issues/2", }, expectedErr: true, }, { behavior: "when given an unparseable argument, errors", args: []string{"://"}, expectedErr: true, }, { behavior: "when given a URL that isn't an issue or PR url, errors", args: []string{"https://github.com"}, expectedErr: true, }, } for _, tc := range tests { t.Run(tc.behavior, func(t *testing.T) { issueNumbers, repo, err := ParseIssuesFromArgs(tc.args) if tc.expectedErr { require.Error(t, err) return } require.NoError(t, err) assert.Equal(t, tc.expectedIssueNumbers, issueNumbers) assert.Equal(t, tc.expectedRepo, repo) }) } } func TestFindIssuesOrPRs(t *testing.T) { tests := []struct { name string issueNumbers []int baseRepo ghrepo.Interface httpStub func(*httpmock.Registry) wantIssueNumbers []int wantErr bool }{ { name: "multiple issues", issueNumbers: []int{1, 2}, baseRepo: ghrepo.New("OWNER", "REPO"), httpStub: func(r *httpmock.Registry) { r.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(`{"data":{"repository":{ "hasIssuesEnabled": true, "issue":{"number":1} }}}`)) r.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(`{"data":{"repository":{ "hasIssuesEnabled": true, "issue":{"number":2} }}}`)) }, wantIssueNumbers: []int{1, 2}, }, { name: "any find error results in total error", issueNumbers: []int{1, 2}, baseRepo: ghrepo.New("OWNER", "REPO"), httpStub: func(r *httpmock.Registry) { r.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StringResponse(`{"data":{"repository":{ "hasIssuesEnabled": true, "issue":{"number":1} }}}`)) r.Register( httpmock.GraphQL(`query IssueByNumber\b`), httpmock.StatusStringResponse(500, "internal server error")) }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { reg := &httpmock.Registry{} if tt.httpStub != nil { tt.httpStub(reg) } httpClient := &http.Client{Transport: reg} issues, err := FindIssuesOrPRs(httpClient, tt.baseRepo, tt.issueNumbers, []string{"number"}) if (err != nil) != tt.wantErr { t.Errorf("FindIssuesOrPRs() error = %v, wantErr %v", err, tt.wantErr) if issues == nil { return } } if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) for i := range issues { assert.Contains(t, tt.wantIssueNumbers, issues[i].Number) } }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/issue/shared/lookup.go
pkg/cmd/issue/shared/lookup.go
package shared import ( "errors" "fmt" "net/http" "net/url" "regexp" "strconv" "strings" "time" "github.com/cli/cli/v2/api" fd "github.com/cli/cli/v2/internal/featuredetection" "github.com/cli/cli/v2/internal/ghrepo" o "github.com/cli/cli/v2/pkg/option" "github.com/cli/cli/v2/pkg/set" "golang.org/x/sync/errgroup" ) var issueURLRE = regexp.MustCompile(`^/([^/]+)/([^/]+)/(?:issues|pull)/(\d+)`) func ParseIssuesFromArgs(args []string) ([]int, o.Option[ghrepo.Interface], error) { var repo o.Option[ghrepo.Interface] issueNumbers := make([]int, len(args)) for i, arg := range args { // For each argument, parse the issue number and an optional repo issueNumber, issueRepo, err := ParseIssueFromArg(arg) if err != nil { return nil, o.None[ghrepo.Interface](), err } // if this is our first issue repo found, then we need to set it if repo.IsNone() { repo = issueRepo } // if there is an issue repo returned, then we need to check if it is the same as the previous one if issueRepo.IsSome() && repo.IsSome() { // Unwraps are safe because we've checked for presence above if !ghrepo.IsSame(repo.Unwrap(), issueRepo.Unwrap()) { return nil, o.None[ghrepo.Interface](), fmt.Errorf( "multiple issues must be in same repo: found %q, expected %q", ghrepo.FullName(issueRepo.Unwrap()), ghrepo.FullName(repo.Unwrap()), ) } } // add the issue number to the list issueNumbers[i] = issueNumber } return issueNumbers, repo, nil } func ParseIssueFromArg(arg string) (int, o.Option[ghrepo.Interface], error) { issueLocator := tryParseIssueFromURL(arg) if issueLocator, present := issueLocator.Value(); present { return issueLocator.issueNumber, o.Some(issueLocator.repo), nil } issueNumber, err := strconv.Atoi(strings.TrimPrefix(arg, "#")) if err != nil { return 0, o.None[ghrepo.Interface](), fmt.Errorf("invalid issue format: %q", arg) } return issueNumber, o.None[ghrepo.Interface](), nil } type issueLocator struct { issueNumber int repo ghrepo.Interface } // tryParseIssueFromURL tries to parse an issue number and repo from a URL. func tryParseIssueFromURL(maybeURL string) o.Option[issueLocator] { u, err := url.Parse(maybeURL) if err != nil { return o.None[issueLocator]() } if u.Scheme != "https" && u.Scheme != "http" { return o.None[issueLocator]() } m := issueURLRE.FindStringSubmatch(u.Path) if m == nil { return o.None[issueLocator]() } repo := ghrepo.NewWithHost(m[1], m[2], u.Hostname()) issueNumber, _ := strconv.Atoi(m[3]) return o.Some(issueLocator{ issueNumber: issueNumber, repo: repo, }) } type PartialLoadError struct { error } // FindIssuesOrPRs loads 1 or more issues or pull requests with the specified fields. If some of the fields // could not be fetched by GraphQL, this returns non-nil issues and a *PartialLoadError. func FindIssuesOrPRs(httpClient *http.Client, repo ghrepo.Interface, issueNumbers []int, fields []string) ([]*api.Issue, error) { issuesChan := make(chan *api.Issue, len(issueNumbers)) g := errgroup.Group{} for _, num := range issueNumbers { issueNumber := num g.Go(func() error { issue, err := FindIssueOrPR(httpClient, repo, issueNumber, fields) if err != nil { return err } issuesChan <- issue return nil }) } err := g.Wait() close(issuesChan) if err != nil { return nil, err } issues := make([]*api.Issue, 0, len(issueNumbers)) for issue := range issuesChan { issues = append(issues, issue) } return issues, nil } func FindIssueOrPR(httpClient *http.Client, repo ghrepo.Interface, number int, fields []string) (*api.Issue, error) { fieldSet := set.NewStringSet() fieldSet.AddValues(fields) if fieldSet.Contains("stateReason") { cachedClient := api.NewCachedHTTPClient(httpClient, time.Hour*24) detector := fd.NewDetector(cachedClient, repo.RepoHost()) features, err := detector.IssueFeatures() if err != nil { return nil, err } if !features.StateReason { fieldSet.Remove("stateReason") } } var getProjectItems bool if fieldSet.Contains("projectItems") { getProjectItems = true fieldSet.Remove("projectItems") fieldSet.Add("number") } fields = fieldSet.ToSlice() type response struct { Repository struct { HasIssuesEnabled bool Issue *api.Issue } } query := fmt.Sprintf(` query IssueByNumber($owner: String!, $repo: String!, $number: Int!) { repository(owner: $owner, name: $repo) { hasIssuesEnabled issue: issueOrPullRequest(number: $number) { __typename ...on Issue{%[1]s} ...on PullRequest{%[2]s} } } }`, api.IssueGraphQL(fields), api.PullRequestGraphQL(fields)) variables := map[string]interface{}{ "owner": repo.RepoOwner(), "repo": repo.RepoName(), "number": number, } var resp response client := api.NewClientFromHTTP(httpClient) if err := client.GraphQL(repo.RepoHost(), query, variables, &resp); err != nil { var gerr api.GraphQLError if errors.As(err, &gerr) { if gerr.Match("NOT_FOUND", "repository.issue") && !resp.Repository.HasIssuesEnabled { return nil, fmt.Errorf("the '%s' repository has disabled issues", ghrepo.FullName(repo)) } else if gerr.Match("FORBIDDEN", "repository.issue.projectCards.") { issue := resp.Repository.Issue // remove nil entries for project cards due to permission issues projects := make([]*api.ProjectInfo, 0, len(issue.ProjectCards.Nodes)) for _, p := range issue.ProjectCards.Nodes { if p != nil { projects = append(projects, p) } } issue.ProjectCards.Nodes = projects return issue, &PartialLoadError{err} } } return nil, err } if resp.Repository.Issue == nil { return nil, errors.New("issue was not found but GraphQL reported no error") } if getProjectItems { apiClient := api.NewClientFromHTTP(httpClient) err := api.ProjectsV2ItemsForIssue(apiClient, repo, resp.Repository.Issue) if err != nil && !api.ProjectsV2IgnorableError(err) { return nil, err } } return resp.Repository.Issue, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/run/run.go
pkg/cmd/run/run.go
package run import ( cmdCancel "github.com/cli/cli/v2/pkg/cmd/run/cancel" cmdDelete "github.com/cli/cli/v2/pkg/cmd/run/delete" cmdDownload "github.com/cli/cli/v2/pkg/cmd/run/download" cmdList "github.com/cli/cli/v2/pkg/cmd/run/list" cmdRerun "github.com/cli/cli/v2/pkg/cmd/run/rerun" cmdView "github.com/cli/cli/v2/pkg/cmd/run/view" cmdWatch "github.com/cli/cli/v2/pkg/cmd/run/watch" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/spf13/cobra" ) func NewCmdRun(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "run <command>", Short: "View details about workflow runs", Long: "List, view, and watch recent workflow runs from GitHub Actions.", GroupID: "actions", } cmdutil.EnableRepoOverride(cmd, f) cmd.AddCommand(cmdList.NewCmdList(f, nil)) cmd.AddCommand(cmdView.NewCmdView(f, nil)) cmd.AddCommand(cmdRerun.NewCmdRerun(f, nil)) cmd.AddCommand(cmdDownload.NewCmdDownload(f, nil)) cmd.AddCommand(cmdWatch.NewCmdWatch(f, nil)) cmd.AddCommand(cmdCancel.NewCmdCancel(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/run/delete/delete.go
pkg/cmd/run/delete/delete.go
package delete import ( "errors" "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/internal/prompter" "github.com/cli/cli/v2/pkg/cmd/run/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) const ( defaultRunGetLimit = 10 ) type DeleteOptions struct { HttpClient func() (*http.Client, error) IO *iostreams.IOStreams BaseRepo func() (ghrepo.Interface, error) Prompter prompter.Prompter Prompt bool RunID string } func NewCmdDelete(f *cmdutil.Factory, runF func(*DeleteOptions) error) *cobra.Command { opts := &DeleteOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, Prompter: f.Prompter, } cmd := &cobra.Command{ Use: "delete [<run-id>]", Short: "Delete a workflow run", Example: heredoc.Doc(` # Interactively select a run to delete $ gh run delete # Delete a specific run $ gh run delete 12345 `), 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.RunID = args[0] } else if !opts.IO.CanPrompt() { return cmdutil.FlagErrorf("run ID required when not running interactively") } else { opts.Prompt = true } if runF != nil { return runF(opts) } return runDelete(opts) }, } return cmd } func runDelete(opts *DeleteOptions) error { httpClient, err := opts.HttpClient() if err != nil { return fmt.Errorf("failed to create http client: %w", err) } client := api.NewClientFromHTTP(httpClient) cs := opts.IO.ColorScheme() repo, err := opts.BaseRepo() if err != nil { return fmt.Errorf("failed to determine base repo: %w", err) } runID := opts.RunID var run *shared.Run if opts.Prompt { payload, err := shared.GetRuns(client, repo, nil, defaultRunGetLimit) if err != nil { return fmt.Errorf("failed to get runs: %w", err) } runs := payload.WorkflowRuns if len(runs) == 0 { return fmt.Errorf("found no runs to delete") } runID, err = shared.SelectRun(opts.Prompter, cs, runs) if err != nil { return err } for _, r := range runs { if fmt.Sprintf("%d", r.ID) == runID { run = &r break } } } else { run, err = shared.GetRun(client, repo, runID, 0) if err != nil { var httpErr api.HTTPError if errors.As(err, &httpErr) { if httpErr.StatusCode == http.StatusNotFound { err = fmt.Errorf("could not find any workflow run with ID %s", opts.RunID) } } return err } } err = deleteWorkflowRun(client, repo, fmt.Sprintf("%d", run.ID)) if err != nil { var httpErr api.HTTPError if errors.As(err, &httpErr) { if httpErr.StatusCode == http.StatusConflict { err = fmt.Errorf("cannot delete a workflow run that is completed") } } return err } fmt.Fprintf(opts.IO.Out, "%s Request to delete workflow run submitted.\n", cs.SuccessIcon()) return nil } func deleteWorkflowRun(client *api.Client, repo ghrepo.Interface, runID string) error { path := fmt.Sprintf("repos/%s/actions/runs/%s", ghrepo.FullName(repo), runID) err := client.REST(repo.RepoHost(), "DELETE", path, nil, nil) 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/run/delete/delete_test.go
pkg/cmd/run/delete/delete_test.go
package delete import ( "bytes" "fmt" "io" "net/http" "testing" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/pkg/cmd/run/shared" workflowShared "github.com/cli/cli/v2/pkg/cmd/workflow/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 tty bool wants DeleteOptions wantsErr bool prompterStubs func(*prompter.PrompterMock) }{ { name: "blank tty", tty: true, wants: DeleteOptions{ Prompt: true, }, }, { name: "blank nontty", wantsErr: true, }, { name: "with arg", cli: "1234", wants: DeleteOptions{ RunID: "1234", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() ios.SetStdinTTY(tt.tty) ios.SetStdoutTTY(tt.tty) f := &cmdutil.Factory{ IOStreams: ios, } argv, err := shlex.Split(tt.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(io.Discard) cmd.SetErr(io.Discard) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) return } assert.NoError(t, err) assert.Equal(t, tt.wants.RunID, gotOpts.RunID) }) } } func TestRunDelete(t *testing.T) { tests := []struct { name string opts *DeleteOptions httpStubs func(*httpmock.Registry) prompterStubs func(*prompter.PrompterMock) wantErr bool wantOut string errMsg string }{ { name: "delete run", opts: &DeleteOptions{ RunID: "1234", }, wantErr: false, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234"), httpmock.JSONResponse(shared.SuccessfulRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) reg.Register( httpmock.REST("DELETE", fmt.Sprintf("repos/OWNER/REPO/actions/runs/%d", shared.SuccessfulRun.ID)), httpmock.StatusStringResponse(204, "")) }, wantOut: "✓ Request to delete workflow run submitted.\n", }, { name: "not found", opts: &DeleteOptions{ RunID: "1234", }, wantErr: true, errMsg: "could not find any workflow run with ID 1234", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234"), httpmock.StatusStringResponse(404, "")) }, }, { name: "prompt", opts: &DeleteOptions{ Prompt: true, }, prompterStubs: func(pm *prompter.PrompterMock) { pm.SelectFunc = func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "✓ cool commit, CI [trunk] Feb 23, 2021") } }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"), httpmock.JSONResponse(shared.RunsPayload{ TotalCount: 0, WorkflowRuns: []shared.Run{shared.SuccessfulRun}, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse( workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{shared.TestWorkflow}, }, )) reg.Register( httpmock.REST("DELETE", fmt.Sprintf("repos/OWNER/REPO/actions/runs/%d", shared.SuccessfulRun.ID)), httpmock.StatusStringResponse(204, "")) }, wantOut: "✓ Request to delete workflow run submitted.\n", }, } for _, tt := range tests { tt.opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.FromFullName("OWNER/REPO") } // mock http reg := &httpmock.Registry{} tt.httpStubs(reg) tt.opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } // mock IO ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) ios.SetStdinTTY(true) tt.opts.IO = ios // mock prompter pm := &prompter.PrompterMock{} if tt.prompterStubs != nil { tt.prompterStubs(pm) } tt.opts.Prompter = pm // execute test t.Run(tt.name, func(t *testing.T) { err := runDelete(tt.opts) if tt.wantErr { assert.Error(t, err) if tt.errMsg != "" { assert.Equal(t, tt.errMsg, err.Error()) } } else { assert.NoError(t, err) } assert.Equal(t, tt.wantOut, stdout.String()) reg.Verify(t) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/run/cancel/cancel_test.go
pkg/cmd/run/cancel/cancel_test.go
package cancel import ( "bytes" "io" "net/http" "testing" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/pkg/cmd/run/shared" workflowShared "github.com/cli/cli/v2/pkg/cmd/workflow/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 TestNewCmdCancel(t *testing.T) { tests := []struct { name string cli string tty bool wants CancelOptions wantsErr bool }{ { name: "blank tty", tty: true, wants: CancelOptions{ Prompt: true, }, }, { name: "blank nontty", wantsErr: true, }, { name: "with arg", cli: "1234", wants: CancelOptions{ RunID: "1234", Force: false, }, }, { name: "with arg and force flag", cli: "1234 --force", wants: CancelOptions{ RunID: "1234", Force: true, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() ios.SetStdinTTY(tt.tty) ios.SetStdoutTTY(tt.tty) f := &cmdutil.Factory{ IOStreams: ios, } argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts *CancelOptions cmd := NewCmdCancel(f, func(opts *CancelOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(io.Discard) cmd.SetErr(io.Discard) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) return } assert.NoError(t, err) assert.Equal(t, tt.wants.RunID, gotOpts.RunID) assert.Equal(t, tt.wants.Force, gotOpts.Force) }) } } func TestRunCancel(t *testing.T) { inProgressRun := shared.TestRun(1234, shared.InProgress, "") completedRun := shared.TestRun(4567, shared.Completed, shared.Failure) tests := []struct { name string httpStubs func(*httpmock.Registry) promptStubs func(*prompter.MockPrompter) opts *CancelOptions wantErr bool wantOut string errMsg string }{ { name: "cancel run", opts: &CancelOptions{ RunID: "1234", }, wantErr: false, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234"), httpmock.JSONResponse(inProgressRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/actions/runs/1234/cancel"), httpmock.StatusStringResponse(202, "{}")) }, wantOut: "✓ Request to cancel workflow 1234 submitted.\n", }, { name: "not found", opts: &CancelOptions{ RunID: "1234", }, wantErr: true, errMsg: "Could not find any workflow run with ID 1234", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234"), httpmock.StatusStringResponse(404, "")) }, }, { name: "completed", opts: &CancelOptions{ RunID: "4567", }, wantErr: true, errMsg: "Cannot cancel a workflow run that is completed", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/4567"), httpmock.JSONResponse(completedRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/actions/runs/4567/cancel"), httpmock.StatusStringResponse(409, ""), ) }, }, { name: "prompt, no in progress runs", opts: &CancelOptions{ Prompt: true, }, wantErr: true, errMsg: "found no in progress runs to cancel", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"), httpmock.JSONResponse(shared.RunsPayload{ WorkflowRuns: []shared.Run{ completedRun, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ shared.TestWorkflow, }, })) }, }, { name: "prompt, cancel", opts: &CancelOptions{ Prompt: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"), httpmock.JSONResponse(shared.RunsPayload{ WorkflowRuns: []shared.Run{ inProgressRun, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ shared.TestWorkflow, }, })) reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/actions/runs/1234/cancel"), httpmock.StatusStringResponse(202, "{}")) }, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterSelect("Select a workflow run", []string{"* cool commit, CI [trunk] Feb 23, 2021"}, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "* cool commit, CI [trunk] Feb 23, 2021") }) }, wantOut: "✓ Request to cancel workflow 1234 submitted.\n", }, { name: "invalid run-id", opts: &CancelOptions{ RunID: "12\n34", }, httpStubs: func(reg *httpmock.Registry) { }, wantErr: true, errMsg: "invalid run-id \"12\\n34\"", }, { name: "force cancel run", opts: &CancelOptions{ RunID: "1234", Force: true, }, wantErr: false, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234"), httpmock.JSONResponse(inProgressRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/actions/runs/1234/force-cancel"), httpmock.StatusStringResponse(202, "{}")) }, wantOut: "✓ Request to force cancel workflow 1234 submitted.\n", }, { name: "force and completed", opts: &CancelOptions{ RunID: "4567", Force: true, }, wantErr: true, errMsg: "Cannot cancel a workflow run that is completed", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/4567"), httpmock.JSONResponse(completedRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/actions/runs/4567/force-cancel"), httpmock.StatusStringResponse(409, ""), ) }, }, } for _, tt := range tests { reg := &httpmock.Registry{} tt.httpStubs(reg) tt.opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) ios.SetStdinTTY(true) tt.opts.IO = ios tt.opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.FromFullName("OWNER/REPO") } pm := prompter.NewMockPrompter(t) tt.opts.Prompter = pm if tt.promptStubs != nil { tt.promptStubs(pm) } t.Run(tt.name, func(t *testing.T) { err := runCancel(tt.opts) if tt.wantErr { assert.Error(t, err) if tt.errMsg != "" { assert.Equal(t, tt.errMsg, err.Error()) } } else { assert.NoError(t, err) } assert.Equal(t, tt.wantOut, stdout.String()) reg.Verify(t) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/run/cancel/cancel.go
pkg/cmd/run/cancel/cancel.go
package cancel import ( "errors" "fmt" "net/http" "strconv" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/run/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type CancelOptions struct { HttpClient func() (*http.Client, error) IO *iostreams.IOStreams BaseRepo func() (ghrepo.Interface, error) Prompter shared.Prompter Prompt bool RunID string Force bool } func NewCmdCancel(f *cmdutil.Factory, runF func(*CancelOptions) error) *cobra.Command { opts := &CancelOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, Prompter: f.Prompter, } cmd := &cobra.Command{ Use: "cancel [<run-id>]", Short: "Cancel a workflow run", 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.RunID = args[0] } else if !opts.IO.CanPrompt() { return cmdutil.FlagErrorf("run ID required when not running interactively") } else { opts.Prompt = true } if runF != nil { return runF(opts) } return runCancel(opts) }, } cmd.Flags().BoolVar(&opts.Force, "force", false, "Force cancel a workflow run") return cmd } func runCancel(opts *CancelOptions) error { if opts.RunID != "" { _, err := strconv.Atoi(opts.RunID) if err != nil { return fmt.Errorf("invalid run-id %#v", opts.RunID) } } httpClient, err := opts.HttpClient() if err != nil { return fmt.Errorf("failed to create http client: %w", err) } client := api.NewClientFromHTTP(httpClient) cs := opts.IO.ColorScheme() repo, err := opts.BaseRepo() if err != nil { return fmt.Errorf("failed to determine base repo: %w", err) } runID := opts.RunID var run *shared.Run if opts.Prompt { runs, err := shared.GetRunsWithFilter(client, repo, nil, 10, func(run shared.Run) bool { return run.Status != shared.Completed }) if err != nil { return fmt.Errorf("failed to get runs: %w", err) } if len(runs) == 0 { return fmt.Errorf("found no in progress runs to cancel") } if runID, err = shared.SelectRun(opts.Prompter, cs, runs); err != nil { return err } // TODO silly stopgap until dust settles and SelectRun can just return a run for _, r := range runs { if fmt.Sprintf("%d", r.ID) == runID { run = &r break } } } else { run, err = shared.GetRun(client, repo, runID, 0) if err != nil { var httpErr api.HTTPError if errors.As(err, &httpErr) { if httpErr.StatusCode == http.StatusNotFound { err = fmt.Errorf("Could not find any workflow run with ID %s", opts.RunID) } } return err } } force := opts.Force err = cancelWorkflowRun(client, repo, fmt.Sprintf("%d", run.ID), force) if err != nil { var httpErr api.HTTPError if errors.As(err, &httpErr) { if httpErr.StatusCode == http.StatusConflict { err = fmt.Errorf("Cannot cancel a workflow run that is completed") } } return err } if force { fmt.Fprintf(opts.IO.Out, "%s Request to force cancel workflow %s submitted.\n", cs.SuccessIcon(), runID) } else { fmt.Fprintf(opts.IO.Out, "%s Request to cancel workflow %s submitted.\n", cs.SuccessIcon(), runID) } return nil } func cancelWorkflowRun(client *api.Client, repo ghrepo.Interface, runID string, force bool) error { var path string if force { path = fmt.Sprintf("repos/%s/actions/runs/%s/force-cancel", ghrepo.FullName(repo), runID) } else { path = fmt.Sprintf("repos/%s/actions/runs/%s/cancel", ghrepo.FullName(repo), runID) } err := client.REST(repo.RepoHost(), "POST", path, nil, nil) 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/run/rerun/rerun_test.go
pkg/cmd/run/rerun/rerun_test.go
package rerun import ( "bytes" "encoding/json" "io" "net/http" "testing" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/pkg/cmd/run/shared" workflowShared "github.com/cli/cli/v2/pkg/cmd/workflow/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/go-gh/v2/pkg/api" "github.com/google/shlex" "github.com/stretchr/testify/assert" ) func TestNewCmdRerun(t *testing.T) { tests := []struct { name string cli string tty bool wants RerunOptions wantsErr bool }{ { name: "blank nontty", wantsErr: true, }, { name: "blank tty", tty: true, wants: RerunOptions{ Prompt: true, }, }, { name: "with arg nontty", cli: "1234", wants: RerunOptions{ RunID: "1234", }, }, { name: "with arg tty", tty: true, cli: "1234", wants: RerunOptions{ RunID: "1234", }, }, { name: "failed arg nontty", cli: "4321 --failed", wants: RerunOptions{ RunID: "4321", OnlyFailed: true, }, }, { name: "failed arg", tty: true, cli: "--failed", wants: RerunOptions{ Prompt: true, OnlyFailed: true, }, }, { name: "with arg job", tty: true, cli: "--job 1234", wants: RerunOptions{ JobID: "1234", }, }, { name: "with args jobID and runID uses jobID", tty: true, cli: "1234 --job 5678", wants: RerunOptions{ JobID: "5678", RunID: "", }, }, { name: "with arg job with no ID fails", tty: true, cli: "--job", wantsErr: true, }, { name: "with arg job with no ID no tty fails", cli: "--job", wantsErr: true, }, { name: "debug nontty", cli: "4321 --debug", wants: RerunOptions{ RunID: "4321", Debug: true, }, }, { name: "debug tty", tty: true, cli: "--debug", wants: RerunOptions{ Prompt: true, Debug: true, }, }, { name: "debug off", cli: "4321 --debug=false", wants: RerunOptions{ RunID: "4321", Debug: false, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() ios.SetStdinTTY(tt.tty) ios.SetStdoutTTY(tt.tty) f := &cmdutil.Factory{ IOStreams: ios, } argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts *RerunOptions cmd := NewCmdRerun(f, func(opts *RerunOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(io.Discard) cmd.SetErr(io.Discard) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) return } assert.NoError(t, err) assert.Equal(t, tt.wants.RunID, gotOpts.RunID) assert.Equal(t, tt.wants.Prompt, gotOpts.Prompt) }) } } func TestRerun(t *testing.T) { tests := []struct { name string httpStubs func(*httpmock.Registry) promptStubs func(*prompter.MockPrompter) opts *RerunOptions tty bool wantErr bool errOut string wantOut string wantDebug bool }{ { name: "arg", tty: true, opts: &RerunOptions{ RunID: "1234", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234"), httpmock.JSONResponse(shared.FailedRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ shared.TestWorkflow, }, })) reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/actions/runs/1234/rerun"), httpmock.StringResponse("{}")) }, wantOut: "✓ Requested rerun of run 1234\n", }, { name: "arg including onlyFailed", tty: true, opts: &RerunOptions{ RunID: "1234", OnlyFailed: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234"), httpmock.JSONResponse(shared.FailedRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ shared.TestWorkflow, }, })) reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/actions/runs/1234/rerun-failed-jobs"), httpmock.StringResponse("{}")) }, wantOut: "✓ Requested rerun (failed jobs) of run 1234\n", }, { name: "arg including a specific job", tty: true, opts: &RerunOptions{ JobID: "20", // 20 is shared.FailedJob.ID }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/jobs/20"), httpmock.JSONResponse(shared.FailedJob)) reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/actions/jobs/20/rerun"), httpmock.StringResponse("{}")) }, wantOut: "✓ Requested rerun of job 20 on run 1234\n", }, { name: "arg including debug", tty: true, opts: &RerunOptions{ RunID: "1234", Debug: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234"), httpmock.JSONResponse(shared.FailedRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ shared.TestWorkflow, }, })) reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/actions/runs/1234/rerun"), httpmock.StringResponse("{}")) }, wantOut: "✓ Requested rerun of run 1234 with debug logging enabled\n", wantDebug: true, }, { name: "arg including onlyFailed and debug", tty: true, opts: &RerunOptions{ RunID: "1234", OnlyFailed: true, Debug: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234"), httpmock.JSONResponse(shared.FailedRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ shared.TestWorkflow, }, })) reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/actions/runs/1234/rerun-failed-jobs"), httpmock.StringResponse("{}")) }, wantOut: "✓ Requested rerun (failed jobs) of run 1234 with debug logging enabled\n", wantDebug: true, }, { name: "arg including a specific job and debug", tty: true, opts: &RerunOptions{ JobID: "20", // 20 is shared.FailedJob.ID Debug: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/jobs/20"), httpmock.JSONResponse(shared.FailedJob)) reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/actions/jobs/20/rerun"), httpmock.StringResponse("{}")) }, wantOut: "✓ Requested rerun of job 20 on run 1234 with debug logging enabled\n", wantDebug: true, }, { name: "prompt", tty: true, opts: &RerunOptions{ Prompt: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"), httpmock.JSONResponse(shared.RunsPayload{ WorkflowRuns: shared.TestRuns, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234"), httpmock.JSONResponse(shared.FailedRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ shared.TestWorkflow, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ shared.TestWorkflow, }, })) reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/actions/runs/1234/rerun"), httpmock.StringResponse("{}")) }, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterSelect("Select a workflow run", []string{"X cool commit, CI [trunk] Feb 23, 2021", "X cool commit, CI [trunk] Feb 23, 2021", "X cool commit, CI [trunk] Feb 23, 2021", "- cool commit, CI [trunk] Feb 23, 2021", "- cool commit, CI [trunk] Feb 23, 2021", "X cool commit, CI [trunk] Feb 23, 2021"}, func(_, _ string, opts []string) (int, error) { return 2, nil }) }, wantOut: "✓ Requested rerun of run 1234\n", }, { name: "prompt but no failed runs", tty: true, opts: &RerunOptions{ Prompt: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"), httpmock.JSONResponse(shared.RunsPayload{ WorkflowRuns: []shared.Run{ shared.SuccessfulRun, shared.TestRun(2, shared.InProgress, ""), }})) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ shared.TestWorkflow, }, })) }, wantErr: true, errOut: "no recent runs have failed; please specify a specific `<run-id>`", }, { name: "API error (403)", tty: true, opts: &RerunOptions{ RunID: "3", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3"), httpmock.JSONResponse(shared.SuccessfulRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ shared.TestWorkflow, }, })) reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/actions/runs/3/rerun"), httpmock.JSONErrorResponse(403, api.HTTPError{ StatusCode: 403, Message: "blah blah", }), ) }, wantErr: true, errOut: "run 3 cannot be rerun; blah blah", }, { name: "API error (non-403)", tty: true, opts: &RerunOptions{ RunID: "3", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3"), httpmock.JSONResponse(shared.SuccessfulRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ shared.TestWorkflow, }, })) reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/actions/runs/3/rerun"), httpmock.JSONErrorResponse(500, api.HTTPError{ StatusCode: 500, Message: "blah blah", }), ) }, wantErr: true, errOut: "failed to rerun: HTTP 500: blah blah (https://api.github.com/repos/OWNER/REPO/actions/runs/3/rerun)", }, } for _, tt := range tests { reg := &httpmock.Registry{} tt.httpStubs(reg) tt.opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } ios, _, stdout, _ := iostreams.Test() ios.SetStdinTTY(tt.tty) ios.SetStdoutTTY(tt.tty) tt.opts.IO = ios tt.opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.FromFullName("OWNER/REPO") } pm := prompter.NewMockPrompter(t) tt.opts.Prompter = pm if tt.promptStubs != nil { tt.promptStubs(pm) } t.Run(tt.name, func(t *testing.T) { err := runRerun(tt.opts) if tt.wantErr { assert.Error(t, err) assert.Equal(t, tt.errOut, err.Error()) return } assert.NoError(t, err) assert.Equal(t, tt.wantOut, stdout.String()) reg.Verify(t) for _, d := range reg.Requests { if d.Method != "POST" { continue } if !tt.wantDebug { assert.Nil(t, d.Body) continue } data, err := io.ReadAll(d.Body) assert.NoError(t, err) var payload RerunPayload err = json.Unmarshal(data, &payload) assert.NoError(t, err) assert.Equal(t, tt.wantDebug, payload.Debug) } }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/run/rerun/rerun.go
pkg/cmd/run/rerun/rerun.go
package rerun import ( "bytes" "encoding/json" "errors" "fmt" "io" "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/run/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type RerunOptions struct { HttpClient func() (*http.Client, error) IO *iostreams.IOStreams BaseRepo func() (ghrepo.Interface, error) Prompter shared.Prompter RunID string OnlyFailed bool JobID string Debug bool Prompt bool } func NewCmdRerun(f *cmdutil.Factory, runF func(*RerunOptions) error) *cobra.Command { opts := &RerunOptions{ IO: f.IOStreams, Prompter: f.Prompter, HttpClient: f.HttpClient, } cmd := &cobra.Command{ Use: "rerun [<run-id>]", Short: "Rerun a run", Long: heredoc.Docf(` Rerun an entire run, only failed jobs, or a specific job from a run. Note that due to historical reasons, the %[1]s--job%[1]s flag may not take what you expect. Specifically, when navigating to a job in the browser, the URL looks like this: %[1]shttps://github.com/<owner>/<repo>/actions/runs/<run-id>/jobs/<number>%[1]s. However, this %[1]s<number>%[1]s should not be used with the %[1]s--job%[1]s flag and will result in the API returning %[1]s404 NOT FOUND%[1]s. Instead, you can get the correct job IDs using the following command: gh run view <run-id> --json jobs --jq '.jobs[] | {name, databaseId}' You will need to use databaseId field for triggering job re-runs. `, "`"), 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.JobID == "" { if !opts.IO.CanPrompt() { return cmdutil.FlagErrorf("`<run-id>` or `--job` required when not running interactively") } else { opts.Prompt = true } } else if len(args) > 0 { opts.RunID = args[0] } if opts.RunID != "" && opts.JobID != "" { opts.RunID = "" if opts.IO.CanPrompt() { cs := opts.IO.ColorScheme() fmt.Fprintf(opts.IO.ErrOut, "%s both run and job IDs specified; ignoring run ID\n", cs.WarningIcon()) } } if runF != nil { return runF(opts) } return runRerun(opts) }, } cmd.Flags().BoolVar(&opts.OnlyFailed, "failed", false, "Rerun only failed jobs, including dependencies") cmd.Flags().StringVarP(&opts.JobID, "job", "j", "", "Rerun a specific job ID from a run, including dependencies") cmd.Flags().BoolVarP(&opts.Debug, "debug", "d", false, "Rerun with debug logging") return cmd } func runRerun(opts *RerunOptions) error { c, err := opts.HttpClient() if err != nil { return fmt.Errorf("failed to create http client: %w", err) } client := api.NewClientFromHTTP(c) repo, err := opts.BaseRepo() if err != nil { return fmt.Errorf("failed to determine base repo: %w", err) } cs := opts.IO.ColorScheme() runID := opts.RunID jobID := opts.JobID var selectedJob *shared.Job if jobID != "" { opts.IO.StartProgressIndicator() selectedJob, err = shared.GetJob(client, repo, jobID) opts.IO.StopProgressIndicator() if err != nil { return fmt.Errorf("failed to get job: %w", err) } runID = fmt.Sprintf("%d", selectedJob.RunID) } if opts.Prompt { runs, err := shared.GetRunsWithFilter(client, repo, nil, 10, func(run shared.Run) bool { if run.Status != shared.Completed { return false } // TODO StartupFailure indicates a bad yaml file; such runs can never be // rerun. But hiding them from the prompt might confuse people? return run.Conclusion != shared.Success && run.Conclusion != shared.StartupFailure }) if err != nil { return fmt.Errorf("failed to get runs: %w", err) } if len(runs) == 0 { return errors.New("no recent runs have failed; please specify a specific `<run-id>`") } if runID, err = shared.SelectRun(opts.Prompter, cs, runs); err != nil { return err } } debugMsg := "" if opts.Debug { debugMsg = " with debug logging enabled" } if opts.JobID != "" { err = rerunJob(client, repo, selectedJob, opts.Debug) if err != nil { return err } if opts.IO.IsStdoutTTY() { fmt.Fprintf(opts.IO.Out, "%s Requested rerun of job %s on run %s%s\n", cs.SuccessIcon(), cs.Cyanf("%d", selectedJob.ID), cs.Cyanf("%d", selectedJob.RunID), debugMsg) } } else { opts.IO.StartProgressIndicator() run, err := shared.GetRun(client, repo, runID, 0) opts.IO.StopProgressIndicator() if err != nil { return fmt.Errorf("failed to get run: %w", err) } err = rerunRun(client, repo, run, opts.OnlyFailed, opts.Debug) if err != nil { return err } if opts.IO.IsStdoutTTY() { onlyFailedMsg := "" if opts.OnlyFailed { onlyFailedMsg = "(failed jobs) " } fmt.Fprintf(opts.IO.Out, "%s Requested rerun %sof run %s%s\n", cs.SuccessIcon(), onlyFailedMsg, cs.Cyanf("%d", run.ID), debugMsg) } } return nil } func rerunRun(client *api.Client, repo ghrepo.Interface, run *shared.Run, onlyFailed, debug bool) error { runVerb := "rerun" if onlyFailed { runVerb = "rerun-failed-jobs" } body, err := requestBody(debug) if err != nil { return fmt.Errorf("failed to create rerun body: %w", err) } path := fmt.Sprintf("repos/%s/actions/runs/%d/%s", ghrepo.FullName(repo), run.ID, runVerb) err = client.REST(repo.RepoHost(), "POST", path, body, nil) if err != nil { var httpError api.HTTPError if errors.As(err, &httpError) && httpError.StatusCode == 403 { return fmt.Errorf("run %d cannot be rerun; %s", run.ID, httpError.Message) } return fmt.Errorf("failed to rerun: %w", err) } return nil } func rerunJob(client *api.Client, repo ghrepo.Interface, job *shared.Job, debug bool) error { body, err := requestBody(debug) if err != nil { return fmt.Errorf("failed to create rerun body: %w", err) } path := fmt.Sprintf("repos/%s/actions/jobs/%d/rerun", ghrepo.FullName(repo), job.ID) err = client.REST(repo.RepoHost(), "POST", path, body, nil) if err != nil { var httpError api.HTTPError if errors.As(err, &httpError) && httpError.StatusCode == 403 { return fmt.Errorf("job %d cannot be rerun", job.ID) } return fmt.Errorf("failed to rerun: %w", err) } return nil } type RerunPayload struct { Debug bool `json:"enable_debug_logging"` } func requestBody(debug bool) (io.Reader, error) { if !debug { return nil, nil } params := &RerunPayload{ debug, } body := &bytes.Buffer{} enc := json.NewEncoder(body) if err := enc.Encode(params); err != nil { return nil, err } return body, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/run/list/list_test.go
pkg/cmd/run/list/list_test.go
package list import ( "bytes" "fmt" "io" "net/http" "net/url" "testing" "time" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/run/shared" workflowShared "github.com/cli/cli/v2/pkg/cmd/workflow/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 cli string tty bool wants ListOptions wantsErr bool }{ { name: "blank", wants: ListOptions{ Limit: defaultLimit, }, }, { name: "limit", cli: "--limit 100", wants: ListOptions{ Limit: 100, }, }, { name: "bad limit", cli: "--limit hi", wantsErr: true, }, { name: "workflow", cli: "--workflow foo.yml", wants: ListOptions{ Limit: defaultLimit, WorkflowSelector: "foo.yml", }, }, { name: "branch", cli: "--branch new-cool-stuff", wants: ListOptions{ Limit: defaultLimit, Branch: "new-cool-stuff", }, }, { name: "user", cli: "--user bak1an", wants: ListOptions{ Limit: defaultLimit, Actor: "bak1an", }, }, { name: "status", cli: "--status completed", wants: ListOptions{ Limit: defaultLimit, Status: "completed", }, }, { name: "event", cli: "--event push", wants: ListOptions{ Limit: defaultLimit, Event: "push", }, }, { name: "created", cli: "--created >=2023-04-24", wants: ListOptions{ Limit: defaultLimit, Created: ">=2023-04-24", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() ios.SetStdinTTY(tt.tty) ios.SetStdoutTTY(tt.tty) f := &cmdutil.Factory{ IOStreams: ios, } argv, err := shlex.Split(tt.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(io.Discard) cmd.SetErr(io.Discard) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) return } assert.Equal(t, tt.wants.Limit, gotOpts.Limit) assert.Equal(t, tt.wants.WorkflowSelector, gotOpts.WorkflowSelector) assert.Equal(t, tt.wants.Branch, gotOpts.Branch) assert.Equal(t, tt.wants.Actor, gotOpts.Actor) assert.Equal(t, tt.wants.Status, gotOpts.Status) assert.Equal(t, tt.wants.Event, gotOpts.Event) assert.Equal(t, tt.wants.Created, gotOpts.Created) }) } } func TestListRun(t *testing.T) { tests := []struct { name string opts *ListOptions wantErr bool wantOut string wantErrOut string wantErrMsg string stubs func(*httpmock.Registry) isTTY bool }{ { name: "default arguments", opts: &ListOptions{ Limit: defaultLimit, now: shared.TestRunStartTime.Add(time.Minute*4 + time.Second*34), }, isTTY: true, stubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"), httpmock.JSONResponse(shared.RunsPayload{ WorkflowRuns: shared.TestRuns, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ shared.TestWorkflow, }, })) }, wantOut: heredoc.Doc(` STATUS TITLE WORKFLOW BRANCH EVENT ID ELAPSED AGE X cool commit CI trunk push 1 4m34s about 4 minutes ago * cool commit CI trunk push 2 4m34s about 4 minutes ago ✓ cool commit CI trunk push 3 4m34s about 4 minutes ago X cool commit CI trunk push 4 4m34s about 4 minutes ago X cool commit CI trunk push 1234 4m34s about 4 minutes ago - cool commit CI trunk push 6 4m34s about 4 minutes ago - cool commit CI trunk push 7 4m34s about 4 minutes ago * cool commit CI trunk push 8 4m34s about 4 minutes ago * cool commit CI trunk push 9 4m34s about 4 minutes ago X cool commit CI trunk push 10 4m34s about 4 minutes ago `), }, { name: "inactive disabled workflow selected", opts: &ListOptions{ Limit: defaultLimit, now: shared.TestRunStartTime.Add(time.Minute*4 + time.Second*34), WorkflowSelector: "d. inact", All: false, }, isTTY: true, stubs: func(reg *httpmock.Registry) { // Uses abbreviated names and commit messages because of output column limit workflow := workflowShared.Workflow{ Name: "d. inact", ID: 1206, Path: ".github/workflows/disabledInactivity.yml", State: workflowShared.DisabledInactivity, } reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ workflow, }, })) }, wantErr: true, wantErrMsg: "could not find any workflows named d. inact", }, { name: "inactive disabled workflow selected and all states applied", opts: &ListOptions{ Limit: defaultLimit, now: shared.TestRunStartTime.Add(time.Minute*4 + time.Second*34), WorkflowSelector: "d. inact", All: true, }, isTTY: true, stubs: func(reg *httpmock.Registry) { // Uses abbreviated names and commit messages because of output column limit workflow := workflowShared.Workflow{ Name: "d. inact", ID: 1206, Path: ".github/workflows/disabledInactivity.yml", State: workflowShared.DisabledInactivity, } reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ workflow, }, })) reg.Register( httpmock.REST("GET", fmt.Sprintf("repos/OWNER/REPO/actions/workflows/%d/runs", workflow.ID)), httpmock.JSONResponse(shared.RunsPayload{ WorkflowRuns: []shared.Run{ shared.TestRunWithWorkflowAndCommit(workflow.ID, 101, shared.Completed, shared.TimedOut, "dicto"), shared.TestRunWithWorkflowAndCommit(workflow.ID, 102, shared.InProgress, shared.TimedOut, "diito"), shared.TestRunWithWorkflowAndCommit(workflow.ID, 103, shared.Completed, shared.Success, "dics"), shared.TestRunWithWorkflowAndCommit(workflow.ID, 104, shared.Completed, shared.Cancelled, "dicc"), shared.TestRunWithWorkflowAndCommit(workflow.ID, 105, shared.Completed, shared.Failure, "dicf"), }, })) }, wantOut: heredoc.Doc(` STATUS TITLE WORKFLOW BRANCH EVENT ID ELAPSED AGE X dicto d. inact trunk push 101 4m34s about 4 minutes ago * diito d. inact trunk push 102 4m34s about 4 minutes ago ✓ dics d. inact trunk push 103 4m34s about 4 minutes ago X dicc d. inact trunk push 104 4m34s about 4 minutes ago X dicf d. inact trunk push 105 4m34s about 4 minutes ago `), }, { name: "manually disabled workflow selected", opts: &ListOptions{ Limit: defaultLimit, now: shared.TestRunStartTime.Add(time.Minute*4 + time.Second*34), WorkflowSelector: "d. man", All: false, }, isTTY: true, stubs: func(reg *httpmock.Registry) { // Uses abbreviated names and commit messages because of output column limit workflow := workflowShared.Workflow{ Name: "d. man", ID: 456, Path: ".github/workflows/disabled.yml", State: workflowShared.DisabledManually, } reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ workflow, }, })) }, wantErr: true, wantErrMsg: "could not find any workflows named d. man", }, { name: "manually disabled workflow selected and all states applied", opts: &ListOptions{ Limit: defaultLimit, now: shared.TestRunStartTime.Add(time.Minute*4 + time.Second*34), WorkflowSelector: "d. man", All: true, }, isTTY: true, stubs: func(reg *httpmock.Registry) { // Uses abbreviated names and commit messages because of output column limit workflow := workflowShared.Workflow{ Name: "d. man", ID: 456, Path: ".github/workflows/disabled.yml", State: workflowShared.DisabledManually, } reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ workflow, }, })) reg.Register( httpmock.REST("GET", fmt.Sprintf("repos/OWNER/REPO/actions/workflows/%d/runs", workflow.ID)), httpmock.JSONResponse(shared.RunsPayload{ WorkflowRuns: []shared.Run{ shared.TestRunWithWorkflowAndCommit(workflow.ID, 201, shared.Completed, shared.TimedOut, "dmcto"), shared.TestRunWithWorkflowAndCommit(workflow.ID, 202, shared.InProgress, shared.TimedOut, "dmito"), shared.TestRunWithWorkflowAndCommit(workflow.ID, 203, shared.Completed, shared.Success, "dmcs"), shared.TestRunWithWorkflowAndCommit(workflow.ID, 204, shared.Completed, shared.Cancelled, "dmcc"), shared.TestRunWithWorkflowAndCommit(workflow.ID, 205, shared.Completed, shared.Failure, "dmcf"), }, })) }, wantOut: heredoc.Doc(` STATUS TITLE WORKFLOW BRANCH EVENT ID ELAPSED AGE X dmcto d. man trunk push 201 4m34s about 4 minutes ago * dmito d. man trunk push 202 4m34s about 4 minutes ago ✓ dmcs d. man trunk push 203 4m34s about 4 minutes ago X dmcc d. man trunk push 204 4m34s about 4 minutes ago X dmcf d. man trunk push 205 4m34s about 4 minutes ago `), }, { name: "default arguments nontty", opts: &ListOptions{ Limit: defaultLimit, now: shared.TestRunStartTime.Add(time.Minute*4 + time.Second*34), }, isTTY: false, stubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"), httpmock.JSONResponse(shared.RunsPayload{ WorkflowRuns: shared.TestRuns, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ shared.TestWorkflow, }, })) }, wantOut: heredoc.Doc(` completed timed_out cool commit CI trunk push 1 4m34s 2021-02-23T04:51:00Z in_progress cool commit CI trunk push 2 4m34s 2021-02-23T04:51:00Z completed success cool commit CI trunk push 3 4m34s 2021-02-23T04:51:00Z completed cancelled cool commit CI trunk push 4 4m34s 2021-02-23T04:51:00Z completed failure cool commit CI trunk push 1234 4m34s 2021-02-23T04:51:00Z completed neutral cool commit CI trunk push 6 4m34s 2021-02-23T04:51:00Z completed skipped cool commit CI trunk push 7 4m34s 2021-02-23T04:51:00Z requested cool commit CI trunk push 8 4m34s 2021-02-23T04:51:00Z queued cool commit CI trunk push 9 4m34s 2021-02-23T04:51:00Z completed stale cool commit CI trunk push 10 4m34s 2021-02-23T04:51:00Z `), }, { name: "org ruleset workflow in runs list shows with empty workflow name", opts: &ListOptions{ Limit: defaultLimit, now: shared.TestRunStartTime.Add(time.Minute*4 + time.Second*34), }, isTTY: true, stubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"), httpmock.JSONResponse(shared.RunsPayload{ WorkflowRuns: shared.TestRunsWithOrgRequiredWorkflows, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ shared.TestWorkflow, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/456"), httpmock.StatusStringResponse(404, "not found"), ) }, wantOut: heredoc.Doc(` STATUS TITLE WORKFLOW BRANCH EVENT ID ELAPSED AGE X cool commit trunk push 1 4m34s about 4 minutes ago * cool commit trunk push 2 4m34s about 4 minutes ago ✓ cool commit trunk push 3 4m34s about 4 minutes ago X cool commit trunk push 4 4m34s about 4 minutes ago X cool commit CI trunk push 5 4m34s about 4 minutes ago - cool commit CI trunk push 6 4m34s about 4 minutes ago - cool commit CI trunk push 7 4m34s about 4 minutes ago * cool commit CI trunk push 8 4m34s about 4 minutes ago * cool commit CI trunk push 9 4m34s about 4 minutes ago `), }, { name: "pagination", opts: &ListOptions{ Limit: 101, now: shared.TestRunStartTime.Add(time.Minute*4 + time.Second*34), }, isTTY: true, stubs: func(reg *httpmock.Registry) { var runID int64 runs := []shared.Run{} for runID < 103 { runs = append(runs, shared.TestRun(runID, shared.InProgress, "")) runID++ } reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"), httpmock.WithHeader(httpmock.JSONResponse(shared.RunsPayload{ WorkflowRuns: runs[0:100], }), "Link", `<https://api.github.com/repositories/123/actions/runs?per_page=100&page=2>; rel="next"`)) reg.Register( httpmock.REST("GET", "repositories/123/actions/runs"), httpmock.JSONResponse(shared.RunsPayload{ WorkflowRuns: runs[100:], })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ shared.TestWorkflow, }, })) }, wantOut: heredoc.Doc(` STATUS TITLE WORKFLOW BRANCH EVENT ID ELAPSED AGE * cool commit CI trunk push 0 4m34s about 4 minutes ago * cool commit CI trunk push 1 4m34s about 4 minutes ago * cool commit CI trunk push 2 4m34s about 4 minutes ago * cool commit CI trunk push 3 4m34s about 4 minutes ago * cool commit CI trunk push 4 4m34s about 4 minutes ago * cool commit CI trunk push 5 4m34s about 4 minutes ago * cool commit CI trunk push 6 4m34s about 4 minutes ago * cool commit CI trunk push 7 4m34s about 4 minutes ago * cool commit CI trunk push 8 4m34s about 4 minutes ago * cool commit CI trunk push 9 4m34s about 4 minutes ago * cool commit CI trunk push 10 4m34s about 4 minutes ago * cool commit CI trunk push 11 4m34s about 4 minutes ago * cool commit CI trunk push 12 4m34s about 4 minutes ago * cool commit CI trunk push 13 4m34s about 4 minutes ago * cool commit CI trunk push 14 4m34s about 4 minutes ago * cool commit CI trunk push 15 4m34s about 4 minutes ago * cool commit CI trunk push 16 4m34s about 4 minutes ago * cool commit CI trunk push 17 4m34s about 4 minutes ago * cool commit CI trunk push 18 4m34s about 4 minutes ago * cool commit CI trunk push 19 4m34s about 4 minutes ago * cool commit CI trunk push 20 4m34s about 4 minutes ago * cool commit CI trunk push 21 4m34s about 4 minutes ago * cool commit CI trunk push 22 4m34s about 4 minutes ago * cool commit CI trunk push 23 4m34s about 4 minutes ago * cool commit CI trunk push 24 4m34s about 4 minutes ago * cool commit CI trunk push 25 4m34s about 4 minutes ago * cool commit CI trunk push 26 4m34s about 4 minutes ago * cool commit CI trunk push 27 4m34s about 4 minutes ago * cool commit CI trunk push 28 4m34s about 4 minutes ago * cool commit CI trunk push 29 4m34s about 4 minutes ago * cool commit CI trunk push 30 4m34s about 4 minutes ago * cool commit CI trunk push 31 4m34s about 4 minutes ago * cool commit CI trunk push 32 4m34s about 4 minutes ago * cool commit CI trunk push 33 4m34s about 4 minutes ago * cool commit CI trunk push 34 4m34s about 4 minutes ago * cool commit CI trunk push 35 4m34s about 4 minutes ago * cool commit CI trunk push 36 4m34s about 4 minutes ago * cool commit CI trunk push 37 4m34s about 4 minutes ago * cool commit CI trunk push 38 4m34s about 4 minutes ago * cool commit CI trunk push 39 4m34s about 4 minutes ago * cool commit CI trunk push 40 4m34s about 4 minutes ago * cool commit CI trunk push 41 4m34s about 4 minutes ago * cool commit CI trunk push 42 4m34s about 4 minutes ago * cool commit CI trunk push 43 4m34s about 4 minutes ago * cool commit CI trunk push 44 4m34s about 4 minutes ago * cool commit CI trunk push 45 4m34s about 4 minutes ago * cool commit CI trunk push 46 4m34s about 4 minutes ago * cool commit CI trunk push 47 4m34s about 4 minutes ago * cool commit CI trunk push 48 4m34s about 4 minutes ago * cool commit CI trunk push 49 4m34s about 4 minutes ago * cool commit CI trunk push 50 4m34s about 4 minutes ago * cool commit CI trunk push 51 4m34s about 4 minutes ago * cool commit CI trunk push 52 4m34s about 4 minutes ago * cool commit CI trunk push 53 4m34s about 4 minutes ago * cool commit CI trunk push 54 4m34s about 4 minutes ago * cool commit CI trunk push 55 4m34s about 4 minutes ago * cool commit CI trunk push 56 4m34s about 4 minutes ago * cool commit CI trunk push 57 4m34s about 4 minutes ago * cool commit CI trunk push 58 4m34s about 4 minutes ago * cool commit CI trunk push 59 4m34s about 4 minutes ago * cool commit CI trunk push 60 4m34s about 4 minutes ago * cool commit CI trunk push 61 4m34s about 4 minutes ago * cool commit CI trunk push 62 4m34s about 4 minutes ago * cool commit CI trunk push 63 4m34s about 4 minutes ago * cool commit CI trunk push 64 4m34s about 4 minutes ago * cool commit CI trunk push 65 4m34s about 4 minutes ago * cool commit CI trunk push 66 4m34s about 4 minutes ago * cool commit CI trunk push 67 4m34s about 4 minutes ago * cool commit CI trunk push 68 4m34s about 4 minutes ago * cool commit CI trunk push 69 4m34s about 4 minutes ago * cool commit CI trunk push 70 4m34s about 4 minutes ago * cool commit CI trunk push 71 4m34s about 4 minutes ago * cool commit CI trunk push 72 4m34s about 4 minutes ago * cool commit CI trunk push 73 4m34s about 4 minutes ago * cool commit CI trunk push 74 4m34s about 4 minutes ago * cool commit CI trunk push 75 4m34s about 4 minutes ago * cool commit CI trunk push 76 4m34s about 4 minutes ago * cool commit CI trunk push 77 4m34s about 4 minutes ago * cool commit CI trunk push 78 4m34s about 4 minutes ago * cool commit CI trunk push 79 4m34s about 4 minutes ago * cool commit CI trunk push 80 4m34s about 4 minutes ago * cool commit CI trunk push 81 4m34s about 4 minutes ago * cool commit CI trunk push 82 4m34s about 4 minutes ago * cool commit CI trunk push 83 4m34s about 4 minutes ago * cool commit CI trunk push 84 4m34s about 4 minutes ago * cool commit CI trunk push 85 4m34s about 4 minutes ago * cool commit CI trunk push 86 4m34s about 4 minutes ago * cool commit CI trunk push 87 4m34s about 4 minutes ago * cool commit CI trunk push 88 4m34s about 4 minutes ago * cool commit CI trunk push 89 4m34s about 4 minutes ago * cool commit CI trunk push 90 4m34s about 4 minutes ago * cool commit CI trunk push 91 4m34s about 4 minutes ago * cool commit CI trunk push 92 4m34s about 4 minutes ago * cool commit CI trunk push 93 4m34s about 4 minutes ago * cool commit CI trunk push 94 4m34s about 4 minutes ago * cool commit CI trunk push 95 4m34s about 4 minutes ago * cool commit CI trunk push 96 4m34s about 4 minutes ago * cool commit CI trunk push 97 4m34s about 4 minutes ago * cool commit CI trunk push 98 4m34s about 4 minutes ago * cool commit CI trunk push 99 4m34s about 4 minutes ago * cool commit CI trunk push 100 4m34s about 4 minutes ago `), }, { name: "no results", opts: &ListOptions{ Limit: defaultLimit, }, stubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"), httpmock.JSONResponse(shared.RunsPayload{}), ) }, wantErr: true, wantErrMsg: "no runs found", }, { name: "workflow selector", opts: &ListOptions{ Limit: defaultLimit, WorkflowSelector: "flow.yml", now: shared.TestRunStartTime.Add(time.Minute*4 + time.Second*34), }, isTTY: true, stubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/flow.yml"), httpmock.JSONResponse(workflowShared.AWorkflow)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123/runs"), httpmock.JSONResponse(shared.RunsPayload{ WorkflowRuns: shared.WorkflowRuns, })) }, wantOut: heredoc.Doc(` STATUS TITLE WORKFLOW BRANCH EVENT ID ELAPSED AGE * cool commit a workflow trunk push 2 4m34s about 4 minute... ✓ cool commit a workflow trunk push 3 4m34s about 4 minute... X cool commit a workflow trunk push 1234 4m34s about 4 minute... `), }, { name: "branch filter applied", opts: &ListOptions{ Limit: defaultLimit, Branch: "the-branch", }, stubs: func(reg *httpmock.Registry) { reg.Register( httpmock.QueryMatcher("GET", "repos/OWNER/REPO/actions/runs", url.Values{ "branch": []string{"the-branch"}, }), httpmock.JSONResponse(shared.RunsPayload{}), ) }, wantErr: true, wantErrMsg: "no runs found", }, { name: "actor filter applied", opts: &ListOptions{ Limit: defaultLimit, Actor: "bak1an", }, stubs: func(reg *httpmock.Registry) { reg.Register( httpmock.QueryMatcher("GET", "repos/OWNER/REPO/actions/runs", url.Values{ "actor": []string{"bak1an"}, }), httpmock.JSONResponse(shared.RunsPayload{}), ) }, wantErr: true, wantErrMsg: "no runs found", }, { name: "status filter applied", opts: &ListOptions{ Limit: defaultLimit, Status: "queued", }, isTTY: true, stubs: func(reg *httpmock.Registry) { reg.Register( httpmock.QueryMatcher("GET", "repos/OWNER/REPO/actions/runs", url.Values{ "status": []string{"queued"}, }), httpmock.JSONResponse(shared.RunsPayload{}), ) }, wantErr: true, wantErrMsg: "no runs found", }, { name: "event filter applied", opts: &ListOptions{ Limit: defaultLimit, Event: "push", }, isTTY: true, stubs: func(reg *httpmock.Registry) { reg.Register( httpmock.QueryMatcher("GET", "repos/OWNER/REPO/actions/runs", url.Values{ "event": []string{"push"}, }), httpmock.JSONResponse(shared.RunsPayload{}), ) }, wantErr: true, wantErrMsg: "no runs found", }, { name: "created filter applied", opts: &ListOptions{ Limit: defaultLimit, Created: ">=2023-04-24", }, isTTY: true, stubs: func(reg *httpmock.Registry) { reg.Register( httpmock.QueryMatcher("GET", "repos/OWNER/REPO/actions/runs", url.Values{ "created": []string{">=2023-04-24"}, }), httpmock.JSONResponse(shared.RunsPayload{}), ) }, wantErr: true, wantErrMsg: "no runs found", }, { name: "commit filter applied", opts: &ListOptions{ Limit: defaultLimit, Commit: "1234567890123456789012345678901234567890", }, isTTY: true, stubs: func(reg *httpmock.Registry) { reg.Register( httpmock.QueryMatcher("GET", "repos/OWNER/REPO/actions/runs", url.Values{ "head_sha": []string{"1234567890123456789012345678901234567890"}, }), httpmock.JSONResponse(shared.RunsPayload{}), ) }, wantErr: true, wantErrMsg: "no runs found", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { reg := &httpmock.Registry{} defer reg.Verify(t) tt.stubs(reg) tt.opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } ios, _, stdout, stderr := iostreams.Test() ios.SetStdoutTTY(tt.isTTY) tt.opts.IO = ios tt.opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.FromFullName("OWNER/REPO") } err := listRun(tt.opts) if tt.wantErr { assert.Error(t, err) assert.Equal(t, tt.wantErrMsg, err.Error()) } else { assert.NoError(t, err) } assert.Equal(t, tt.wantOut, stdout.String()) assert.Equal(t, tt.wantErrOut, stderr.String()) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/run/list/list.go
pkg/cmd/run/list/list.go
package list import ( "fmt" "net/http" "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/pkg/cmd/run/shared" workflowShared "github.com/cli/cli/v2/pkg/cmd/workflow/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) const ( defaultLimit = 20 ) type ListOptions struct { IO *iostreams.IOStreams HttpClient func() (*http.Client, error) BaseRepo func() (ghrepo.Interface, error) Prompter iprompter Exporter cmdutil.Exporter Limit int WorkflowSelector string Branch string Actor string Status string Event string Created string Commit string All bool now time.Time } type iprompter interface { Select(string, string, []string) (int, error) } func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Command { opts := &ListOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, Prompter: f.Prompter, now: time.Now(), } cmd := &cobra.Command{ Use: "list", Short: "List recent workflow runs", Long: heredoc.Docf(` List recent workflow runs. Note that providing the %[1]sworkflow_name%[1]s to the %[1]s-w%[1]s flag will not fetch disabled workflows. Also pass the %[1]s-a%[1]s flag to fetch disabled workflow runs using the %[1]sworkflow_name%[1]s and the %[1]s-w%[1]s flag. Runs created by organization and enterprise ruleset workflows will not display a workflow name due to GitHub API limitations. To see runs associated with a pull request, users should run %[1]sgh pr checks%[1]s. `, "`"), 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", defaultLimit, "Maximum number of runs to fetch") cmd.Flags().StringVarP(&opts.WorkflowSelector, "workflow", "w", "", "Filter runs by workflow") cmd.Flags().StringVarP(&opts.Branch, "branch", "b", "", "Filter runs by branch") cmd.Flags().StringVarP(&opts.Actor, "user", "u", "", "Filter runs by user who triggered the run") cmd.Flags().StringVarP(&opts.Event, "event", "e", "", "Filter runs by which `event` triggered the run") cmd.Flags().StringVarP(&opts.Created, "created", "", "", "Filter runs by the `date` it was created") cmd.Flags().StringVarP(&opts.Commit, "commit", "c", "", "Filter runs by the `SHA` of the commit") cmd.Flags().BoolVarP(&opts.All, "all", "a", false, "Include disabled workflows") cmdutil.StringEnumFlag(cmd, &opts.Status, "status", "s", "", shared.AllStatuses, "Filter runs by status") cmdutil.AddJSONFlags(cmd, &opts.Exporter, shared.RunFields) _ = cmdutil.RegisterBranchCompletionFlags(f.GitClient, cmd, "branch") return cmd } func listRun(opts *ListOptions) error { baseRepo, err := opts.BaseRepo() if err != nil { return fmt.Errorf("failed to determine base repo: %w", err) } c, err := opts.HttpClient() if err != nil { return fmt.Errorf("failed to create http client: %w", err) } client := api.NewClientFromHTTP(c) filters := &shared.FilterOptions{ Branch: opts.Branch, Actor: opts.Actor, Status: opts.Status, Event: opts.Event, Created: opts.Created, Commit: opts.Commit, } opts.IO.StartProgressIndicator() defer opts.IO.StopProgressIndicator() if opts.WorkflowSelector != "" { // initially the workflow state is limited to 'active' states := []workflowShared.WorkflowState{workflowShared.Active} if opts.All { // the all flag tells us to add the remaining workflow states // note: this will be incomplete if more workflow states are added to `workflowShared` states = append(states, workflowShared.DisabledManually, workflowShared.DisabledInactivity) } if workflow, err := workflowShared.ResolveWorkflow(opts.Prompter, opts.IO, client, baseRepo, false, opts.WorkflowSelector, states); err == nil { filters.WorkflowID = workflow.ID filters.WorkflowName = workflow.Name } else { return err } } runsResult, err := shared.GetRuns(client, baseRepo, filters, opts.Limit) opts.IO.StopProgressIndicator() if err != nil { return fmt.Errorf("failed to get runs: %w", err) } runs := runsResult.WorkflowRuns if len(runs) == 0 && opts.Exporter == nil { return cmdutil.NewNoResultsError("no runs 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, runs) } tp := tableprinter.New(opts.IO, tableprinter.WithHeader("STATUS", "TITLE", "WORKFLOW", "BRANCH", "EVENT", "ID", "ELAPSED", "AGE")) cs := opts.IO.ColorScheme() for _, run := range runs { if tp.IsTTY() { symbol, symbolColor := shared.Symbol(cs, run.Status, run.Conclusion) tp.AddField(symbol, tableprinter.WithColor(symbolColor)) } else { tp.AddField(string(run.Status)) tp.AddField(string(run.Conclusion)) } tp.AddField(run.Title(), tableprinter.WithColor(cs.Bold)) tp.AddField(run.WorkflowName()) tp.AddField(run.HeadBranch, tableprinter.WithColor(cs.Bold)) tp.AddField(string(run.Event)) tp.AddField(fmt.Sprintf("%d", run.ID), tableprinter.WithColor(cs.Cyan)) tp.AddField(run.Duration(opts.now).String()) tp.AddTimeField(opts.now, run.StartedTime(), cs.Muted) 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/run/view/view.go
pkg/cmd/run/view/view.go
package view import ( "archive/zip" "bufio" "bytes" "errors" "fmt" "io" "net/http" "os" "path/filepath" "strconv" "time" "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/run/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type RunLogCache struct { cacheDir string } func (c RunLogCache) Exists(key string) (bool, error) { _, err := os.Stat(c.filepath(key)) if err == nil { return true, nil } if errors.Is(err, os.ErrNotExist) { return false, nil } return false, fmt.Errorf("checking cache entry: %v", err) } func (c RunLogCache) Create(key string, content io.Reader) error { if err := os.MkdirAll(c.cacheDir, 0755); err != nil { return fmt.Errorf("creating cache directory: %v", err) } out, err := os.Create(c.filepath(key)) if err != nil { return fmt.Errorf("creating cache entry: %v", err) } defer out.Close() if _, err := io.Copy(out, content); err != nil { return fmt.Errorf("writing cache entry: %v", err) } return nil } func (c RunLogCache) Open(key string) (*zip.ReadCloser, error) { r, err := zip.OpenReader(c.filepath(key)) if err != nil { return nil, fmt.Errorf("opening cache entry: %v", err) } return r, nil } func (c RunLogCache) filepath(key string) string { return filepath.Join(c.cacheDir, fmt.Sprintf("run-log-%s.zip", key)) } type ViewOptions struct { HttpClient func() (*http.Client, error) IO *iostreams.IOStreams BaseRepo func() (ghrepo.Interface, error) Browser browser.Browser Prompter shared.Prompter RunLogCache RunLogCache RunID string JobID string Verbose bool ExitStatus bool Log bool LogFailed bool Web bool Attempt uint64 Prompt bool Exporter cmdutil.Exporter Now func() time.Time } func NewCmdView(f *cmdutil.Factory, runF func(*ViewOptions) error) *cobra.Command { opts := &ViewOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, Prompter: f.Prompter, Now: time.Now, Browser: f.Browser, } cmd := &cobra.Command{ Use: "view [<run-id>]", Short: "View a summary of a workflow run", Long: heredoc.Docf(` View a summary of a workflow run. Due to platform limitations, %[1]sgh%[1]s may not always be able to associate jobs with their corresponding logs when using the primary method of fetching logs in zip format. In such cases, %[1]sgh%[1]s will attempt to fetch logs for each job individually via the API. This fallback is slower and more resource-intensive. If more than 25 job logs are missing, the operation will fail with an error. Additionally, due to similar platform constraints, some log lines may not be associated with a specific step within a job. In these cases, the step name will appear as %[1]sUNKNOWN STEP%[1]s in the log output. `, "`", maxAPILogFetchers), Args: cobra.MaximumNArgs(1), Example: heredoc.Doc(` # Interactively select a run to view, optionally selecting a single job $ gh run view # View a specific run $ gh run view 12345 # View a specific run with specific attempt number $ gh run view 12345 --attempt 3 # View a specific job within a run $ gh run view --job 456789 # View the full log for a specific job $ gh run view --log --job 456789 # Exit non-zero if a run failed $ gh run view 0451 --exit-status && echo "run pending or passed" `), RunE: func(cmd *cobra.Command, args []string) error { // support `-R, --repo` override opts.BaseRepo = f.BaseRepo config, err := f.Config() if err != nil { return err } opts.RunLogCache = RunLogCache{ cacheDir: config.CacheDir(), } if len(args) == 0 && opts.JobID == "" { if !opts.IO.CanPrompt() { return cmdutil.FlagErrorf("run or job ID required when not running interactively") } else { opts.Prompt = true } } else if len(args) > 0 { opts.RunID = args[0] } if opts.RunID != "" && opts.JobID != "" { opts.RunID = "" if opts.IO.CanPrompt() { cs := opts.IO.ColorScheme() fmt.Fprintf(opts.IO.ErrOut, "%s both run and job IDs specified; ignoring run ID\n", cs.WarningIcon()) } } if opts.Web && opts.Log { return cmdutil.FlagErrorf("specify only one of --web or --log") } if opts.Log && opts.LogFailed { return cmdutil.FlagErrorf("specify only one of --log or --log-failed") } if runF != nil { return runF(opts) } return runView(opts) }, } cmd.Flags().BoolVarP(&opts.Verbose, "verbose", "v", false, "Show job steps") // TODO should we try and expose pending via another exit code? cmd.Flags().BoolVar(&opts.ExitStatus, "exit-status", false, "Exit with non-zero status if run failed") cmd.Flags().StringVarP(&opts.JobID, "job", "j", "", "View a specific job ID from a run") cmd.Flags().BoolVar(&opts.Log, "log", false, "View full log for either a run or specific job") cmd.Flags().BoolVar(&opts.LogFailed, "log-failed", false, "View the log for any failed steps in a run or specific job") cmd.Flags().BoolVarP(&opts.Web, "web", "w", false, "Open run in the browser") cmd.Flags().Uint64VarP(&opts.Attempt, "attempt", "a", 0, "The attempt number of the workflow run") cmdutil.AddJSONFlags(cmd, &opts.Exporter, shared.SingleRunFields) return cmd } func runView(opts *ViewOptions) 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) } jobID := opts.JobID runID := opts.RunID attempt := opts.Attempt var selectedJob *shared.Job var run *shared.Run var jobs []shared.Job defer opts.IO.StopProgressIndicator() if jobID != "" { opts.IO.StartProgressIndicator() selectedJob, err = shared.GetJob(client, repo, jobID) opts.IO.StopProgressIndicator() if err != nil { return fmt.Errorf("failed to get job: %w", err) } // TODO once more stuff is merged, standardize on using ints runID = fmt.Sprintf("%d", selectedJob.RunID) } cs := opts.IO.ColorScheme() if opts.Prompt { // TODO arbitrary limit opts.IO.StartProgressIndicator() runs, err := shared.GetRuns(client, repo, nil, 10) opts.IO.StopProgressIndicator() if err != nil { return fmt.Errorf("failed to get runs: %w", err) } runID, err = shared.SelectRun(opts.Prompter, cs, runs.WorkflowRuns) if err != nil { return err } } opts.IO.StartProgressIndicator() run, err = shared.GetRun(client, repo, runID, attempt) opts.IO.StopProgressIndicator() if err != nil { return fmt.Errorf("failed to get run: %w", err) } if shouldFetchJobs(opts) { opts.IO.StartProgressIndicator() jobs, err = shared.GetJobs(client, repo, run, attempt) opts.IO.StopProgressIndicator() if err != nil { return err } } if opts.Prompt && len(jobs) > 1 { selectedJob, err = promptForJob(opts.Prompter, cs, jobs) if err != nil { return err } } 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, run) } if opts.Web { url := run.URL if selectedJob != nil { url = selectedJob.URL + "?check_suite_focus=true" } if opts.IO.IsStdoutTTY() { fmt.Fprintf(opts.IO.Out, "Opening %s in your browser.\n", text.DisplayURL(url)) } return opts.Browser.Browse(url) } if selectedJob == nil && len(jobs) == 0 { opts.IO.StartProgressIndicator() jobs, err = shared.GetJobs(client, repo, run, attempt) opts.IO.StopProgressIndicator() if err != nil { return fmt.Errorf("failed to get jobs: %w", err) } } else if selectedJob != nil { jobs = []shared.Job{*selectedJob} } if opts.Log || opts.LogFailed { if selectedJob != nil && selectedJob.Status != shared.Completed { return fmt.Errorf("job %d is still in progress; logs will be available when it is complete", selectedJob.ID) } if run.Status != shared.Completed { return fmt.Errorf("run %d is still in progress; logs will be available when it is complete", run.ID) } opts.IO.StartProgressIndicator() runLogZip, err := getRunLog(opts.RunLogCache, httpClient, repo, run, attempt) opts.IO.StopProgressIndicator() if err != nil { return fmt.Errorf("failed to get run log: %w", err) } defer runLogZip.Close() zlm := getZipLogMap(&runLogZip.Reader, jobs) segments, err := populateLogSegments(httpClient, repo, jobs, zlm, opts.LogFailed) if err != nil { if errors.Is(err, errTooManyAPILogFetchers) { return fmt.Errorf("too many API requests needed to fetch logs; try narrowing down to a specific job with the `--job` option") } return err } return displayLogSegments(opts.IO.Out, segments) } prNumber := "" number, err := shared.PullRequestForRun(client, repo, *run) if err == nil { prNumber = fmt.Sprintf(" %s#%d", ghrepo.FullName(repo), number) } var artifacts []shared.Artifact if selectedJob == nil { artifacts, err = shared.ListArtifacts(httpClient, repo, strconv.FormatInt(int64(run.ID), 10)) if err != nil { return fmt.Errorf("failed to get artifacts: %w", err) } } var annotations []shared.Annotation var missingAnnotationsPermissions bool for _, job := range jobs { as, err := shared.GetAnnotations(client, repo, job) if err != nil { if err != shared.ErrMissingAnnotationsPermissions { return fmt.Errorf("failed to get annotations: %w", err) } missingAnnotationsPermissions = true break } annotations = append(annotations, as...) } out := opts.IO.Out fmt.Fprintln(out) fmt.Fprintln(out, shared.RenderRunHeader(cs, *run, text.FuzzyAgo(opts.Now(), run.StartedTime()), prNumber, attempt)) fmt.Fprintln(out) if len(jobs) == 0 && run.Conclusion == shared.Failure || run.Conclusion == shared.StartupFailure { fmt.Fprintf(out, "%s %s\n", cs.FailureIcon(), cs.Bold("This run likely failed because of a workflow file issue.")) fmt.Fprintln(out) fmt.Fprintf(out, "For more information, see: %s\n", cs.Bold(run.URL)) if opts.ExitStatus { return cmdutil.SilentError } return nil } if selectedJob == nil { fmt.Fprintln(out, cs.Bold("JOBS")) fmt.Fprintln(out, shared.RenderJobs(cs, jobs, opts.Verbose)) } else { fmt.Fprintln(out, shared.RenderJobs(cs, jobs, true)) } if missingAnnotationsPermissions { fmt.Fprintln(out) fmt.Fprintln(out, cs.Bold("ANNOTATIONS")) fmt.Fprintln(out, "requesting annotations returned 403 Forbidden as the token does not have sufficient permissions. Note that it is not currently possible to create a fine-grained PAT with the `checks:read` permission.") } else if len(annotations) > 0 { fmt.Fprintln(out) fmt.Fprintln(out, cs.Bold("ANNOTATIONS")) fmt.Fprintln(out, shared.RenderAnnotations(cs, annotations)) } if selectedJob == nil { if len(artifacts) > 0 { fmt.Fprintln(out) fmt.Fprintln(out, cs.Bold("ARTIFACTS")) for _, a := range artifacts { expiredBadge := "" if a.Expired { expiredBadge = cs.Muted(" (expired)") } fmt.Fprintf(out, "%s%s\n", a.Name, expiredBadge) } } fmt.Fprintln(out) if shared.IsFailureState(run.Conclusion) { fmt.Fprintf(out, "To see what failed, try: gh run view %d --log-failed\n", run.ID) } else if len(jobs) == 1 { fmt.Fprintf(out, "For more information about the job, try: gh run view --job=%d\n", jobs[0].ID) } else { fmt.Fprintf(out, "For more information about a job, try: gh run view --job=<job-id>\n") } fmt.Fprintln(out, cs.Mutedf("View this run on GitHub: %s", run.URL)) if opts.ExitStatus && shared.IsFailureState(run.Conclusion) { return cmdutil.SilentError } } else { fmt.Fprintln(out) if shared.IsFailureState(selectedJob.Conclusion) { fmt.Fprintf(out, "To see the logs for the failed steps, try: gh run view --log-failed --job=%d\n", selectedJob.ID) } else { fmt.Fprintf(out, "To see the full job log, try: gh run view --log --job=%d\n", selectedJob.ID) } fmt.Fprintln(out, cs.Mutedf("View this run on GitHub: %s", run.URL)) if opts.ExitStatus && shared.IsFailureState(selectedJob.Conclusion) { return cmdutil.SilentError } } return nil } func shouldFetchJobs(opts *ViewOptions) bool { if opts.Prompt { return true } if opts.Exporter != nil { for _, f := range opts.Exporter.Fields() { if f == "jobs" { return true } } } return false } func getLog(httpClient *http.Client, logURL string) (io.ReadCloser, error) { req, err := http.NewRequest("GET", logURL, nil) if err != nil { return nil, err } resp, err := httpClient.Do(req) if err != nil { return nil, err } if resp.StatusCode == 404 { return nil, errors.New("log not found") } else if resp.StatusCode != 200 { return nil, api.HandleHTTPError(resp) } return resp.Body, nil } func getRunLog(cache RunLogCache, httpClient *http.Client, repo ghrepo.Interface, run *shared.Run, attempt uint64) (*zip.ReadCloser, error) { cacheKey := fmt.Sprintf("%d-%d", run.ID, run.StartedTime().Unix()) isCached, err := cache.Exists(cacheKey) if err != nil { return nil, err } if !isCached { // Run log does not exist in cache so retrieve and store it logURL := fmt.Sprintf("%srepos/%s/actions/runs/%d/logs", ghinstance.RESTPrefix(repo.RepoHost()), ghrepo.FullName(repo), run.ID) if attempt > 0 { logURL = fmt.Sprintf("%srepos/%s/actions/runs/%d/attempts/%d/logs", ghinstance.RESTPrefix(repo.RepoHost()), ghrepo.FullName(repo), run.ID, attempt) } resp, err := getLog(httpClient, logURL) if err != nil { return nil, err } defer resp.Close() data, err := io.ReadAll(resp) if err != nil { return nil, err } respReader := bytes.NewReader(data) // Check if the response is a valid zip format _, err = zip.NewReader(respReader, respReader.Size()) if err != nil { return nil, err } err = cache.Create(cacheKey, respReader) if err != nil { return nil, err } } return cache.Open(cacheKey) } func promptForJob(prompter shared.Prompter, cs *iostreams.ColorScheme, jobs []shared.Job) (*shared.Job, error) { candidates := []string{"View all jobs in this run"} for _, job := range jobs { symbol, _ := shared.Symbol(cs, job.Status, job.Conclusion) candidates = append(candidates, fmt.Sprintf("%s %s", symbol, job.Name)) } selected, err := prompter.Select("View a specific job in this run?", "", candidates) if err != nil { return nil, err } if selected > 0 { return &jobs[selected-1], nil } // User wants to see all jobs return nil, nil } func displayLogSegments(w io.Writer, segments []logSegment) error { for _, segment := range segments { stepName := "UNKNOWN STEP" if segment.step != nil { stepName = segment.step.Name } rc, err := segment.fetcher.GetLog() if err != nil { return err } err = func() error { defer rc.Close() prefix := fmt.Sprintf("%s\t%s\t", segment.job.Name, stepName) if err := copyLogWithLinePrefix(w, rc, prefix); err != nil { return err } return nil }() if err != nil { return err } } return nil } func copyLogWithLinePrefix(w io.Writer, r io.Reader, prefix string) error { scanner := bufio.NewScanner(r) for scanner.Scan() { fmt.Fprintf(w, "%s%s\n", prefix, scanner.Text()) } return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/run/view/logs_test.go
pkg/cmd/run/view/logs_test.go
package view import ( "archive/zip" "bytes" "io" "net/http" "testing" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/run/shared" "github.com/cli/cli/v2/pkg/httpmock" ghAPI "github.com/cli/go-gh/v2/pkg/api" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestZipLogFetcher(t *testing.T) { zr := createZipReader(t, map[string]string{ "foo.txt": "blah blah", }) fetcher := &zipLogFetcher{ File: zr.File[0], } rc, err := fetcher.GetLog() assert.NoError(t, err) defer rc.Close() content, err := io.ReadAll(rc) assert.NoError(t, err) assert.Equal(t, "blah blah", string(content)) } func TestApiLogFetcher(t *testing.T) { tests := []struct { name string httpStubs func(reg *httpmock.Registry) wantErr string wantContent string }{ { // This is the real flow as of now. When we call the `/logs` // endpoint, the server will respond with a 302 redirect, pointing // to the actual log file URL. name: "successful with redirect (HTTP 302, then HTTP 200)", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/jobs/123/logs"), httpmock.WithHeader( httpmock.StatusStringResponse(http.StatusFound, ""), "Location", "https://some.domain/the-actual-log", ), ) reg.Register( httpmock.REST("GET", "the-actual-log"), httpmock.StringResponse("blah blah"), ) }, wantContent: "blah blah", }, { name: "successful without redirect (HTTP 200)", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/jobs/123/logs"), httpmock.StatusStringResponse(http.StatusOK, "blah blah"), ) }, wantContent: "blah blah", }, { name: "failed with not found error (HTTP 404)", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/jobs/123/logs"), httpmock.StatusStringResponse(http.StatusNotFound, ""), ) }, wantErr: "log not found: 123", }, { name: "failed with server error (HTTP 500)", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/jobs/123/logs"), httpmock.JSONErrorResponse(http.StatusInternalServerError, ghAPI.HTTPError{ Message: "blah blah", StatusCode: http.StatusInternalServerError, }), ) }, wantErr: "HTTP 500: blah blah (https://api.github.com/repos/OWNER/REPO/actions/jobs/123/logs)", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { reg := &httpmock.Registry{} defer reg.Verify(t) tt.httpStubs(reg) httpClient := &http.Client{Transport: reg} fetcher := &apiLogFetcher{ httpClient: httpClient, repo: ghrepo.New("OWNER", "REPO"), jobID: 123, } rc, err := fetcher.GetLog() if tt.wantErr != "" { assert.EqualError(t, err, tt.wantErr) assert.Nil(t, rc) return } assert.NoError(t, err) assert.NotNil(t, rc) content, err := io.ReadAll(rc) assert.NoError(t, err) assert.NoError(t, rc.Close()) assert.Equal(t, tt.wantContent, string(content)) }) } } func TestGetZipLogMap(t *testing.T) { tests := []struct { name string job shared.Job zipReader *zip.Reader // wantJobLog can be nil (i.e. not found) or string wantJobLog any // wantStepLogs elements can be nil (i.e. not found) or string wantStepLogs []any }{ { name: "job log missing from zip, but step log present", job: shared.Job{ ID: 123, Name: "job foo", Steps: []shared.Step{{ Name: "step one", Number: 1, }}, }, zipReader: createZipReader(t, map[string]string{ "job foo/1_step one.txt": "step one log", }), wantJobLog: nil, wantStepLogs: []any{ "step one log", }, }, { name: "matching job name and step number 1", job: shared.Job{ ID: 123, Name: "job foo", Steps: []shared.Step{{ Name: "step one", Number: 1, }}, }, zipReader: createZipReader(t, map[string]string{ "0_job foo.txt": "job log", "job foo/1_step one.txt": "step one log", }), wantJobLog: "job log", wantStepLogs: []any{ "step one log", }, }, { name: "matching job name and step number 2", job: shared.Job{ ID: 123, Name: "job foo", Steps: []shared.Step{{ Name: "step two", Number: 2, }}, }, zipReader: createZipReader(t, map[string]string{ "0_job foo.txt": "job log", "job foo/2_step two.txt": "step two log", }), wantJobLog: "job log", wantStepLogs: []any{ nil, // no log for step 1 "step two log", }, }, { // We should just look for the step number and not the step name. name: "matching job name and step number and mismatch step name", job: shared.Job{ ID: 123, Name: "job foo", Steps: []shared.Step{{ Name: "mismatch", Number: 1, }}, }, zipReader: createZipReader(t, map[string]string{ "0_job foo.txt": "job log", "job foo/1_step one.txt": "step one log", }), wantJobLog: "job log", wantStepLogs: []any{ "step one log", }, }, { name: "matching job name and mismatch step number", job: shared.Job{ ID: 123, Name: "job foo", Steps: []shared.Step{{ Name: "step two", Number: 2, }}, }, zipReader: createZipReader(t, map[string]string{ "0_job foo.txt": "job log", "job foo/1_step one.txt": "step one log", }), wantJobLog: "job log", wantStepLogs: []any{ nil, // no log for step 1 nil, // no log for step 2 }, }, { name: "matching job name with no step logs in zip", job: shared.Job{ ID: 123, Name: "job foo", Steps: []shared.Step{{ Name: "step one", Number: 1, }}, }, zipReader: createZipReader(t, map[string]string{ "0_job foo.txt": "job log", }), wantJobLog: "job log", wantStepLogs: []any{ nil, // no log for step 1 }, }, { name: "matching job name with no step data", job: shared.Job{ ID: 123, Name: "job foo", }, zipReader: createZipReader(t, map[string]string{ "0_job foo.txt": "job log", }), wantJobLog: "job log", wantStepLogs: []any{ nil, // no log for step 1 }, }, { name: "matching job name with random prefix and no step logs in zip", job: shared.Job{ ID: 123, Name: "job foo", Steps: []shared.Step{{ Name: "step one", Number: 1, }}, }, zipReader: createZipReader(t, map[string]string{ "999999999_job foo.txt": "job log", }), wantJobLog: "job log", wantStepLogs: []any{ nil, // no log for step 1 }, }, { name: "matching job name with legacy filename and no step logs in zip", job: shared.Job{ ID: 123, Name: "job foo", Steps: []shared.Step{{ Name: "step one", Number: 1, }}, }, zipReader: createZipReader(t, map[string]string{ "-9999999999_job foo.txt": "job log", }), wantJobLog: "job log", wantStepLogs: []any{ nil, // no log for step 1 }, }, { name: "matching job name with legacy filename and no step data", job: shared.Job{ ID: 123, Name: "job foo", }, zipReader: createZipReader(t, map[string]string{ "-9999999999_job foo.txt": "job log", }), wantJobLog: "job log", wantStepLogs: []any{ nil, // no log for step 1 }, }, { name: "matching job name with both normal and legacy filename", job: shared.Job{ ID: 123, Name: "job foo", }, zipReader: createZipReader(t, map[string]string{ "0_job foo.txt": "job log", "-9999999999_job foo.txt": "legacy job log", }), wantJobLog: "job log", wantStepLogs: []any{ nil, // no log for step 1 }, }, { name: "one job name is a suffix of another", job: shared.Job{ ID: 123, Name: "job foo", Steps: []shared.Step{{ Name: "step one", Number: 1, }}, }, zipReader: createZipReader(t, map[string]string{ "0_jjob foo.txt": "the other job log", "jjob foo/1_step one.txt": "the other step one log", "1_job foo.txt": "job log", "job foo/1_step one.txt": "step one log", }), wantJobLog: "job log", wantStepLogs: []any{ "step one log", }, }, { name: "escape metacharacters in job name", job: shared.Job{ ID: 123, Name: "metacharacters .+*?()|[]{}^$ job", Steps: []shared.Step{{ Name: "step one", Number: 1, }}, }, zipReader: createZipReader(t, nil), wantJobLog: nil, wantStepLogs: []any{ nil, // no log for step 1 }, }, { name: "mismatching job name", job: shared.Job{ ID: 123, Name: "mismatch", Steps: []shared.Step{{ Name: "step one", Number: 1, }}, }, zipReader: createZipReader(t, nil), wantJobLog: nil, wantStepLogs: []any{ nil, // no log for step 1 }, }, { name: "job name with forward slash matches dir with slash removed", job: shared.Job{ ID: 123, Name: "job foo / with slash", Steps: []shared.Step{{ Name: "step one", Number: 1, }}, }, zipReader: createZipReader(t, map[string]string{ "0_job foo with slash.txt": "job log", "job foo with slash/1_step one.txt": "step one log", }), wantJobLog: "job log", wantStepLogs: []any{ "step one log", }, }, { name: "job name with colon matches dir with colon removed", job: shared.Job{ ID: 123, Name: "job foo : with colon", Steps: []shared.Step{{ Name: "step one", Number: 1, }}, }, zipReader: createZipReader(t, map[string]string{ "0_job foo with colon.txt": "job log", "job foo with colon/1_step one.txt": "step one log", }), wantJobLog: "job log", wantStepLogs: []any{ "step one log", }, }, { name: "job name with really long name (over the ZIP limit)", job: shared.Job{ ID: 123, Name: "thisisnineteenchars_thisisnineteenchars_thisisnineteenchars_thisisnineteenchars_thisisnineteenchars_", Steps: []shared.Step{{ Name: "long name job", Number: 1, }}, }, zipReader: createZipReader(t, map[string]string{ "thisisnineteenchars_thisisnineteenchars_thisisnineteenchars_thisisnineteenchars_thisisnine/1_long name job.txt": "step one log", }), wantJobLog: nil, wantStepLogs: []any{ "step one log", }, }, { name: "job name that would be truncated by the C# server to split a grapheme", job: shared.Job{ ID: 123, Name: "emoji test 😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅", Steps: []shared.Step{{ Name: "emoji job", Number: 1, }}, }, zipReader: createZipReader(t, map[string]string{ "emoji test 😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅�/1_emoji job.txt": "step one log", }), wantJobLog: nil, wantStepLogs: []any{ "step one log", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { logMap := getZipLogMap(tt.zipReader, []shared.Job{tt.job}) jobLogFile, ok := logMap.forJob(tt.job.ID) switch want := tt.wantJobLog.(type) { case nil: require.False(t, ok) require.Nil(t, jobLogFile) case string: require.True(t, ok) require.NotNil(t, jobLogFile) require.Equal(t, want, string(readZipFile(t, jobLogFile))) default: t.Fatal("wantJobLog must be nil or string") } for i, wantStepLog := range tt.wantStepLogs { stepLogFile, ok := logMap.forStep(tt.job.ID, 1+i) // Step numbers start from 1 switch want := wantStepLog.(type) { case nil: require.False(t, ok) require.Nil(t, stepLogFile) case string: require.True(t, ok) require.NotNil(t, stepLogFile) gotStepLog := readZipFile(t, stepLogFile) require.Equal(t, want, string(gotStepLog)) default: t.Fatal("wantStepLog must be nil or string") } } }) } } func readZipFile(t *testing.T, zf *zip.File) []byte { rc, err := zf.Open() assert.NoError(t, err) defer rc.Close() content, err := io.ReadAll(rc) assert.NoError(t, err) return content } func createZipReader(t *testing.T, files map[string]string) *zip.Reader { raw := createZipArchive(t, files) zr, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw))) assert.NoError(t, err) return zr } func createZipArchive(t *testing.T, files map[string]string) []byte { buf := bytes.NewBuffer(nil) zw := zip.NewWriter(buf) for name, content := range files { fileWriter, err := zw.Create(name) assert.NoError(t, err) _, err = fileWriter.Write([]byte(content)) assert.NoError(t, err) } err := zw.Close() assert.NoError(t, err) return buf.Bytes() }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/run/view/logs.go
pkg/cmd/run/view/logs.go
package view import ( "archive/zip" "errors" "fmt" "io" "net/http" "regexp" "slices" "sort" "strings" "unicode/utf16" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghinstance" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/run/shared" ) type logFetcher interface { GetLog() (io.ReadCloser, error) } type zipLogFetcher struct { File *zip.File } func (f *zipLogFetcher) GetLog() (io.ReadCloser, error) { return f.File.Open() } type apiLogFetcher struct { httpClient *http.Client repo ghrepo.Interface jobID int64 } func (f *apiLogFetcher) GetLog() (io.ReadCloser, error) { logURL := fmt.Sprintf("%srepos/%s/actions/jobs/%d/logs", ghinstance.RESTPrefix(f.repo.RepoHost()), ghrepo.FullName(f.repo), f.jobID) req, err := http.NewRequest("GET", logURL, nil) if err != nil { return nil, err } resp, err := f.httpClient.Do(req) if err != nil { return nil, err } if resp.StatusCode == 404 { return nil, fmt.Errorf("log not found: %v", f.jobID) } else if resp.StatusCode != 200 { return nil, api.HandleHTTPError(resp) } return resp.Body, nil } // logSegment represents a segment of a log trail, which can be either an entire // job log or an individual step log. type logSegment struct { job *shared.Job step *shared.Step fetcher logFetcher } // maxAPILogFetchers is the maximum allowed number of API log fetchers that can // be assigned to log segments. This is a heuristic limit to avoid overwhelming // the API with too many requests when fetching logs for a run with many jobs or // steps. const maxAPILogFetchers = 25 var errTooManyAPILogFetchers = errors.New("too many missing logs") // populateLogSegments populates log segments from the provided jobs and data // available in the given ZIP archive map. Any missing logs will be assigned a // log fetcher that retrieves logs from the API. // // For example, if there's no step log available in the ZIP archive, the entire // job log will be selected as a log segment. // // Note that, as heuristic approach, we only allow a limited number of API log // fetchers to be assigned. This is to avoid overwhelming the API with too many // requests. func populateLogSegments(httpClient *http.Client, repo ghrepo.Interface, jobs []shared.Job, zlm *zipLogMap, onlyFailed bool) ([]logSegment, error) { segments := make([]logSegment, 0, len(jobs)) apiLogFetcherCount := 0 for _, job := range jobs { if shared.IsSkipped(job.Conclusion) { continue } if onlyFailed && !shared.IsFailureState(job.Conclusion) { continue } stepLogAvailable := slices.ContainsFunc(job.Steps, func(step shared.Step) bool { _, ok := zlm.forStep(job.ID, step.Number) return ok }) // If at least one step log is available, we populate the segments with // them and don't use the entire job log. if stepLogAvailable { steps := slices.Clone(job.Steps) sort.Sort(steps) for _, step := range steps { if onlyFailed && !shared.IsFailureState(step.Conclusion) { continue } zf, ok := zlm.forStep(job.ID, step.Number) if !ok { // We have no step log in the zip archive, but there's nothing we can do // about that because there is no API endpoint to fetch step logs. continue } segments = append(segments, logSegment{ job: &job, step: &step, fetcher: &zipLogFetcher{File: zf}, }) } continue } segment := logSegment{job: &job} if zf, ok := zlm.forJob(job.ID); ok { segment.fetcher = &zipLogFetcher{File: zf} } else { segment.fetcher = &apiLogFetcher{ httpClient: httpClient, repo: repo, jobID: job.ID, } apiLogFetcherCount++ } segments = append(segments, segment) if apiLogFetcherCount > maxAPILogFetchers { return nil, errTooManyAPILogFetchers } } return segments, nil } // zipLogMap is a map of job and step logs available in a ZIP archive. type zipLogMap struct { jobs map[int64]*zip.File steps map[string]*zip.File } func newZipLogMap() *zipLogMap { return &zipLogMap{ jobs: make(map[int64]*zip.File), steps: make(map[string]*zip.File), } } func (l *zipLogMap) forJob(jobID int64) (*zip.File, bool) { f, ok := l.jobs[jobID] return f, ok } func (l *zipLogMap) forStep(jobID int64, stepNumber int) (*zip.File, bool) { logFetcherKey := fmt.Sprintf("%d/%d", jobID, stepNumber) f, ok := l.steps[logFetcherKey] return f, ok } func (l *zipLogMap) addStep(jobID int64, stepNumber int, zf *zip.File) { logFetcherKey := fmt.Sprintf("%d/%d", jobID, stepNumber) l.steps[logFetcherKey] = zf } func (l *zipLogMap) addJob(jobID int64, zf *zip.File) { l.jobs[jobID] = zf } // getZipLogMap populates a logs struct with appropriate log fetchers based on // the provided zip file and list of jobs. // // The structure of zip file is expected to be as: // // zip/ // ├── jobname1/ // │ ├── 1_stepname.txt // │ ├── 2_anotherstepname.txt // │ ├── 3_stepstepname.txt // │ └── 4_laststepname.txt // ├── jobname2/ // | ├── 1_stepname.txt // | └── 2_somestepname.txt // ├── 0_jobname1.txt // ├── 1_jobname2.txt // └── -9999999999_jobname3.txt // // The function iterates through the list of jobs and tries to find the matching // log file in the ZIP archive. // // The top-level .txt files include the logs for an entire job run. Note that // the prefixed number is either: // - An ordinal and cannot be mapped to the corresponding job's ID. // - A negative integer which is the ID of the job in the old Actions service. // The service right now tries to get logs and use an ordinal in a loop. // However, if it doesn't get the logs, it falls back to an old service // where the ID can apparently be negative. func getZipLogMap(rlz *zip.Reader, jobs []shared.Job) *zipLogMap { zlm := newZipLogMap() for _, job := range jobs { // So far we haven't yet encountered a ZIP containing both top-level job // logs (i.e. the normal and the legacy .txt files). However, it's still // possible. Therefore, we prioritise the normal log over the legacy one. if zf := matchFileInZIPArchive(rlz, jobLogFilenameRegexp(job)); zf != nil { zlm.addJob(job.ID, zf) } else if zf := matchFileInZIPArchive(rlz, legacyJobLogFilenameRegexp(job)); zf != nil { zlm.addJob(job.ID, zf) } for _, step := range job.Steps { if zf := matchFileInZIPArchive(rlz, stepLogFilenameRegexp(job, step)); zf != nil { zlm.addStep(job.ID, step.Number, zf) } } } return zlm } const JOB_NAME_MAX_LENGTH = 90 func getJobNameForLogFilename(name string) string { // As described in https://github.com/cli/cli/issues/5011#issuecomment-1570713070, there are a number of steps // the server can take when producing the downloaded zip file that can result in a mismatch between the job name // and the filename in the zip including: // * Removing characters in the job name that aren't allowed in file paths // * Truncating names that are too long for zip files // * Adding collision deduplicating numbers for jobs with the same name // // We are hesitant to duplicate all the server logic due to the fragility but it may be unavoidable. Currently, we: // * Strip `/` which occur when composite action job names are constructed of the form `<JOB_NAME`> / <ACTION_NAME>` // * Truncate long job names // sanitizedJobName := strings.ReplaceAll(name, "/", "") sanitizedJobName = strings.ReplaceAll(sanitizedJobName, ":", "") sanitizedJobName = truncateAsUTF16(sanitizedJobName, JOB_NAME_MAX_LENGTH) return sanitizedJobName } // A job run log file is a top-level .txt file whose name starts with an ordinal // number; e.g., "0_jobname.txt". func jobLogFilenameRegexp(job shared.Job) *regexp.Regexp { sanitizedJobName := getJobNameForLogFilename(job.Name) re := fmt.Sprintf(`^\d+_%s\.txt$`, regexp.QuoteMeta(sanitizedJobName)) return regexp.MustCompile(re) } // A legacy job run log file is a top-level .txt file whose name starts with a // negative number which is the ID of the run; e.g., "-2147483648_jobname.txt". func legacyJobLogFilenameRegexp(job shared.Job) *regexp.Regexp { sanitizedJobName := getJobNameForLogFilename(job.Name) re := fmt.Sprintf(`^-\d+_%s\.txt$`, regexp.QuoteMeta(sanitizedJobName)) return regexp.MustCompile(re) } func stepLogFilenameRegexp(job shared.Job, step shared.Step) *regexp.Regexp { sanitizedJobName := getJobNameForLogFilename(job.Name) re := fmt.Sprintf(`^%s\/%d_.*\.txt$`, regexp.QuoteMeta(sanitizedJobName), step.Number) return regexp.MustCompile(re) } /* If you're reading this comment by necessity, I'm sorry and if you're reading it for fun, you're welcome, you weirdo. What is the length of this string "a😅😅"? If you said 9 you'd be right. If you said 3 or 5 you might also be right! Here's a summary: "a" takes 1 byte (`\x61`) "😅" takes 4 `bytes` (`\xF0\x9F\x98\x85`) "a😅😅" therefore takes 9 `bytes` In Go `len("a😅😅")` is 9 because the `len` builtin counts `bytes` In Go `len([]rune("a😅😅"))` is 3 because each `rune` is 4 `bytes` so each character fits within a `rune` In C# `"a😅😅".Length` is 5 because `.Length` counts `Char` objects, `Chars` hold 2 bytes, and "😅" takes 2 Chars. But wait, what does C# have to do with anything? Well the server is running C#. Which server? The one that serves log files to us in `.zip` format of course! When the server is constructing the zip file to avoid running afoul of a 260 byte zip file path length limitation, it applies transformations to various strings in order to limit their length. In C#, the server truncates strings with this function: public static string TruncateAfter(string str, int max) { string result = str.Length > max ? str.Substring(0, max) : str; result = result.Trim(); return result; } This seems like it would be easy enough to replicate in Go but as we already discovered, the length of a string isn't as obvious as it might seem. Since C# uses UTF-16 encoding for strings, and Go uses UTF-8 encoding and represents characters by runes (which are an alias of int32) we cannot simply slice the string without any further consideration. Instead, we need to encode the string as UTF-16 bytes, slice it and then decode it back to UTF-8. Interestingly, in C# length and substring both act on the Char type so it's possible to slice into the middle of a visual, "representable" character. For example we know `"a😅😅".Length` = 5 (1+2+2) and therefore Substring(0,4) results in the final character being cleaved in two, resulting in "a😅�". Since our int32 runes are being encoded as 2 uint16 elements, we also mimic this behaviour by slicing into the UTF-16 encoded string. Here's a program you can put into a dotnet playground to see how C# works: using System; public class Program { public static void Main() { string s = "a😅😅"; Console.WriteLine("{0} {1}", s.Length, s); string t = TruncateAfter(s, 4); Console.WriteLine("{0} {1}", t.Length, t); } public static string TruncateAfter(string str, int max) { string result = str.Length > max ? str.Substring(0, max) : str; return result.Trim(); } } This will output: 5 a😅😅 4 a😅� */ func truncateAsUTF16(str string, max int) string { // Encode the string to UTF-16 to count code units utf16Encoded := utf16.Encode([]rune(str)) if len(utf16Encoded) > max { // Decode back to UTF-8 up to the max length str = string(utf16.Decode(utf16Encoded[:max])) } return strings.TrimSpace(str) } func matchFileInZIPArchive(zr *zip.Reader, re *regexp.Regexp) *zip.File { for _, file := range zr.File { if re.MatchString(file.Name) { return file } } return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/run/view/view_test.go
pkg/cmd/run/view/view_test.go
package view import ( "bytes" "fmt" "io" "net/http" "net/url" "slices" "strings" "testing" "time" "github.com/MakeNowJust/heredoc" "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/internal/ghrepo" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/pkg/cmd/run/shared" workflowShared "github.com/cli/cli/v2/pkg/cmd/workflow/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 TestNewCmdView(t *testing.T) { tests := []struct { name string cli string tty bool wants ViewOptions wantsErr bool }{ { name: "blank nontty", wantsErr: true, }, { name: "blank tty", tty: true, wants: ViewOptions{ Prompt: true, }, }, { name: "web tty", tty: true, cli: "--web", wants: ViewOptions{ Prompt: true, Web: true, }, }, { name: "web nontty", cli: "1234 --web", wants: ViewOptions{ Web: true, RunID: "1234", }, }, { name: "disallow web and log", tty: true, cli: "-w --log", wantsErr: true, }, { name: "disallow log and log-failed", tty: true, cli: "--log --log-failed", wantsErr: true, }, { name: "exit status", cli: "--exit-status 1234", wants: ViewOptions{ RunID: "1234", ExitStatus: true, }, }, { name: "verbosity", cli: "-v", tty: true, wants: ViewOptions{ Verbose: true, Prompt: true, }, }, { name: "with arg nontty", cli: "1234", wants: ViewOptions{ RunID: "1234", }, }, { name: "job id passed", cli: "--job 1234", wants: ViewOptions{ JobID: "1234", }, }, { name: "log passed", tty: true, cli: "--log", wants: ViewOptions{ Prompt: true, Log: true, }, }, { name: "tolerates both run and job id", cli: "1234 --job 4567", wants: ViewOptions{ JobID: "4567", }, }, { name: "run id with attempt", cli: "1234 --attempt 2", wants: ViewOptions{ RunID: "1234", Attempt: 2, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() ios.SetStdinTTY(tt.tty) ios.SetStdoutTTY(tt.tty) f := &cmdutil.Factory{ IOStreams: ios, Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, } argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts *ViewOptions cmd := NewCmdView(f, func(opts *ViewOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(io.Discard) cmd.SetErr(io.Discard) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) return } assert.NoError(t, err) assert.Equal(t, tt.wants.RunID, gotOpts.RunID) assert.Equal(t, tt.wants.Prompt, gotOpts.Prompt) assert.Equal(t, tt.wants.ExitStatus, gotOpts.ExitStatus) assert.Equal(t, tt.wants.Verbose, gotOpts.Verbose) assert.Equal(t, tt.wants.Attempt, gotOpts.Attempt) }) } } func TestViewRun(t *testing.T) { emptyZipArchive := createZipArchive(t, map[string]string{}) zipArchive := createZipArchive(t, map[string]string{ "0_cool job.txt": heredoc.Doc(` log line 1 log line 2 log line 3 log line 1 log line 2 log line 3`), "cool job/1_fob the barz.txt": heredoc.Doc(` log line 1 log line 2 log line 3 `), "cool job/2_barz the fob.txt": heredoc.Doc(` log line 1 log line 2 log line 3 `), "1_sad job.txt": heredoc.Doc(` log line 1 log line 2 log line 3 log line 1 log line 2 log line 3 `), "sad job/1_barf the quux.txt": heredoc.Doc(` log line 1 log line 2 log line 3 `), "sad job/2_quuz the barf.txt": heredoc.Doc(` log line 1 log line 2 log line 3 `), "2_cool job with no step logs.txt": heredoc.Doc(` log line 1 log line 2 log line 3 `), "3_sad job with no step logs.txt": heredoc.Doc(` log line 1 log line 2 log line 3 `), "-9999999999_legacy cool job with no step logs.txt": heredoc.Doc(` log line 1 log line 2 log line 3 `), "-9999999999_legacy sad job with no step logs.txt": heredoc.Doc(` log line 1 log line 2 log line 3 `), }) tests := []struct { name string httpStubs func(*httpmock.Registry) promptStubs func(*prompter.MockPrompter) opts *ViewOptions tty bool wantErr bool wantOut string browsedURL string errMsg string }{ { name: "associate with PR", tty: true, opts: &ViewOptions{ RunID: "3", Prompt: false, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3"), httpmock.JSONResponse(shared.SuccessfulRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/artifacts"), httpmock.StringResponse(`{}`)) reg.Register( httpmock.GraphQL(`query PullRequestForRun`), httpmock.StringResponse(`{"data": { "repository": { "pullRequests": { "nodes": [ {"number": 2898, "headRepository": { "owner": { "login": "OWNER" }, "name": "REPO"}} ]}}}}`)) reg.Register( httpmock.REST("GET", "runs/3/jobs"), httpmock.JSONResponse(shared.JobsPayload{ Jobs: []shared.Job{ shared.SuccessfulJob, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/check-runs/10/annotations"), httpmock.JSONResponse([]shared.Annotation{})) }, wantOut: "\n✓ trunk CI OWNER/REPO#2898 · 3\nTriggered via push about 59 minutes ago\n\nJOBS\n✓ cool job in 4m34s (ID 10)\n\nFor more information about the job, try: gh run view --job=10\nView this run on GitHub: https://github.com/runs/3\n", }, { name: "associate with PR with attempt", tty: true, opts: &ViewOptions{ RunID: "3", Attempt: 3, Prompt: false, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/attempts/3"), httpmock.JSONResponse(shared.SuccessfulRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/artifacts"), httpmock.StringResponse(`{}`)) reg.Register( httpmock.GraphQL(`query PullRequestForRun`), httpmock.StringResponse(`{"data": { "repository": { "pullRequests": { "nodes": [ {"number": 2898, "headRepository": { "owner": { "login": "OWNER" }, "name": "REPO"}} ]}}}}`)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/attempts/3/jobs"), httpmock.JSONResponse(shared.JobsPayload{ Jobs: []shared.Job{ shared.SuccessfulJob, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/check-runs/10/annotations"), httpmock.JSONResponse([]shared.Annotation{})) }, wantOut: "\n✓ trunk CI OWNER/REPO#2898 · 3 (Attempt #3)\nTriggered via push about 59 minutes ago\n\nJOBS\n✓ cool job in 4m34s (ID 10)\n\nFor more information about the job, try: gh run view --job=10\nView this run on GitHub: https://github.com/runs/3/attempts/3\n", }, { name: "exit status, failed run", opts: &ViewOptions{ RunID: "1234", ExitStatus: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234"), httpmock.JSONResponse(shared.FailedRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234/artifacts"), httpmock.StringResponse(`{}`)) reg.Register( httpmock.GraphQL(`query PullRequestForRun`), httpmock.StringResponse(``)) reg.Register( httpmock.REST("GET", "runs/1234/jobs"), httpmock.JSONResponse(shared.JobsPayload{ Jobs: []shared.Job{ shared.FailedJob, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/check-runs/20/annotations"), httpmock.JSONResponse(shared.FailedJobAnnotations)) }, wantOut: "\nX trunk CI · 1234\nTriggered via push about 59 minutes ago\n\nJOBS\nX sad job in 4m34s (ID 20)\n ✓ barf the quux\n X quux the barf\n\nANNOTATIONS\nX the job is sad\nsad job: blaze.py#420\n\n\nTo see what failed, try: gh run view 1234 --log-failed\nView this run on GitHub: https://github.com/runs/1234\n", wantErr: true, }, { name: "with artifacts", opts: &ViewOptions{ RunID: "3", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3"), httpmock.JSONResponse(shared.SuccessfulRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/artifacts"), httpmock.JSONResponse(map[string][]shared.Artifact{ "artifacts": { shared.Artifact{Name: "artifact-1", Expired: false}, shared.Artifact{Name: "artifact-2", Expired: true}, shared.Artifact{Name: "artifact-3", Expired: false}, }, })) reg.Register( httpmock.GraphQL(`query PullRequestForRun`), httpmock.StringResponse(``)) reg.Register( httpmock.REST("GET", "runs/3/jobs"), httpmock.JSONResponse(shared.JobsPayload{})) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) }, wantOut: heredoc.Doc(` ✓ trunk CI · 3 Triggered via push about 59 minutes ago JOBS ARTIFACTS artifact-1 artifact-2 (expired) artifact-3 For more information about a job, try: gh run view --job=<job-id> View this run on GitHub: https://github.com/runs/3 `), }, { name: "with artifacts and attempt", opts: &ViewOptions{ RunID: "3", Attempt: 3, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/attempts/3"), httpmock.JSONResponse(shared.SuccessfulRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/artifacts"), httpmock.JSONResponse(map[string][]shared.Artifact{ "artifacts": { shared.Artifact{Name: "artifact-1", Expired: false}, shared.Artifact{Name: "artifact-2", Expired: true}, shared.Artifact{Name: "artifact-3", Expired: false}, }, })) reg.Register( httpmock.GraphQL(`query PullRequestForRun`), httpmock.StringResponse(``)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/attempts/3/jobs"), httpmock.JSONResponse(shared.JobsPayload{})) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) }, wantOut: heredoc.Doc(` ✓ trunk CI · 3 (Attempt #3) Triggered via push about 59 minutes ago JOBS ARTIFACTS artifact-1 artifact-2 (expired) artifact-3 For more information about a job, try: gh run view --job=<job-id> View this run on GitHub: https://github.com/runs/3/attempts/3 `), }, { name: "exit status, successful run", opts: &ViewOptions{ RunID: "3", ExitStatus: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3"), httpmock.JSONResponse(shared.SuccessfulRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/artifacts"), httpmock.StringResponse(`{}`)) reg.Register( httpmock.GraphQL(`query PullRequestForRun`), httpmock.StringResponse(``)) reg.Register( httpmock.REST("GET", "runs/3/jobs"), httpmock.JSONResponse(shared.JobsPayload{ Jobs: []shared.Job{ shared.SuccessfulJob, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/check-runs/10/annotations"), httpmock.JSONResponse([]shared.Annotation{})) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) }, wantOut: "\n✓ trunk CI · 3\nTriggered via push about 59 minutes ago\n\nJOBS\n✓ cool job in 4m34s (ID 10)\n\nFor more information about the job, try: gh run view --job=10\nView this run on GitHub: https://github.com/runs/3\n", }, { name: "exit status, successful run, with attempt", opts: &ViewOptions{ RunID: "3", Attempt: 3, ExitStatus: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/attempts/3"), httpmock.JSONResponse(shared.SuccessfulRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/artifacts"), httpmock.StringResponse(`{}`)) reg.Register( httpmock.GraphQL(`query PullRequestForRun`), httpmock.StringResponse(``)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/attempts/3/jobs"), httpmock.JSONResponse(shared.JobsPayload{ Jobs: []shared.Job{ shared.SuccessfulJob, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/check-runs/10/annotations"), httpmock.JSONResponse([]shared.Annotation{})) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) }, wantOut: "\n✓ trunk CI · 3 (Attempt #3)\nTriggered via push about 59 minutes ago\n\nJOBS\n✓ cool job in 4m34s (ID 10)\n\nFor more information about the job, try: gh run view --job=10\nView this run on GitHub: https://github.com/runs/3/attempts/3\n", }, { name: "verbose", tty: true, opts: &ViewOptions{ RunID: "1234", Prompt: false, Verbose: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234"), httpmock.JSONResponse(shared.FailedRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234/artifacts"), httpmock.StringResponse(`{}`)) reg.Register( httpmock.GraphQL(`query PullRequestForRun`), httpmock.StringResponse(``)) reg.Register( httpmock.REST("GET", "runs/1234/jobs"), httpmock.JSONResponse(shared.JobsPayload{ Jobs: []shared.Job{ shared.SuccessfulJob, shared.FailedJob, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/check-runs/10/annotations"), httpmock.JSONResponse([]shared.Annotation{})) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/check-runs/20/annotations"), httpmock.JSONResponse(shared.FailedJobAnnotations)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) }, wantOut: "\nX trunk CI · 1234\nTriggered via push about 59 minutes ago\n\nJOBS\n✓ cool job in 4m34s (ID 10)\n ✓ fob the barz\n ✓ barz the fob\nX sad job in 4m34s (ID 20)\n ✓ barf the quux\n X quux the barf\n\nANNOTATIONS\nX the job is sad\nsad job: blaze.py#420\n\n\nTo see what failed, try: gh run view 1234 --log-failed\nView this run on GitHub: https://github.com/runs/1234\n", }, { name: "prompts for choice, one job", tty: true, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"), httpmock.JSONResponse(shared.RunsPayload{ WorkflowRuns: shared.TestRuns, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3"), httpmock.JSONResponse(shared.SuccessfulRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/artifacts"), httpmock.StringResponse(`{}`)) reg.Register( httpmock.GraphQL(`query PullRequestForRun`), httpmock.StringResponse(``)) reg.Register( httpmock.REST("GET", "runs/3/jobs"), httpmock.JSONResponse(shared.JobsPayload{ Jobs: []shared.Job{ shared.SuccessfulJob, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/check-runs/10/annotations"), httpmock.JSONResponse([]shared.Annotation{})) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ shared.TestWorkflow, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) }, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterSelect("Select a workflow run", []string{"X cool commit, CI [trunk] Feb 23, 2021", "* cool commit, CI [trunk] Feb 23, 2021", "✓ cool commit, CI [trunk] Feb 23, 2021", "X cool commit, CI [trunk] Feb 23, 2021", "X cool commit, CI [trunk] Feb 23, 2021", "- cool commit, CI [trunk] Feb 23, 2021", "- cool commit, CI [trunk] Feb 23, 2021", "* cool commit, CI [trunk] Feb 23, 2021", "* cool commit, CI [trunk] Feb 23, 2021", "X cool commit, CI [trunk] Feb 23, 2021"}, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "✓ cool commit, CI [trunk] Feb 23, 2021") }) }, opts: &ViewOptions{ Prompt: true, }, wantOut: "\n✓ trunk CI · 3\nTriggered via push about 59 minutes ago\n\nJOBS\n✓ cool job in 4m34s (ID 10)\n\nFor more information about the job, try: gh run view --job=10\nView this run on GitHub: https://github.com/runs/3\n", }, { name: "interactive with log", tty: true, opts: &ViewOptions{ Prompt: true, Log: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"), httpmock.JSONResponse(shared.RunsPayload{ WorkflowRuns: shared.TestRuns, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3"), httpmock.JSONResponse(shared.SuccessfulRun)) reg.Register( httpmock.REST("GET", "runs/3/jobs"), httpmock.JSONResponse(shared.JobsPayload{ Jobs: []shared.Job{ shared.SuccessfulJob, shared.FailedJob, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/logs"), httpmock.BinaryResponse(zipArchive)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ shared.TestWorkflow, }, })) }, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterSelect("Select a workflow run", []string{"X cool commit, CI [trunk] Feb 23, 2021", "* cool commit, CI [trunk] Feb 23, 2021", "✓ cool commit, CI [trunk] Feb 23, 2021", "X cool commit, CI [trunk] Feb 23, 2021", "X cool commit, CI [trunk] Feb 23, 2021", "- cool commit, CI [trunk] Feb 23, 2021", "- cool commit, CI [trunk] Feb 23, 2021", "* cool commit, CI [trunk] Feb 23, 2021", "* cool commit, CI [trunk] Feb 23, 2021", "X cool commit, CI [trunk] Feb 23, 2021"}, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "✓ cool commit, CI [trunk] Feb 23, 2021") }) pm.RegisterSelect("View a specific job in this run?", []string{"View all jobs in this run", "✓ cool job", "X sad job"}, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "✓ cool job") }) }, wantOut: coolJobRunLogOutput, }, { name: "interactive with log and attempt", tty: true, opts: &ViewOptions{ Prompt: true, Attempt: 3, Log: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"), httpmock.JSONResponse(shared.RunsPayload{ WorkflowRuns: shared.TestRuns, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/attempts/3"), httpmock.JSONResponse(shared.SuccessfulRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/attempts/3/jobs"), httpmock.JSONResponse(shared.JobsPayload{ Jobs: []shared.Job{ shared.SuccessfulJob, shared.FailedJob, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/attempts/3/logs"), httpmock.BinaryResponse(zipArchive)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ shared.TestWorkflow, }, })) }, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterSelect("Select a workflow run", []string{"X cool commit, CI [trunk] Feb 23, 2021", "* cool commit, CI [trunk] Feb 23, 2021", "✓ cool commit, CI [trunk] Feb 23, 2021", "X cool commit, CI [trunk] Feb 23, 2021", "X cool commit, CI [trunk] Feb 23, 2021", "- cool commit, CI [trunk] Feb 23, 2021", "- cool commit, CI [trunk] Feb 23, 2021", "* cool commit, CI [trunk] Feb 23, 2021", "* cool commit, CI [trunk] Feb 23, 2021", "X cool commit, CI [trunk] Feb 23, 2021"}, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "✓ cool commit, CI [trunk] Feb 23, 2021") }) pm.RegisterSelect("View a specific job in this run?", []string{"View all jobs in this run", "✓ cool job", "X sad job"}, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "✓ cool job") }) }, wantOut: coolJobRunLogOutput, }, { name: "noninteractive with log", opts: &ViewOptions{ JobID: "10", Log: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/jobs/10"), httpmock.JSONResponse(shared.SuccessfulJob)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3"), httpmock.JSONResponse(shared.SuccessfulRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/logs"), httpmock.BinaryResponse(zipArchive)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) }, wantOut: coolJobRunLogOutput, }, { name: "noninteractive with log and attempt", opts: &ViewOptions{ JobID: "10", Attempt: 3, Log: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/jobs/10"), httpmock.JSONResponse(shared.SuccessfulJob)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/attempts/3"), httpmock.JSONResponse(shared.SuccessfulRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/attempts/3/logs"), httpmock.BinaryResponse(zipArchive)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) }, wantOut: coolJobRunLogOutput, }, { name: "interactive with run log", tty: true, opts: &ViewOptions{ Prompt: true, Log: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"), httpmock.JSONResponse(shared.RunsPayload{ WorkflowRuns: shared.TestRuns, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3"), httpmock.JSONResponse(shared.SuccessfulRun)) reg.Register( httpmock.REST("GET", "runs/3/jobs"), httpmock.JSONResponse(shared.JobsPayload{ Jobs: []shared.Job{ shared.SuccessfulJob, shared.FailedJob, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/logs"), httpmock.BinaryResponse(zipArchive)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ shared.TestWorkflow, }, })) }, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterSelect("Select a workflow run", []string{"X cool commit, CI [trunk] Feb 23, 2021", "* cool commit, CI [trunk] Feb 23, 2021", "✓ cool commit, CI [trunk] Feb 23, 2021", "X cool commit, CI [trunk] Feb 23, 2021", "X cool commit, CI [trunk] Feb 23, 2021", "- cool commit, CI [trunk] Feb 23, 2021", "- cool commit, CI [trunk] Feb 23, 2021", "* cool commit, CI [trunk] Feb 23, 2021", "* cool commit, CI [trunk] Feb 23, 2021", "X cool commit, CI [trunk] Feb 23, 2021"}, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "✓ cool commit, CI [trunk] Feb 23, 2021") }) pm.RegisterSelect("View a specific job in this run?", []string{"View all jobs in this run", "✓ cool job", "X sad job"}, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "View all jobs in this run") }) }, wantOut: expectedRunLogOutput, }, { name: "noninteractive with run log", tty: true, opts: &ViewOptions{ RunID: "3", Log: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3"), httpmock.JSONResponse(shared.SuccessfulRun)) reg.Register( httpmock.REST("GET", "runs/3/jobs"), httpmock.JSONResponse(shared.JobsPayload{ Jobs: []shared.Job{ shared.SuccessfulJob, shared.FailedJob, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/3/logs"), httpmock.BinaryResponse(zipArchive)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) }, wantOut: expectedRunLogOutput, }, { name: "interactive with log-failed", tty: true, opts: &ViewOptions{ Prompt: true, LogFailed: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"), httpmock.JSONResponse(shared.RunsPayload{ WorkflowRuns: shared.TestRuns, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234"), httpmock.JSONResponse(shared.FailedRun)) reg.Register( httpmock.REST("GET", "runs/1234/jobs"), httpmock.JSONResponse(shared.JobsPayload{ Jobs: []shared.Job{ shared.SuccessfulJob, shared.FailedJob, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234/logs"), httpmock.BinaryResponse(zipArchive)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ shared.TestWorkflow, }, })) }, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterSelect("Select a workflow run", []string{"X cool commit, CI [trunk] Feb 23, 2021", "* cool commit, CI [trunk] Feb 23, 2021", "✓ cool commit, CI [trunk] Feb 23, 2021", "X cool commit, CI [trunk] Feb 23, 2021", "X cool commit, CI [trunk] Feb 23, 2021", "- cool commit, CI [trunk] Feb 23, 2021", "- cool commit, CI [trunk] Feb 23, 2021", "* cool commit, CI [trunk] Feb 23, 2021", "* cool commit, CI [trunk] Feb 23, 2021", "X cool commit, CI [trunk] Feb 23, 2021"}, func(_, _ string, opts []string) (int, error) { return 4, nil }) pm.RegisterSelect("View a specific job in this run?", []string{"View all jobs in this run", "✓ cool job", "X sad job"}, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "X sad job") }) }, wantOut: quuxTheBarfLogOutput, }, { name: "interactive with log-failed with attempt", tty: true, opts: &ViewOptions{ Prompt: true, Attempt: 3, LogFailed: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"), httpmock.JSONResponse(shared.RunsPayload{ WorkflowRuns: shared.TestRuns, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234/attempts/3"), httpmock.JSONResponse(shared.FailedRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234/attempts/3/jobs"), httpmock.JSONResponse(shared.JobsPayload{ Jobs: []shared.Job{ shared.SuccessfulJob, shared.FailedJob, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234/attempts/3/logs"), httpmock.BinaryResponse(zipArchive)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ shared.TestWorkflow, }, })) }, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterSelect("Select a workflow run", []string{"X cool commit, CI [trunk] Feb 23, 2021", "* cool commit, CI [trunk] Feb 23, 2021", "✓ cool commit, CI [trunk] Feb 23, 2021", "X cool commit, CI [trunk] Feb 23, 2021", "X cool commit, CI [trunk] Feb 23, 2021", "- cool commit, CI [trunk] Feb 23, 2021", "- cool commit, CI [trunk] Feb 23, 2021", "* cool commit, CI [trunk] Feb 23, 2021", "* cool commit, CI [trunk] Feb 23, 2021", "X cool commit, CI [trunk] Feb 23, 2021"}, func(_, _ string, opts []string) (int, error) { return 4, nil }) pm.RegisterSelect("View a specific job in this run?", []string{"View all jobs in this run", "✓ cool job", "X sad job"}, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "X sad job") }) }, wantOut: quuxTheBarfLogOutput, }, { name: "noninteractive with log-failed", opts: &ViewOptions{ JobID: "20", LogFailed: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/jobs/20"), httpmock.JSONResponse(shared.FailedJob)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234"), httpmock.JSONResponse(shared.FailedRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234/logs"), httpmock.BinaryResponse(zipArchive)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) }, wantOut: quuxTheBarfLogOutput, }, { name: "interactive with run log-failed", tty: true, opts: &ViewOptions{ Prompt: true, LogFailed: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"), httpmock.JSONResponse(shared.RunsPayload{ WorkflowRuns: shared.TestRuns, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234"), httpmock.JSONResponse(shared.FailedRun)) reg.Register( httpmock.REST("GET", "runs/1234/jobs"), httpmock.JSONResponse(shared.JobsPayload{ Jobs: []shared.Job{ shared.SuccessfulJob, shared.FailedJob, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234/logs"),
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
true
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/run/watch/watch_test.go
pkg/cmd/run/watch/watch_test.go
package watch import ( "bytes" "io" "net/http" "testing" "time" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/pkg/cmd/run/shared" workflowShared "github.com/cli/cli/v2/pkg/cmd/workflow/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/go-gh/v2/pkg/api" "github.com/google/shlex" "github.com/stretchr/testify/assert" ) func TestNewCmdWatch(t *testing.T) { tests := []struct { name string cli string tty bool wants WatchOptions wantsErr bool }{ { name: "blank nontty", wantsErr: true, }, { name: "blank tty", tty: true, wants: WatchOptions{ Prompt: true, Interval: defaultInterval, }, }, { name: "interval", tty: true, cli: "-i10", wants: WatchOptions{ Interval: 10, Prompt: true, }, }, { name: "exit status", cli: "1234 --exit-status", wants: WatchOptions{ Interval: defaultInterval, RunID: "1234", ExitStatus: true, }, }, { name: "compact status", cli: "1234 --compact", wants: WatchOptions{ Interval: defaultInterval, RunID: "1234", Compact: true, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() ios.SetStdinTTY(tt.tty) ios.SetStdoutTTY(tt.tty) f := &cmdutil.Factory{ IOStreams: ios, } argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts *WatchOptions cmd := NewCmdWatch(f, func(opts *WatchOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(io.Discard) cmd.SetErr(io.Discard) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) return } assert.NoError(t, err) assert.Equal(t, tt.wants.RunID, gotOpts.RunID) assert.Equal(t, tt.wants.Prompt, gotOpts.Prompt) assert.Equal(t, tt.wants.ExitStatus, gotOpts.ExitStatus) assert.Equal(t, tt.wants.Interval, gotOpts.Interval) }) } } func TestWatchRun(t *testing.T) { failedRunStubs := func(reg *httpmock.Registry) { inProgressRun := shared.TestRunWithCommit(2, shared.InProgress, "", "commit2") completedRun := shared.TestRun(2, shared.Completed, shared.Failure) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"), httpmock.JSONResponse(shared.RunsPayload{ WorkflowRuns: []shared.Run{ shared.TestRunWithCommit(1, shared.InProgress, "", "commit1"), inProgressRun, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/2"), httpmock.JSONResponse(inProgressRun)) reg.Register( httpmock.REST("GET", "runs/2/jobs"), httpmock.JSONResponse(shared.JobsPayload{ Jobs: []shared.Job{}})) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/2"), httpmock.JSONResponse(completedRun)) reg.Register( httpmock.REST("GET", "runs/2/jobs"), httpmock.JSONResponse(shared.JobsPayload{ Jobs: []shared.Job{ shared.FailedJob, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/check-runs/20/annotations"), httpmock.JSONResponse(shared.FailedJobAnnotations)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ shared.TestWorkflow, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) } successfulRunStubs := func(reg *httpmock.Registry) { inProgressRun := shared.TestRunWithCommit(2, shared.InProgress, "", "commit2") completedRun := shared.TestRun(2, shared.Completed, shared.Success) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"), httpmock.JSONResponse(shared.RunsPayload{ WorkflowRuns: []shared.Run{ shared.TestRunWithCommit(1, shared.InProgress, "", "commit1"), inProgressRun, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/2"), httpmock.JSONResponse(inProgressRun)) reg.Register( httpmock.REST("GET", "runs/2/jobs"), httpmock.JSONResponse(shared.JobsPayload{ Jobs: []shared.Job{ shared.SuccessfulJob, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/check-runs/10/annotations"), httpmock.JSONResponse([]shared.Annotation{})) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/2"), httpmock.JSONResponse(completedRun)) reg.Register( httpmock.REST("GET", "runs/2/jobs"), httpmock.JSONResponse(shared.JobsPayload{ Jobs: []shared.Job{ shared.SuccessfulJob, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ shared.TestWorkflow, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) } tests := []struct { name string httpStubs func(*httpmock.Registry) promptStubs func(*prompter.MockPrompter) opts *WatchOptions tty bool wantErr bool errMsg string wantOut string }{ { name: "run ID provided run already completed", opts: &WatchOptions{ RunID: "1234", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234"), httpmock.JSONResponse(shared.FailedRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) }, wantOut: "Run CI (1234) has already completed with 'failure'\n", }, { name: "already completed, exit status", opts: &WatchOptions{ RunID: "1234", ExitStatus: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234"), httpmock.JSONResponse(shared.FailedRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) }, wantOut: "Run CI (1234) has already completed with 'failure'\n", wantErr: true, errMsg: "SilentError", }, { name: "prompt, no in progress runs", tty: true, opts: &WatchOptions{ Prompt: true, }, wantErr: true, errMsg: "found no in progress runs to watch", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs"), httpmock.JSONResponse(shared.RunsPayload{ WorkflowRuns: []shared.Run{ shared.FailedRun, shared.SuccessfulRun, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(workflowShared.WorkflowsPayload{ Workflows: []workflowShared.Workflow{ shared.TestWorkflow, }, })) }, }, { name: "interval respected", tty: true, opts: &WatchOptions{ Interval: 0, Prompt: true, }, httpStubs: successfulRunStubs, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterSelect("Select a workflow run", []string{"* commit1, CI [trunk] Feb 23, 2021", "* commit2, CI [trunk] Feb 23, 2021"}, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "* commit2, CI [trunk] Feb 23, 2021") }) }, wantOut: "\x1b[?1049h\x1b[0;0H\x1b[JRefreshing run status every 0 seconds. Press Ctrl+C to quit.\n\n* trunk CI · 2\nTriggered via push about 59 minutes ago\n\nJOBS\n✓ cool job in 4m34s (ID 10)\n ✓ fob the barz\n ✓ barz the fob\n\x1b[?1049l✓ trunk CI · 2\nTriggered via push about 59 minutes ago\n\nJOBS\n✓ cool job in 4m34s (ID 10)\n ✓ fob the barz\n ✓ barz the fob\n\n✓ Run CI (2) completed with 'success'\n", }, { name: "exit status respected", tty: true, opts: &WatchOptions{ Interval: 0, Prompt: true, ExitStatus: true, }, httpStubs: failedRunStubs, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterSelect("Select a workflow run", []string{"* commit1, CI [trunk] Feb 23, 2021", "* commit2, CI [trunk] Feb 23, 2021"}, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "* commit2, CI [trunk] Feb 23, 2021") }) }, wantOut: "\x1b[?1049h\x1b[0;0H\x1b[JRefreshing run status every 0 seconds. Press Ctrl+C to quit.\n\n* trunk CI · 2\nTriggered via push about 59 minutes ago\n\n\x1b[?1049lX trunk CI · 2\nTriggered via push about 59 minutes ago\n\nJOBS\nX sad job in 4m34s (ID 20)\n ✓ barf the quux\n X quux the barf\n\nANNOTATIONS\nX the job is sad\nsad job: blaze.py#420\n\n\nX Run CI (2) completed with 'failure'\n", wantErr: true, errMsg: "SilentError", }, { name: "failed to get run status", tty: true, opts: &WatchOptions{ RunID: "1234", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234"), httpmock.JSONResponse(shared.TestRunWithCommit(1234, shared.InProgress, "", "commit2")), ) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow), ) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/1234"), httpmock.JSONErrorResponse(404, api.HTTPError{ StatusCode: 404, Message: "run 1234 not found", }), ) }, wantOut: "\x1b[?1049h\x1b[?1049l", wantErr: true, errMsg: "failed to get run: HTTP 404: run 1234 not found (https://api.github.com/repos/OWNER/REPO/actions/runs/1234?exclude_pull_requests=true)", }, { name: "annotation endpoint forbidden (fine grained tokens)", tty: true, opts: &WatchOptions{ RunID: "2", }, httpStubs: func(reg *httpmock.Registry) { inProgressRun := shared.TestRunWithCommit(2, shared.InProgress, "", "commit2") completedRun := shared.TestRun(2, shared.Completed, shared.Success) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/2"), httpmock.JSONResponse(inProgressRun)) reg.Register( httpmock.REST("GET", "runs/2/jobs"), httpmock.JSONResponse(shared.JobsPayload{ Jobs: []shared.Job{ shared.SuccessfulJob, shared.FailedJob, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/check-runs/10/annotations"), httpmock.JSONResponse(shared.SuccessfulJobAnnotations)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/check-runs/20/annotations"), httpmock.StatusStringResponse(403, "Forbidden")) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/2"), httpmock.JSONResponse(completedRun)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.TestWorkflow)) }, wantOut: "\x1b[?1049h\x1b[?1049l✓ trunk CI · 2\nTriggered via push about 59 minutes ago\n\nJOBS\n✓ cool job in 4m34s (ID 10)\n ✓ fob the barz\n ✓ barz the fob\nX sad job in 4m34s (ID 20)\n ✓ barf the quux\n X quux the barf\n\nANNOTATIONS\nrequesting annotations returned 403 Forbidden as the token does not have sufficient permissions. Note that it is not currently possible to create a fine-grained PAT with the `checks:read` permission.\n✓ Run CI (2) completed with 'success'\n", }, } for _, tt := range tests { reg := &httpmock.Registry{} tt.httpStubs(reg) tt.opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } tt.opts.Now = func() time.Time { notnow, _ := time.Parse("2006-01-02 15:04:05", "2021-02-23 05:50:00") return notnow } ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(tt.tty) ios.SetAlternateScreenBufferEnabled(tt.tty) tt.opts.IO = ios tt.opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.FromFullName("OWNER/REPO") } t.Run(tt.name, func(t *testing.T) { pm := prompter.NewMockPrompter(t) tt.opts.Prompter = pm if tt.promptStubs != nil { tt.promptStubs(pm) } err := watchRun(tt.opts) if tt.wantErr { assert.EqualError(t, err, tt.errMsg) } else { assert.NoError(t, err) } // avoiding using `assert.Equal` here because it would print raw escape sequences to stdout if got := stdout.String(); got != tt.wantOut { t.Errorf("got stdout:\n%q\nwant:\n%q", got, tt.wantOut) } reg.Verify(t) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/run/watch/watch.go
pkg/cmd/run/watch/watch.go
package watch import ( "bytes" "fmt" "io" "net/http" "time" "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/run/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) const defaultInterval int = 3 type WatchOptions struct { IO *iostreams.IOStreams HttpClient func() (*http.Client, error) BaseRepo func() (ghrepo.Interface, error) Prompter shared.Prompter RunID string Interval int ExitStatus bool Compact bool Prompt bool Now func() time.Time } func NewCmdWatch(f *cmdutil.Factory, runF func(*WatchOptions) error) *cobra.Command { opts := &WatchOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, Prompter: f.Prompter, Now: time.Now, } cmd := &cobra.Command{ Use: "watch <run-id>", Short: "Watch a run until it completes, showing its progress", Long: heredoc.Docf(` Watch a run until it completes, showing its progress. By default, all steps are displayed. The %[1]s--compact%[1]s option can be used to only show the relevant/failed steps. This command does not support authenticating via fine grained PATs as it is not currently possible to create a PAT with the %[1]schecks:read%[1]s permission. `, "`"), Example: heredoc.Doc(` # Watch a run until it's done $ gh run watch # Watch a run in compact mode $ gh run watch --compact # Run some other command when the run is finished $ gh run watch && notify-send 'run is done!' `), RunE: func(cmd *cobra.Command, args []string) error { // support `-R, --repo` override opts.BaseRepo = f.BaseRepo if len(args) > 0 { opts.RunID = args[0] } else if !opts.IO.CanPrompt() { return cmdutil.FlagErrorf("run ID required when not running interactively") } else { opts.Prompt = true } if runF != nil { return runF(opts) } return watchRun(opts) }, } cmd.Flags().BoolVar(&opts.ExitStatus, "exit-status", false, "Exit with non-zero status if run fails") cmd.Flags().BoolVar(&opts.Compact, "compact", false, "Show only relevant/failed steps") cmd.Flags().IntVarP(&opts.Interval, "interval", "i", defaultInterval, "Refresh interval in seconds") return cmd } func watchRun(opts *WatchOptions) error { c, err := opts.HttpClient() if err != nil { return fmt.Errorf("failed to create http client: %w", err) } client := api.NewClientFromHTTP(c) repo, err := opts.BaseRepo() if err != nil { return fmt.Errorf("failed to determine base repo: %w", err) } cs := opts.IO.ColorScheme() runID := opts.RunID var run *shared.Run if opts.Prompt { runs, err := shared.GetRunsWithFilter(client, repo, nil, 10, func(run shared.Run) bool { return run.Status != shared.Completed }) if err != nil { return fmt.Errorf("failed to get runs: %w", err) } if len(runs) == 0 { return fmt.Errorf("found no in progress runs to watch") } if runID, err = shared.SelectRun(opts.Prompter, cs, runs); err != nil { return err } // TODO silly stopgap until dust settles and SelectRun can just return a run for _, r := range runs { if fmt.Sprintf("%d", r.ID) == runID { run = &r break } } } else { run, err = shared.GetRun(client, repo, runID, 0) if err != nil { return fmt.Errorf("failed to get run: %w", err) } } if run.Status == shared.Completed { fmt.Fprintf(opts.IO.Out, "Run %s (%s) has already completed with '%s'\n", cs.Bold(run.WorkflowName()), cs.Cyanf("%d", run.ID), run.Conclusion) if opts.ExitStatus && run.Conclusion != shared.Success { return cmdutil.SilentError } return nil } prNumber := "" number, err := shared.PullRequestForRun(client, repo, *run) if err == nil { prNumber = fmt.Sprintf(" %s#%d", ghrepo.FullName(repo), number) } annotationCache := map[int64][]shared.Annotation{} duration, err := time.ParseDuration(fmt.Sprintf("%ds", opts.Interval)) if err != nil { return fmt.Errorf("could not parse interval: %w", err) } out := &bytes.Buffer{} opts.IO.StartAlternateScreenBuffer() for run.Status != shared.Completed { // Write to a temporary buffer to reduce total number of fetches run, err = renderRun(out, *opts, client, repo, run, prNumber, annotationCache) if err != nil { break } if run.Status == shared.Completed { break } // If not completed, refresh the screen buffer and write the temporary buffer to stdout opts.IO.RefreshScreen() fmt.Fprintln(opts.IO.Out, cs.Boldf("Refreshing run status every %d seconds. Press Ctrl+C to quit.", opts.Interval)) fmt.Fprintln(opts.IO.Out) _, err = io.Copy(opts.IO.Out, out) out.Reset() if err != nil { break } time.Sleep(duration) } opts.IO.StopAlternateScreenBuffer() if err != nil { return err } // Write the last temporary buffer one last time _, err = io.Copy(opts.IO.Out, out) if err != nil { return err } symbol, symbolColor := shared.Symbol(cs, run.Status, run.Conclusion) id := cs.Cyanf("%d", run.ID) if opts.IO.IsStdoutTTY() { fmt.Fprintln(opts.IO.Out) fmt.Fprintf(opts.IO.Out, "%s Run %s (%s) completed with '%s'\n", symbolColor(symbol), cs.Bold(run.WorkflowName()), id, run.Conclusion) } if opts.ExitStatus && run.Conclusion != shared.Success { return cmdutil.SilentError } return nil } func renderRun(out io.Writer, opts WatchOptions, client *api.Client, repo ghrepo.Interface, run *shared.Run, prNumber string, annotationCache map[int64][]shared.Annotation) (*shared.Run, error) { cs := opts.IO.ColorScheme() var err error run, err = shared.GetRun(client, repo, fmt.Sprintf("%d", run.ID), 0) if err != nil { return nil, fmt.Errorf("failed to get run: %w", err) } jobs, err := shared.GetJobs(client, repo, run, 0) if err != nil { return nil, fmt.Errorf("failed to get jobs: %w", err) } var annotations []shared.Annotation var missingAnnotationsPermissions bool for _, job := range jobs { if as, ok := annotationCache[job.ID]; ok { annotations = as continue } as, err := shared.GetAnnotations(client, repo, job) if err != nil { if err != shared.ErrMissingAnnotationsPermissions { return nil, fmt.Errorf("failed to get annotations: %w", err) } missingAnnotationsPermissions = true break } annotations = append(annotations, as...) if job.Status != shared.InProgress { annotationCache[job.ID] = annotations } } fmt.Fprintln(out, shared.RenderRunHeader(cs, *run, text.FuzzyAgo(opts.Now(), run.StartedTime()), prNumber, 0)) fmt.Fprintln(out) if len(jobs) == 0 { return run, nil } fmt.Fprintln(out, cs.Bold("JOBS")) if opts.Compact { fmt.Fprintln(out, shared.RenderJobsCompact(cs, jobs)) } else { fmt.Fprintln(out, shared.RenderJobs(cs, jobs, true)) } if missingAnnotationsPermissions { fmt.Fprintln(out) fmt.Fprintln(out, cs.Bold("ANNOTATIONS")) fmt.Fprintf(out, "requesting annotations returned 403 Forbidden as the token does not have sufficient permissions. Note that it is not currently possible to create a fine-grained PAT with the `checks:read` permission.") } else if len(annotations) > 0 { fmt.Fprintln(out) fmt.Fprintln(out, cs.Bold("ANNOTATIONS")) fmt.Fprintln(out, shared.RenderAnnotations(cs, annotations)) } return run, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/run/shared/shared_test.go
pkg/cmd/run/shared/shared_test.go
package shared import ( "bytes" "encoding/json" "net/http" "strings" "testing" "time" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/httpmock" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestPreciseAgo(t *testing.T) { const form = "2006-Jan-02 15:04:05" now, _ := time.Parse(form, "2021-Apr-12 14:00:00") cases := map[string]string{ "2021-Apr-12 14:00:00": "0s ago", "2021-Apr-12 13:59:30": "30s ago", "2021-Apr-12 13:59:00": "1m0s ago", "2021-Apr-12 13:30:15": "29m45s ago", "2021-Apr-12 13:00:00": "1h0m0s ago", "2021-Apr-12 02:30:45": "11h29m15s ago", "2021-Apr-11 14:00:00": "24h0m0s ago", "2021-Apr-01 14:00:00": "264h0m0s ago", "2021-Mar-12 14:00:00": "Mar 12, 2021", } for createdAt, expected := range cases { d, _ := time.Parse(form, createdAt) got := preciseAgo(now, d) if got != expected { t.Errorf("expected %s but got %s for %s", expected, got, createdAt) } } } func TestGetAnnotations404(t *testing.T) { reg := &httpmock.Registry{} defer reg.Verify(t) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/check-runs/123456/annotations"), httpmock.StatusStringResponse(404, "not found")) httpClient := &http.Client{Transport: reg} apiClient := api.NewClientFromHTTP(httpClient) repo := ghrepo.New("OWNER", "REPO") result, err := GetAnnotations(apiClient, repo, Job{ID: 123456, Name: "a job"}) assert.NoError(t, err) assert.Equal(t, result, []Annotation{}) } func TestRun_Duration(t *testing.T) { now, _ := time.Parse(time.RFC3339, "2022-07-20T11:22:58Z") tests := []struct { name string json string wants string }{ { name: "no run_started_at", json: heredoc.Doc(` { "created_at": "2022-07-20T11:20:13Z", "updated_at": "2022-07-20T11:21:16Z", "status": "completed" }`), wants: "1m3s", }, { name: "with run_started_at", json: heredoc.Doc(` { "created_at": "2022-07-20T11:20:13Z", "run_started_at": "2022-07-20T11:20:55Z", "updated_at": "2022-07-20T11:21:16Z", "status": "completed" }`), wants: "21s", }, { name: "in_progress", json: heredoc.Doc(` { "created_at": "2022-07-20T11:20:13Z", "run_started_at": "2022-07-20T11:20:55Z", "updated_at": "2022-07-20T11:21:16Z", "status": "in_progress" }`), wants: "2m3s", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { var r Run assert.NoError(t, json.Unmarshal([]byte(tt.json), &r)) assert.Equal(t, tt.wants, r.Duration(now).String()) }) } } func TestRunExportData(t *testing.T) { oldestStartedAt, _ := time.Parse(time.RFC3339, "2022-07-20T11:20:13Z") oldestStepStartedAt, _ := time.Parse(time.RFC3339, "2022-07-20T11:20:15Z") oldestStepCompletedAt, _ := time.Parse(time.RFC3339, "2022-07-20T11:21:10Z") oldestCompletedAt, _ := time.Parse(time.RFC3339, "2022-07-20T11:21:16Z") newestStartedAt, _ := time.Parse(time.RFC3339, "2022-07-20T11:20:55Z") newestStepStartedAt, _ := time.Parse(time.RFC3339, "2022-07-20T11:21:01Z") newestStepCompletedAt, _ := time.Parse(time.RFC3339, "2022-07-20T11:23:10Z") newestCompletedAt, _ := time.Parse(time.RFC3339, "2022-07-20T11:23:16Z") tests := []struct { name string fields []string run Run output string }{ { name: "exports workflow run's single job", fields: []string{"jobs"}, run: Run{ Jobs: []Job{ { ID: 123456, Status: "completed", Conclusion: "success", Name: "macos", Steps: []Step{ { Name: "Checkout", Status: "completed", Conclusion: "success", Number: 1, StartedAt: oldestStepStartedAt, CompletedAt: oldestStepCompletedAt, }, }, StartedAt: oldestStartedAt, CompletedAt: oldestCompletedAt, URL: "https://example.com/OWNER/REPO/actions/runs/123456", }, }, }, output: `{"jobs":[{"completedAt":"2022-07-20T11:21:16Z","conclusion":"success","databaseId":123456,"name":"macos","startedAt":"2022-07-20T11:20:13Z","status":"completed","steps":[{"completedAt":"2022-07-20T11:21:10Z","conclusion":"success","name":"Checkout","number":1,"startedAt":"2022-07-20T11:20:15Z","status":"completed"}],"url":"https://example.com/OWNER/REPO/actions/runs/123456"}]}`, }, { name: "exports workflow run's multiple jobs", fields: []string{"jobs"}, run: Run{ Jobs: []Job{ { ID: 123456, Status: "completed", Conclusion: "success", Name: "macos", Steps: []Step{ { Name: "Checkout", Status: "completed", Conclusion: "success", Number: 1, StartedAt: oldestStepStartedAt, CompletedAt: oldestStepCompletedAt, }, }, StartedAt: oldestStartedAt, CompletedAt: oldestCompletedAt, URL: "https://example.com/OWNER/REPO/actions/runs/123456", }, { ID: 234567, Status: "completed", Conclusion: "error", Name: "windows", Steps: []Step{ { Name: "Checkout", Status: "completed", Conclusion: "error", Number: 2, StartedAt: newestStepStartedAt, CompletedAt: newestStepCompletedAt, }, }, StartedAt: newestStartedAt, CompletedAt: newestCompletedAt, URL: "https://example.com/OWNER/REPO/actions/runs/234567", }, }, }, output: `{"jobs":[{"completedAt":"2022-07-20T11:21:16Z","conclusion":"success","databaseId":123456,"name":"macos","startedAt":"2022-07-20T11:20:13Z","status":"completed","steps":[{"completedAt":"2022-07-20T11:21:10Z","conclusion":"success","name":"Checkout","number":1,"startedAt":"2022-07-20T11:20:15Z","status":"completed"}],"url":"https://example.com/OWNER/REPO/actions/runs/123456"},{"completedAt":"2022-07-20T11:23:16Z","conclusion":"error","databaseId":234567,"name":"windows","startedAt":"2022-07-20T11:20:55Z","status":"completed","steps":[{"completedAt":"2022-07-20T11:23:10Z","conclusion":"error","name":"Checkout","number":2,"startedAt":"2022-07-20T11:21:01Z","status":"completed"}],"url":"https://example.com/OWNER/REPO/actions/runs/234567"}]}`, }, { name: "exports workflow run with attempt count", fields: []string{"attempt"}, run: Run{ Attempt: 1, Jobs: []Job{}, }, output: `{"attempt":1}`, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { exported := tt.run.ExportData(tt.fields) buf := bytes.Buffer{} enc := json.NewEncoder(&buf) require.NoError(t, enc.Encode(exported)) assert.Equal(t, tt.output, strings.TrimSpace(buf.String())) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/run/shared/presentation.go
pkg/cmd/run/shared/presentation.go
package shared import ( "fmt" "strings" "github.com/cli/cli/v2/pkg/iostreams" ) func RenderRunHeader(cs *iostreams.ColorScheme, run Run, ago, prNumber string, attempt uint64) string { title := fmt.Sprintf("%s %s%s", cs.Bold(run.HeadBranch), run.WorkflowName(), prNumber) symbol, symbolColor := Symbol(cs, run.Status, run.Conclusion) id := cs.Cyanf("%d", run.ID) attemptLabel := "" if attempt > 0 { attemptLabel = fmt.Sprintf(" (Attempt #%d)", attempt) } header := "" header += fmt.Sprintf("%s %s · %s%s\n", symbolColor(symbol), title, id, attemptLabel) header += fmt.Sprintf("Triggered via %s %s", run.Event, ago) return header } func RenderJobs(cs *iostreams.ColorScheme, jobs []Job, verbose bool) string { lines := []string{} for _, job := range jobs { elapsed := job.CompletedAt.Sub(job.StartedAt) elapsedStr := fmt.Sprintf(" in %s", elapsed) if elapsed < 0 { elapsedStr = "" } symbol, symbolColor := Symbol(cs, job.Status, job.Conclusion) id := cs.Cyanf("%d", job.ID) lines = append(lines, fmt.Sprintf("%s %s%s (ID %s)", symbolColor(symbol), cs.Bold(job.Name), elapsedStr, id)) if verbose || IsFailureState(job.Conclusion) { for _, step := range job.Steps { stepSymbol, stepSymColor := Symbol(cs, step.Status, step.Conclusion) lines = append(lines, fmt.Sprintf(" %s %s", stepSymColor(stepSymbol), step.Name)) } } } return strings.Join(lines, "\n") } func RenderJobsCompact(cs *iostreams.ColorScheme, jobs []Job) string { lines := []string{} for _, job := range jobs { elapsed := job.CompletedAt.Sub(job.StartedAt) elapsedStr := fmt.Sprintf(" in %s", elapsed) if elapsed < 0 { elapsedStr = "" } symbol, symbolColor := Symbol(cs, job.Status, job.Conclusion) id := cs.Cyanf("%d", job.ID) lines = append(lines, fmt.Sprintf("%s %s%s (ID %s)", symbolColor(symbol), cs.Bold(job.Name), elapsedStr, id)) if job.Status == Completed && job.Conclusion == Success { continue } var inProgressStepLine string var failedStepLines []string for _, step := range job.Steps { stepSymbol, stepSymColor := Symbol(cs, step.Status, step.Conclusion) stepLine := fmt.Sprintf(" %s %s", stepSymColor(stepSymbol), step.Name) if IsFailureState(step.Conclusion) { failedStepLines = append(failedStepLines, stepLine) } if step.Status == InProgress { inProgressStepLine = stepLine } } lines = append(lines, failedStepLines...) if inProgressStepLine != "" { lines = append(lines, inProgressStepLine) } } return strings.Join(lines, "\n") } func RenderAnnotations(cs *iostreams.ColorScheme, annotations []Annotation) string { lines := []string{} for _, a := range annotations { lines = append(lines, fmt.Sprintf("%s %s", AnnotationSymbol(cs, a), a.Message)) // Following newline is essential for spacing between annotations lines = append(lines, cs.Mutedf("%s: %s#%d\n", a.JobName, a.Path, a.StartLine)) } return strings.Join(lines, "\n") }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/run/shared/artifacts.go
pkg/cmd/run/shared/artifacts.go
package shared import ( "encoding/json" "fmt" "net/http" "regexp" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghinstance" "github.com/cli/cli/v2/internal/ghrepo" ) type Artifact struct { Name string `json:"name"` Size uint64 `json:"size_in_bytes"` DownloadURL string `json:"archive_download_url"` Expired bool `json:"expired"` } type artifactsPayload struct { Artifacts []Artifact } func ListArtifacts(httpClient *http.Client, repo ghrepo.Interface, runID string) ([]Artifact, error) { var results []Artifact perPage := 100 path := fmt.Sprintf("repos/%s/%s/actions/artifacts?per_page=%d", repo.RepoOwner(), repo.RepoName(), perPage) if runID != "" { path = fmt.Sprintf("repos/%s/%s/actions/runs/%s/artifacts?per_page=%d", repo.RepoOwner(), repo.RepoName(), runID, perPage) } url := fmt.Sprintf("%s%s", ghinstance.RESTPrefix(repo.RepoHost()), path) for { var payload artifactsPayload nextURL, err := apiGet(httpClient, url, &payload) if err != nil { return nil, err } results = append(results, payload.Artifacts...) if nextURL == "" { break } url = nextURL } return results, nil } func apiGet(httpClient *http.Client, url string, data interface{}) (string, error) { req, err := http.NewRequest("GET", url, nil) if err != nil { return "", err } resp, err := httpClient.Do(req) if err != nil { return "", err } defer resp.Body.Close() if resp.StatusCode > 299 { return "", api.HandleHTTPError(resp) } dec := json.NewDecoder(resp.Body) if err := dec.Decode(data); err != nil { return "", err } return findNextPage(resp), nil } var linkRE = regexp.MustCompile(`<([^>]+)>;\s*rel="([^"]+)"`) func findNextPage(resp *http.Response) string { for _, m := range linkRE.FindAllStringSubmatch(resp.Header.Get("Link"), -1) { if len(m) > 2 && m[2] == "next" { return m[1] } } return "" }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/run/shared/shared.go
pkg/cmd/run/shared/shared.go
package shared import ( "errors" "fmt" "net/http" "net/url" "reflect" "strings" "time" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghrepo" workflowShared "github.com/cli/cli/v2/pkg/cmd/workflow/shared" "github.com/cli/cli/v2/pkg/iostreams" ) type Prompter interface { Select(string, string, []string) (int, error) } const ( // Run statuses Queued Status = "queued" Completed Status = "completed" InProgress Status = "in_progress" Requested Status = "requested" Waiting Status = "waiting" Pending Status = "pending" // Run conclusions ActionRequired Conclusion = "action_required" Cancelled Conclusion = "cancelled" Failure Conclusion = "failure" Neutral Conclusion = "neutral" Skipped Conclusion = "skipped" Stale Conclusion = "stale" StartupFailure Conclusion = "startup_failure" Success Conclusion = "success" TimedOut Conclusion = "timed_out" AnnotationFailure Level = "failure" AnnotationWarning Level = "warning" ) type Status string type Conclusion string type Level string var AllStatuses = []string{ "queued", "completed", "in_progress", "requested", "waiting", "pending", "action_required", "cancelled", "failure", "neutral", "skipped", "stale", "startup_failure", "success", "timed_out", } var RunFields = []string{ "name", "displayTitle", "headBranch", "headSha", "createdAt", "updatedAt", "startedAt", "attempt", "status", "conclusion", "event", "number", "databaseId", "workflowDatabaseId", "workflowName", "url", } var SingleRunFields = append(RunFields, "jobs") type Run struct { Name string `json:"name"` // the semantics of this field are unclear DisplayTitle string `json:"display_title"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` StartedAt time.Time `json:"run_started_at"` Status Status Conclusion Conclusion Event string ID int64 workflowName string // cache column WorkflowID int64 `json:"workflow_id"` Number int64 `json:"run_number"` Attempt uint64 `json:"run_attempt"` HeadBranch string `json:"head_branch"` JobsURL string `json:"jobs_url"` HeadCommit Commit `json:"head_commit"` HeadSha string `json:"head_sha"` URL string `json:"html_url"` HeadRepository Repo `json:"head_repository"` Jobs []Job `json:"-"` // populated by GetJobs } func (r *Run) StartedTime() time.Time { if r.StartedAt.IsZero() { return r.CreatedAt } return r.StartedAt } func (r *Run) Duration(now time.Time) time.Duration { endTime := r.UpdatedAt if r.Status != Completed { endTime = now } d := endTime.Sub(r.StartedTime()) if d < 0 { return 0 } return d.Round(time.Second) } type Repo struct { Owner struct { Login string } Name string } type Commit struct { Message string } // Title is the display title for a run, falling back to the commit subject if unavailable func (r Run) Title() string { if r.DisplayTitle != "" { return r.DisplayTitle } commitLines := strings.Split(r.HeadCommit.Message, "\n") if len(commitLines) > 0 { return commitLines[0] } else { return r.HeadSha[0:8] } } // WorkflowName returns the human-readable name of the workflow that this run belongs to. // TODO: consider lazy-loading the underlying API data to avoid extra API calls unless necessary func (r Run) WorkflowName() string { return r.workflowName } func (r *Run) ExportData(fields []string) map[string]interface{} { v := reflect.ValueOf(r).Elem() fieldByName := func(v reflect.Value, field string) reflect.Value { return v.FieldByNameFunc(func(s string) bool { return strings.EqualFold(field, s) }) } data := map[string]interface{}{} for _, f := range fields { switch f { case "databaseId": data[f] = r.ID case "workflowDatabaseId": data[f] = r.WorkflowID case "workflowName": data[f] = r.WorkflowName() case "jobs": jobs := make([]interface{}, 0, len(r.Jobs)) for _, j := range r.Jobs { steps := make([]interface{}, 0, len(j.Steps)) for _, s := range j.Steps { var stepCompletedAt time.Time if !s.CompletedAt.IsZero() { stepCompletedAt = s.CompletedAt } steps = append(steps, map[string]interface{}{ "name": s.Name, "status": s.Status, "conclusion": s.Conclusion, "number": s.Number, "startedAt": s.StartedAt, "completedAt": stepCompletedAt, }) } var jobCompletedAt time.Time if !j.CompletedAt.IsZero() { jobCompletedAt = j.CompletedAt } jobs = append(jobs, map[string]interface{}{ "databaseId": j.ID, "status": j.Status, "conclusion": j.Conclusion, "name": j.Name, "steps": steps, "startedAt": j.StartedAt, "completedAt": jobCompletedAt, "url": j.URL, }) } data[f] = jobs default: sf := fieldByName(v, f) data[f] = sf.Interface() } } return data } type Job struct { ID int64 Status Status Conclusion Conclusion Name string Steps Steps StartedAt time.Time `json:"started_at"` CompletedAt time.Time `json:"completed_at"` URL string `json:"html_url"` RunID int64 `json:"run_id"` } type Step struct { Name string Status Status Conclusion Conclusion Number int StartedAt time.Time `json:"started_at"` CompletedAt time.Time `json:"completed_at"` } type Steps []Step func (s Steps) Len() int { return len(s) } func (s Steps) Less(i, j int) bool { return s[i].Number < s[j].Number } func (s Steps) Swap(i, j int) { s[i], s[j] = s[j], s[i] } type Annotation struct { JobName string Message string Path string Level Level `json:"annotation_level"` StartLine int `json:"start_line"` } func AnnotationSymbol(cs *iostreams.ColorScheme, a Annotation) string { switch a.Level { case AnnotationFailure: return cs.FailureIcon() case AnnotationWarning: return cs.WarningIcon() default: return "-" } } type CheckRun struct { ID int64 } var ErrMissingAnnotationsPermissions = errors.New("missing annotations permissions error") // GetAnnotations fetches annotations from the REST API. // // If the job has no annotations, an empty slice is returned. // If the API returns a 403, a custom ErrMissingAnnotationsPermissions error is returned. // // When fine-grained PATs support checks:read permission, we can remove the need for this at the call sites. func GetAnnotations(client *api.Client, repo ghrepo.Interface, job Job) ([]Annotation, error) { var result []*Annotation path := fmt.Sprintf("repos/%s/check-runs/%d/annotations", ghrepo.FullName(repo), job.ID) err := client.REST(repo.RepoHost(), "GET", path, nil, &result) if err != nil { var httpError api.HTTPError if !errors.As(err, &httpError) { return nil, err } if httpError.StatusCode == http.StatusNotFound { return []Annotation{}, nil } if httpError.StatusCode == http.StatusForbidden { return nil, ErrMissingAnnotationsPermissions } return nil, err } out := []Annotation{} for _, annotation := range result { annotation.JobName = job.Name out = append(out, *annotation) } return out, nil } func IsFailureState(c Conclusion) bool { switch c { case ActionRequired, Failure, StartupFailure, TimedOut: return true default: return false } } func IsSkipped(c Conclusion) bool { return c == Skipped } type RunsPayload struct { TotalCount int `json:"total_count"` WorkflowRuns []Run `json:"workflow_runs"` } type FilterOptions struct { Branch string Actor string WorkflowID int64 // avoid loading workflow name separately and use the provided one WorkflowName string Status string Event string Created string Commit string } // GetRunsWithFilter fetches 50 runs from the API and filters them in-memory func GetRunsWithFilter(client *api.Client, repo ghrepo.Interface, opts *FilterOptions, limit int, f func(Run) bool) ([]Run, error) { runs, err := GetRuns(client, repo, opts, 50) if err != nil { return nil, err } var filtered []Run for _, run := range runs.WorkflowRuns { if f(run) { filtered = append(filtered, run) } if len(filtered) == limit { break } } return filtered, nil } func GetRuns(client *api.Client, repo ghrepo.Interface, opts *FilterOptions, limit int) (*RunsPayload, error) { path := fmt.Sprintf("repos/%s/actions/runs", ghrepo.FullName(repo)) if opts != nil && opts.WorkflowID > 0 { path = fmt.Sprintf("repos/%s/actions/workflows/%d/runs", ghrepo.FullName(repo), opts.WorkflowID) } perPage := limit if limit > 100 { perPage = 100 } path += fmt.Sprintf("?per_page=%d", perPage) path += "&exclude_pull_requests=true" // significantly reduces payload size if opts != nil { if opts.Branch != "" { path += fmt.Sprintf("&branch=%s", url.QueryEscape(opts.Branch)) } if opts.Actor != "" { path += fmt.Sprintf("&actor=%s", url.QueryEscape(opts.Actor)) } if opts.Status != "" { path += fmt.Sprintf("&status=%s", url.QueryEscape(opts.Status)) } if opts.Event != "" { path += fmt.Sprintf("&event=%s", url.QueryEscape(opts.Event)) } if opts.Created != "" { path += fmt.Sprintf("&created=%s", url.QueryEscape(opts.Created)) } if opts.Commit != "" { path += fmt.Sprintf("&head_sha=%s", url.QueryEscape(opts.Commit)) } } var result *RunsPayload pagination: for path != "" { var response RunsPayload var err error path, err = client.RESTWithNext(repo.RepoHost(), "GET", path, nil, &response) if err != nil { return nil, err } if result == nil { result = &response if len(result.WorkflowRuns) == limit { break pagination } } else { for _, run := range response.WorkflowRuns { result.WorkflowRuns = append(result.WorkflowRuns, run) if len(result.WorkflowRuns) == limit { break pagination } } } } if opts != nil && opts.WorkflowName != "" { for i := range result.WorkflowRuns { result.WorkflowRuns[i].workflowName = opts.WorkflowName } } else if len(result.WorkflowRuns) > 0 { if err := preloadWorkflowNames(client, repo, result.WorkflowRuns); err != nil { return result, err } } return result, nil } func preloadWorkflowNames(client *api.Client, repo ghrepo.Interface, runs []Run) error { workflows, err := workflowShared.GetWorkflows(client, repo, 0) if err != nil { return err } workflowMap := map[int64]string{} for _, wf := range workflows { workflowMap[wf.ID] = wf.Name } for i, run := range runs { if _, ok := workflowMap[run.WorkflowID]; !ok { // Look up workflow by ID because it may have been deleted workflow, err := workflowShared.GetWorkflow(client, repo, run.WorkflowID) // If the error is an httpError and it is a 404, this is likely a // organization or enterprise ruleset workflow. The user does not // have permissions to view the details of the workflow, so we cannot // look it up directly without receiving a 404, but it is nonetheless // in the workflow run list. To handle this, we set the workflow name // to an empty string. // Deciding to put this here instead of in GetWorkflow to allow // the caller to decide what a 404 means. if httpErr, ok := err.(api.HTTPError); ok && httpErr.StatusCode == 404 { workflowMap[run.WorkflowID] = "" continue } if err != nil { return err } workflowMap[run.WorkflowID] = workflow.Name } runs[i].workflowName = workflowMap[run.WorkflowID] } return nil } type JobsPayload struct { TotalCount int `json:"total_count"` Jobs []Job } func GetJobs(client *api.Client, repo ghrepo.Interface, run *Run, attempt uint64) ([]Job, error) { if run.Jobs != nil { return run.Jobs, nil } query := url.Values{} query.Set("per_page", "100") jobsPath := fmt.Sprintf("%s?%s", run.JobsURL, query.Encode()) if attempt > 0 { jobsPath = fmt.Sprintf("repos/%s/actions/runs/%d/attempts/%d/jobs?%s", ghrepo.FullName(repo), run.ID, attempt, query.Encode()) } for jobsPath != "" { var resp JobsPayload var err error jobsPath, err = client.RESTWithNext(repo.RepoHost(), http.MethodGet, jobsPath, nil, &resp) if err != nil { run.Jobs = nil return nil, err } run.Jobs = append(run.Jobs, resp.Jobs...) } return run.Jobs, nil } func GetJob(client *api.Client, repo ghrepo.Interface, jobID string) (*Job, error) { path := fmt.Sprintf("repos/%s/actions/jobs/%s", ghrepo.FullName(repo), jobID) var result Job err := client.REST(repo.RepoHost(), "GET", path, nil, &result) if err != nil { return nil, err } return &result, nil } // SelectRun prompts the user to select a run from a list of runs by using the recommended prompter interface func SelectRun(p Prompter, cs *iostreams.ColorScheme, runs []Run) (string, error) { now := time.Now() candidates := []string{} for _, run := range runs { symbol, _ := Symbol(cs, run.Status, run.Conclusion) candidates = append(candidates, // TODO truncate commit message, long ones look terrible fmt.Sprintf("%s %s, %s [%s] %s", symbol, run.Title(), run.WorkflowName(), run.HeadBranch, preciseAgo(now, run.StartedTime()))) } selected, err := p.Select("Select a workflow run", "", candidates) if err != nil { return "", err } return fmt.Sprintf("%d", runs[selected].ID), nil } func GetRun(client *api.Client, repo ghrepo.Interface, runID string, attempt uint64) (*Run, error) { var result Run path := fmt.Sprintf("repos/%s/actions/runs/%s?exclude_pull_requests=true", ghrepo.FullName(repo), runID) if attempt > 0 { path = fmt.Sprintf("repos/%s/actions/runs/%s/attempts/%d?exclude_pull_requests=true", ghrepo.FullName(repo), runID, attempt) } err := client.REST(repo.RepoHost(), "GET", path, nil, &result) if err != nil { return nil, err } if attempt > 0 { result.URL, err = url.JoinPath(result.URL, fmt.Sprintf("/attempts/%d", attempt)) if err != nil { return nil, err } } // Set name to workflow name workflow, err := workflowShared.GetWorkflow(client, repo, result.WorkflowID) if err != nil { return nil, err } else { result.workflowName = workflow.Name } return &result, nil } type colorFunc func(string) string func Symbol(cs *iostreams.ColorScheme, status Status, conclusion Conclusion) (string, colorFunc) { noColor := func(s string) string { return s } if status == Completed { switch conclusion { case Success: return cs.SuccessIconWithColor(noColor), cs.Green case Skipped, Neutral: return "-", cs.Muted default: return cs.FailureIconWithColor(noColor), cs.Red } } return "*", cs.Yellow } func PullRequestForRun(client *api.Client, repo ghrepo.Interface, run Run) (int, error) { type response struct { Repository struct { PullRequests struct { Nodes []struct { Number int HeadRepository struct { Owner struct { Login string } Name string } } } } Number int } variables := map[string]interface{}{ "owner": repo.RepoOwner(), "repo": repo.RepoName(), "headRefName": run.HeadBranch, } query := ` query PullRequestForRun($owner: String!, $repo: String!, $headRefName: String!) { repository(owner: $owner, name: $repo) { pullRequests(headRefName: $headRefName, first: 1, orderBy: { field: CREATED_AT, direction: DESC }) { nodes { number headRepository { owner { login } name } } } } }` var resp response err := client.GraphQL(repo.RepoHost(), query, variables, &resp) if err != nil { return -1, err } prs := resp.Repository.PullRequests.Nodes if len(prs) == 0 { return -1, fmt.Errorf("no matching PR found for %s", run.HeadBranch) } number := -1 for _, pr := range prs { if pr.HeadRepository.Owner.Login == run.HeadRepository.Owner.Login && pr.HeadRepository.Name == run.HeadRepository.Name { number = pr.Number } } if number == -1 { return number, fmt.Errorf("no matching PR found for %s", run.HeadBranch) } return number, nil } func preciseAgo(now time.Time, createdAt time.Time) string { ago := now.Sub(createdAt) if ago < 30*24*time.Hour { s := ago.Truncate(time.Second).String() return fmt.Sprintf("%s ago", s) } return createdAt.Format("Jan _2, 2006") }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/run/shared/presentation_test.go
pkg/cmd/run/shared/presentation_test.go
package shared import ( "testing" "time" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/pkg/iostreams" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestRenderJobs(t *testing.T) { startedAt, err := time.Parse(time.RFC3339, "2009-03-19T00:00:00Z") require.NoError(t, err) completedAt, err := time.Parse(time.RFC3339, "2009-03-19T00:01:00Z") require.NoError(t, err) tests := []struct { name string jobs []Job wantVerbose string wantNormal string wantCompact string }{ { name: "nil jobs", jobs: nil, }, { name: "empty jobs", jobs: []Job{}, }, { // This is not a real-world case, but nevertheless the code should // be able to handle that without error/panic. name: "in-progress job without steps", jobs: []Job{ { Name: "foo", ID: 999, StartedAt: startedAt, Status: InProgress, }, }, wantCompact: heredoc.Doc(` * foo (ID 999)`), wantNormal: heredoc.Doc(` * foo (ID 999)`), wantVerbose: heredoc.Doc(` * foo (ID 999)`), }, { // This is not a real-world case, but nevertheless the code should // be able to handle that without error/panic. name: "successful job without steps", jobs: []Job{ { Name: "foo", ID: 999, StartedAt: startedAt, CompletedAt: completedAt, Status: Completed, Conclusion: Success, }, }, wantCompact: heredoc.Doc(` ✓ foo in 1m0s (ID 999)`), wantNormal: heredoc.Doc(` ✓ foo in 1m0s (ID 999)`), wantVerbose: heredoc.Doc(` ✓ foo in 1m0s (ID 999)`), }, { // This is not a real-world case, but nevertheless the code should // be able to handle that without error/panic. name: "failed job without steps", jobs: []Job{ { Name: "foo", ID: 999, StartedAt: startedAt, CompletedAt: completedAt, Status: Completed, Conclusion: Failure, }, }, wantCompact: heredoc.Doc(` X foo in 1m0s (ID 999)`), wantNormal: heredoc.Doc(` X foo in 1m0s (ID 999)`), wantVerbose: heredoc.Doc(` X foo in 1m0s (ID 999)`), }, { name: "in-progress job with various step status values", jobs: []Job{ { Name: "foo", ID: 999, StartedAt: startedAt, Status: InProgress, Steps: []Step{ { Name: "passed", StartedAt: startedAt, CompletedAt: completedAt, Status: Completed, Conclusion: Success, Number: 1, }, { Name: "skipped", Status: Completed, Conclusion: Skipped, Number: 2, }, { Name: "failed 1", StartedAt: startedAt, CompletedAt: completedAt, Status: Completed, Conclusion: Failure, Number: 3, }, { Name: "failed 2", StartedAt: startedAt, CompletedAt: completedAt, Status: Completed, Conclusion: Failure, Number: 4, }, { Name: "in-progress", StartedAt: startedAt, Status: InProgress, Number: 5, }, { Name: "pending", Status: Pending, Number: 6, }, }, }, }, wantCompact: heredoc.Doc(` * foo (ID 999) X failed 1 X failed 2 * in-progress`), wantNormal: heredoc.Doc(` * foo (ID 999)`), wantVerbose: heredoc.Doc(` * foo (ID 999) ✓ passed - skipped X failed 1 X failed 2 * in-progress * pending`), }, { // As of my observations (babakks) when there is a failed step, the // job run is marked as failed. In other words, a successful job run // cannot have any failed steps. That's why there's no failed steps // in this test case. name: "successful job with various step status values", jobs: []Job{ { Name: "foo", ID: 999, StartedAt: startedAt, CompletedAt: completedAt, Status: Completed, Conclusion: Success, Steps: []Step{ { Name: "passed 1", StartedAt: startedAt, CompletedAt: completedAt, Status: Completed, Conclusion: Success, Number: 1, }, { Name: "skipped", Status: Completed, Conclusion: Skipped, Number: 2, }, { Name: "passed 2", StartedAt: startedAt, CompletedAt: completedAt, Status: Completed, Conclusion: Success, Number: 3, }, }, }, }, wantCompact: heredoc.Doc(` ✓ foo in 1m0s (ID 999)`), wantNormal: heredoc.Doc(` ✓ foo in 1m0s (ID 999)`), wantVerbose: heredoc.Doc(` ✓ foo in 1m0s (ID 999) ✓ passed 1 - skipped ✓ passed 2`), }, { name: "failed job with various step status values", jobs: []Job{ { Name: "foo", ID: 999, StartedAt: startedAt, CompletedAt: completedAt, Status: Completed, Conclusion: Failure, Steps: []Step{ { Name: "passed 1", StartedAt: startedAt, CompletedAt: completedAt, Status: Completed, Conclusion: Success, Number: 1, }, { Name: "skipped", Status: Completed, Conclusion: Skipped, Number: 2, }, { Name: "failed 1", StartedAt: startedAt, CompletedAt: completedAt, Status: Completed, Conclusion: Failure, Number: 3, }, { Name: "failed 2", StartedAt: startedAt, CompletedAt: completedAt, Status: Completed, Conclusion: Failure, Number: 4, }, { Name: "passed 2", StartedAt: startedAt, CompletedAt: completedAt, Status: Completed, Conclusion: Success, Number: 5, }, }, }, }, wantCompact: heredoc.Doc(` X foo in 1m0s (ID 999) X failed 1 X failed 2`), wantNormal: heredoc.Doc(` X foo in 1m0s (ID 999) ✓ passed 1 - skipped X failed 1 X failed 2 ✓ passed 2`), wantVerbose: heredoc.Doc(` X foo in 1m0s (ID 999) ✓ passed 1 - skipped X failed 1 X failed 2 ✓ passed 2`), }, { name: "multiple jobs", jobs: []Job{ { Name: "in-progress", ID: 999, StartedAt: startedAt, Status: InProgress, Steps: []Step{ { Name: "passed", StartedAt: startedAt, CompletedAt: completedAt, Status: Completed, Conclusion: Success, Number: 1, }, { Name: "in-progress", StartedAt: startedAt, Status: InProgress, Number: 2, }, }, }, { Name: "successful", ID: 999, StartedAt: startedAt, CompletedAt: completedAt, Status: Completed, Conclusion: Success, Steps: []Step{ { Name: "passed", StartedAt: startedAt, CompletedAt: completedAt, Status: Completed, Conclusion: Success, Number: 1, }, { Name: "skipped", Status: Completed, Conclusion: Skipped, Number: 2, }, }, }, { Name: "failed", ID: 999, StartedAt: startedAt, CompletedAt: completedAt, Status: Completed, Conclusion: Failure, Steps: []Step{ { Name: "passed", StartedAt: startedAt, CompletedAt: completedAt, Status: Completed, Conclusion: Success, Number: 1, }, { Name: "failed", StartedAt: startedAt, CompletedAt: completedAt, Status: Completed, Conclusion: Failure, Number: 2, }, }, }, }, wantCompact: heredoc.Doc(` * in-progress (ID 999) * in-progress ✓ successful in 1m0s (ID 999) X failed in 1m0s (ID 999) X failed`), wantNormal: heredoc.Doc(` * in-progress (ID 999) ✓ successful in 1m0s (ID 999) X failed in 1m0s (ID 999) ✓ passed X failed`), wantVerbose: heredoc.Doc(` * in-progress (ID 999) ✓ passed * in-progress ✓ successful in 1m0s (ID 999) ✓ passed - skipped X failed in 1m0s (ID 999) ✓ passed X failed`), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotCompact := RenderJobsCompact(&iostreams.ColorScheme{}, tt.jobs) assert.Equal(t, tt.wantCompact, gotCompact, "unexpected compact mode output") gotNormal := RenderJobs(&iostreams.ColorScheme{}, tt.jobs, false) assert.Equal(t, tt.wantNormal, gotNormal, "unexpected normal mode output") gotVerbose := RenderJobs(&iostreams.ColorScheme{}, tt.jobs, true) assert.Equal(t, tt.wantVerbose, gotVerbose, "unexpected verbose mode output") }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/run/shared/artifacts_test.go
pkg/cmd/run/shared/artifacts_test.go
package shared import ( "fmt" "net/http" "net/url" "testing" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/httpmock" "github.com/stretchr/testify/assert" ) func TestDownloadWorkflowArtifactsPageinates(t *testing.T) { testRepoOwner := "OWNER" testRepoName := "REPO" testRunId := "1234567890" reg := &httpmock.Registry{} defer reg.Verify(t) firstReq := httpmock.QueryMatcher( "GET", fmt.Sprintf("repos/%s/%s/actions/runs/%s/artifacts", testRepoOwner, testRepoName, testRunId), url.Values{"per_page": []string{"100"}}, ) firstArtifact := Artifact{ Name: "artifact-0", Size: 2, DownloadURL: fmt.Sprintf("https://api.github.com/repos/%s/%s/actions/artifacts/987654320/zip", testRepoOwner, testRepoName), Expired: true, } firstRes := httpmock.JSONResponse(artifactsPayload{Artifacts: []Artifact{firstArtifact}}) testLinkUri := fmt.Sprintf("repositories/123456789/actions/runs/%s/artifacts", testRunId) testLinkUrl := fmt.Sprintf("https://api.github.com/%s", testLinkUri) firstRes = httpmock.WithHeader( firstRes, "Link", fmt.Sprintf(`<%s?per_page=100&page=2>; rel="next", <%s?per_page=100&page=2>; rel="last"`, testLinkUrl, testLinkUrl), ) secondReq := httpmock.QueryMatcher( "GET", testLinkUri, url.Values{"per_page": []string{"100"}, "page": []string{"2"}}, ) secondArtifact := Artifact{ Name: "artifact-1", Size: 2, DownloadURL: fmt.Sprintf("https://api.github.com/repos/%s/%s/actions/artifacts/987654321/zip", testRepoOwner, testRepoName), Expired: false, } secondRes := httpmock.JSONResponse(artifactsPayload{Artifacts: []Artifact{secondArtifact}}) reg.Register(firstReq, firstRes) reg.Register(secondReq, secondRes) httpClient := &http.Client{Transport: reg} repo := ghrepo.New(testRepoOwner, testRepoName) result, err := ListArtifacts(httpClient, repo, testRunId) assert.NoError(t, err) assert.Equal(t, []Artifact{firstArtifact, secondArtifact}, result) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/run/shared/test.go
pkg/cmd/run/shared/test.go
package shared import ( "fmt" "time" workflowShared "github.com/cli/cli/v2/pkg/cmd/workflow/shared" "github.com/cli/cli/v2/pkg/iostreams" ) var TestRunStartTime, _ = time.Parse("2006-01-02 15:04:05", "2021-02-23 04:51:00") func TestRun(id int64, s Status, c Conclusion) Run { return TestRunWithCommit(id, s, c, "cool commit") } func TestRunWithCommit(id int64, s Status, c Conclusion, commit string) Run { return TestRunWithWorkflowAndCommit(123, id, s, c, commit) } func TestRunWithOrgRequiredWorkflow(id int64, s Status, c Conclusion, commit string) Run { return TestRunWithWorkflowAndCommit(456, id, s, c, commit) } func TestRunWithWorkflowAndCommit(workflowId, runId int64, s Status, c Conclusion, commit string) Run { return Run{ WorkflowID: workflowId, ID: runId, CreatedAt: TestRunStartTime, UpdatedAt: TestRunStartTime.Add(time.Minute*4 + time.Second*34), Status: s, Conclusion: c, Event: "push", HeadBranch: "trunk", JobsURL: fmt.Sprintf("https://api.github.com/runs/%d/jobs", runId), HeadCommit: Commit{ Message: commit, }, HeadSha: "1234567890", URL: fmt.Sprintf("https://github.com/runs/%d", runId), HeadRepository: Repo{ Owner: struct{ Login string }{Login: "OWNER"}, Name: "REPO", }, } } var SuccessfulRun Run = TestRun(3, Completed, Success) var FailedRun Run = TestRun(1234, Completed, Failure) var TestRuns []Run = []Run{ TestRun(1, Completed, TimedOut), TestRun(2, InProgress, ""), SuccessfulRun, TestRun(4, Completed, Cancelled), FailedRun, TestRun(6, Completed, Neutral), TestRun(7, Completed, Skipped), TestRun(8, Requested, ""), TestRun(9, Queued, ""), TestRun(10, Completed, Stale), } var TestRunsWithOrgRequiredWorkflows []Run = []Run{ TestRunWithOrgRequiredWorkflow(1, Completed, TimedOut, "cool commit"), TestRunWithOrgRequiredWorkflow(2, InProgress, "", "cool commit"), TestRunWithOrgRequiredWorkflow(3, Completed, Success, "cool commit"), TestRunWithOrgRequiredWorkflow(4, Completed, Cancelled, "cool commit"), TestRun(5, Completed, Failure), TestRun(6, Completed, Neutral), TestRun(7, Completed, Skipped), TestRun(8, Requested, ""), TestRun(9, Queued, ""), } var WorkflowRuns []Run = []Run{ TestRun(2, InProgress, ""), SuccessfulRun, FailedRun, } var SuccessfulJob Job = Job{ ID: 10, Status: Completed, Conclusion: Success, Name: "cool job", StartedAt: TestRunStartTime, CompletedAt: TestRunStartTime.Add(time.Minute*4 + time.Second*34), URL: "https://github.com/jobs/10", RunID: 3, Steps: []Step{ { Name: "fob the barz", Status: Completed, Conclusion: Success, Number: 1, }, { Name: "barz the fob", Status: Completed, Conclusion: Success, Number: 2, }, }, } // Note that this run *has* steps, but in the ZIP archive the step logs are not // included. var SuccessfulJobWithoutStepLogs Job = Job{ ID: 11, Status: Completed, Conclusion: Success, Name: "cool job with no step logs", StartedAt: TestRunStartTime, CompletedAt: TestRunStartTime.Add(time.Minute*4 + time.Second*34), URL: "https://github.com/jobs/11", RunID: 3, Steps: []Step{ { Name: "fob the barz", Status: Completed, Conclusion: Success, Number: 1, }, { Name: "barz the fob", Status: Completed, Conclusion: Success, Number: 2, }, }, } // Note that this run *has* steps, but in the ZIP archive the step logs are not // included. var LegacySuccessfulJobWithoutStepLogs Job = Job{ ID: 12, Status: Completed, Conclusion: Success, Name: "legacy cool job with no step logs", StartedAt: TestRunStartTime, CompletedAt: TestRunStartTime.Add(time.Minute*4 + time.Second*34), URL: "https://github.com/jobs/12", RunID: 3, Steps: []Step{ { Name: "fob the barz", Status: Completed, Conclusion: Success, Number: 1, }, { Name: "barz the fob", Status: Completed, Conclusion: Success, Number: 2, }, }, } var SkippedJob Job = Job{ ID: 13, Status: Completed, Conclusion: Skipped, Name: "cool job", StartedAt: TestRunStartTime, CompletedAt: TestRunStartTime, URL: "https://github.com/jobs/13", RunID: 3, Steps: []Step{}, } var FailedJob Job = Job{ ID: 20, Status: Completed, Conclusion: Failure, Name: "sad job", StartedAt: TestRunStartTime, CompletedAt: TestRunStartTime.Add(time.Minute*4 + time.Second*34), URL: "https://github.com/jobs/20", RunID: 1234, Steps: []Step{ { Name: "barf the quux", Status: Completed, Conclusion: Success, Number: 1, }, { Name: "quux the barf", Status: Completed, Conclusion: Failure, Number: 2, }, }, } // Note that this run *has* steps, but in the ZIP archive the step logs are not // included. var FailedJobWithoutStepLogs Job = Job{ ID: 21, Status: Completed, Conclusion: Failure, Name: "sad job with no step logs", StartedAt: TestRunStartTime, CompletedAt: TestRunStartTime.Add(time.Minute*4 + time.Second*34), URL: "https://github.com/jobs/21", RunID: 1234, Steps: []Step{ { Name: "barf the quux", Status: Completed, Conclusion: Success, Number: 1, }, { Name: "quux the barf", Status: Completed, Conclusion: Failure, Number: 2, }, }, } // Note that this run *has* steps, but in the ZIP archive the step logs are not // included. var LegacyFailedJobWithoutStepLogs Job = Job{ ID: 22, Status: Completed, Conclusion: Failure, Name: "legacy sad job with no step logs", StartedAt: TestRunStartTime, CompletedAt: TestRunStartTime.Add(time.Minute*4 + time.Second*34), URL: "https://github.com/jobs/22", RunID: 1234, Steps: []Step{ { Name: "barf the quux", Status: Completed, Conclusion: Success, Number: 1, }, { Name: "quux the barf", Status: Completed, Conclusion: Failure, Number: 2, }, }, } var SuccessfulJobAnnotations []Annotation = []Annotation{ { JobName: "cool job", Message: "the job is happy", Path: "blaze.py", Level: "notice", StartLine: 420, }, } var FailedJobAnnotations []Annotation = []Annotation{ { JobName: "sad job", Message: "the job is sad", Path: "blaze.py", Level: "failure", StartLine: 420, }, } var TestWorkflow workflowShared.Workflow = workflowShared.Workflow{ Name: "CI", ID: 123, } type TestExporter struct { fields []string writeHandler func(io *iostreams.IOStreams, data interface{}) error } func MakeTestExporter(fields []string, wh func(io *iostreams.IOStreams, data interface{}) error) *TestExporter { return &TestExporter{fields: fields, writeHandler: wh} } func (t *TestExporter) Fields() []string { return t.fields } func (t *TestExporter) Write(io *iostreams.IOStreams, data interface{}) error { return t.writeHandler(io, data) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/run/download/zip_test.go
pkg/cmd/run/download/zip_test.go
package download import ( "archive/zip" "os" "path/filepath" "testing" "github.com/cli/cli/v2/internal/safepaths" "github.com/stretchr/testify/require" ) func Test_extractZip(t *testing.T) { tmpDir := t.TempDir() extractPath, err := safepaths.ParseAbsolute(filepath.Join(tmpDir, "artifact")) require.NoError(t, err) zipFile, err := zip.OpenReader("./fixtures/myproject.zip") require.NoError(t, err) defer zipFile.Close() err = extractZip(&zipFile.Reader, extractPath) require.NoError(t, err) _, err = os.Stat(filepath.Join(extractPath.String(), "src", "main.go")) require.NoError(t, err) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/run/download/zip.go
pkg/cmd/run/download/zip.go
package download import ( "archive/zip" "errors" "fmt" "io" "os" "path/filepath" "github.com/cli/cli/v2/internal/safepaths" ) const ( dirMode os.FileMode = 0755 fileMode os.FileMode = 0644 execMode os.FileMode = 0755 ) func extractZip(zr *zip.Reader, destDir safepaths.Absolute) error { for _, zf := range zr.File { fpath, err := destDir.Join(zf.Name) if err != nil { var pathTraversalError safepaths.PathTraversalError if errors.As(err, &pathTraversalError) { continue } return err } if err := extractZipFile(zf, fpath); err != nil { return fmt.Errorf("error extracting %q: %w", zf.Name, err) } } return nil } func extractZipFile(zf *zip.File, dest safepaths.Absolute) (extractErr error) { zm := zf.Mode() if zm.IsDir() { extractErr = os.MkdirAll(dest.String(), dirMode) return } var f io.ReadCloser f, extractErr = zf.Open() if extractErr != nil { return } defer f.Close() if extractErr = os.MkdirAll(filepath.Dir(dest.String()), dirMode); extractErr != nil { return } var df *os.File if df, extractErr = os.OpenFile(dest.String(), os.O_WRONLY|os.O_CREATE|os.O_EXCL, getPerm(zm)); extractErr != nil { return } defer func() { if err := df.Close(); extractErr == nil && err != nil { extractErr = err } }() _, extractErr = io.Copy(df, f) return } func getPerm(m os.FileMode) os.FileMode { if m&0111 == 0 { return fileMode } return execMode }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/run/download/http_test.go
pkg/cmd/run/download/http_test.go
package download import ( "net/http" "os" "path/filepath" "sort" "strings" "testing" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/safepaths" "github.com/cli/cli/v2/pkg/httpmock" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func Test_List(t *testing.T) { reg := &httpmock.Registry{} defer reg.Verify(t) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/runs/123/artifacts"), httpmock.StringResponse(`{ "total_count": 2, "artifacts": [ {"name": "artifact-1"}, {"name": "artifact-2"} ] }`)) api := &apiPlatform{ client: &http.Client{Transport: reg}, repo: ghrepo.New("OWNER", "REPO"), } artifacts, err := api.List("123") require.NoError(t, err) require.Equal(t, 2, len(artifacts)) assert.Equal(t, "artifact-1", artifacts[0].Name) assert.Equal(t, "artifact-2", artifacts[1].Name) } func Test_List_perRepository(t *testing.T) { reg := &httpmock.Registry{} defer reg.Verify(t) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/artifacts"), httpmock.StringResponse(`{}`)) api := &apiPlatform{ client: &http.Client{Transport: reg}, repo: ghrepo.New("OWNER", "REPO"), } _, err := api.List("") require.NoError(t, err) } func Test_Download(t *testing.T) { tmpDir := t.TempDir() destDir, err := safepaths.ParseAbsolute(filepath.Join(tmpDir, "artifact")) require.NoError(t, err) reg := &httpmock.Registry{} defer reg.Verify(t) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/artifacts/12345/zip"), httpmock.FileResponse("./fixtures/myproject.zip")) api := &apiPlatform{ client: &http.Client{Transport: reg}, } require.NoError(t, api.Download("https://api.github.com/repos/OWNER/REPO/actions/artifacts/12345/zip", destDir)) var paths []string parentPrefix := tmpDir + string(filepath.Separator) err = filepath.Walk(tmpDir, func(p string, info os.FileInfo, err error) error { if err != nil { return err } if p == tmpDir { return nil } entry := strings.TrimPrefix(p, parentPrefix) if info.IsDir() { entry += "/" } else if info.Mode()&0111 != 0 { entry += "(X)" } paths = append(paths, entry) return nil }) require.NoError(t, err) sort.Strings(paths) assert.Equal(t, []string{ "artifact/", filepath.Join("artifact", "bin") + "/", filepath.Join("artifact", "bin", "myexe"), filepath.Join("artifact", "readme.md"), filepath.Join("artifact", "src") + "/", filepath.Join("artifact", "src", "main.go"), filepath.Join("artifact", "src", "util.go"), }, paths) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/run/download/http.go
pkg/cmd/run/download/http.go
package download import ( "archive/zip" "fmt" "io" "net/http" "os" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/safepaths" "github.com/cli/cli/v2/pkg/cmd/run/shared" ) type apiPlatform struct { client *http.Client repo ghrepo.Interface } func (p *apiPlatform) List(runID string) ([]shared.Artifact, error) { return shared.ListArtifacts(p.client, p.repo, runID) } func (p *apiPlatform) Download(url string, dir safepaths.Absolute) error { return downloadArtifact(p.client, url, dir) } func downloadArtifact(httpClient *http.Client, url string, destDir safepaths.Absolute) error { req, err := http.NewRequest("GET", url, nil) if err != nil { return err } // The server rejects this :( //req.Header.Set("Accept", "application/zip") resp, err := httpClient.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode > 299 { return api.HandleHTTPError(resp) } tmpfile, err := os.CreateTemp("", "gh-artifact.*.zip") if err != nil { return fmt.Errorf("error initializing temporary file: %w", err) } defer func() { _ = tmpfile.Close() _ = os.Remove(tmpfile.Name()) }() size, err := io.Copy(tmpfile, resp.Body) if err != nil { return fmt.Errorf("error writing zip archive: %w", err) } zipfile, err := zip.NewReader(tmpfile, size) if err != nil { return fmt.Errorf("error extracting zip archive: %w", err) } if err := extractZip(zipfile, destDir); err != nil { return fmt.Errorf("error extracting zip archive: %w", err) } return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/run/download/download_test.go
pkg/cmd/run/download/download_test.go
package download import ( "bytes" "errors" "fmt" "io" "net/http" "os" "path/filepath" "testing" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/internal/safepaths" "github.com/cli/cli/v2/pkg/cmd/run/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 Test_NewCmdDownload(t *testing.T) { tests := []struct { name string args string isTTY bool want DownloadOptions wantErr string }{ { name: "empty", args: "", isTTY: true, want: DownloadOptions{ RunID: "", DoPrompt: true, Names: []string(nil), DestinationDir: ".", }, }, { name: "with run ID", args: "2345", isTTY: true, want: DownloadOptions{ RunID: "2345", DoPrompt: false, Names: []string(nil), DestinationDir: ".", }, }, { name: "to destination", args: "2345 -D tmp/dest", isTTY: true, want: DownloadOptions{ RunID: "2345", DoPrompt: false, Names: []string(nil), DestinationDir: "tmp/dest", }, }, { name: "repo level with names", args: "-n one -n two", isTTY: true, want: DownloadOptions{ RunID: "", DoPrompt: false, Names: []string{"one", "two"}, DestinationDir: ".", }, }, { name: "repo level with patterns", args: "-p o*e -p tw*", isTTY: true, want: DownloadOptions{ RunID: "", DoPrompt: false, FilePatterns: []string{"o*e", "tw*"}, DestinationDir: ".", }, }, { name: "repo level with names and patterns", args: "-p o*e -p tw* -n three -n four", isTTY: true, want: DownloadOptions{ RunID: "", DoPrompt: false, Names: []string{"three", "four"}, FilePatterns: []string{"o*e", "tw*"}, DestinationDir: ".", }, }, } 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, HttpClient: func() (*http.Client, error) { return nil, nil }, BaseRepo: func() (ghrepo.Interface, error) { return nil, nil }, } var opts *DownloadOptions cmd := NewCmdDownload(f, func(o *DownloadOptions) 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.RunID, opts.RunID) assert.Equal(t, tt.want.Names, opts.Names) assert.Equal(t, tt.want.FilePatterns, opts.FilePatterns) assert.Equal(t, tt.want.DestinationDir, opts.DestinationDir) assert.Equal(t, tt.want.DoPrompt, opts.DoPrompt) }) } } type run struct { id string testArtifacts []testArtifact } type testArtifact struct { artifact shared.Artifact files []string } type fakePlatform struct { runs []run } func (f *fakePlatform) List(runID string) ([]shared.Artifact, error) { runIds := map[string]struct{}{} if runID != "" { runIds[runID] = struct{}{} } else { for _, run := range f.runs { runIds[run.id] = struct{}{} } } var artifacts []shared.Artifact for _, run := range f.runs { // Skip over any runs that we aren't looking for if _, ok := runIds[run.id]; !ok { continue } // Grab the artifacts of everything else for _, testArtifact := range run.testArtifacts { artifacts = append(artifacts, testArtifact.artifact) } } return artifacts, nil } func (f *fakePlatform) Download(url string, dir safepaths.Absolute) error { if err := os.MkdirAll(dir.String(), 0755); err != nil { return err } // Now to be consistent, we find the artifact with the provided URL. // It's a bit janky to iterate the runs, to find the right artifact // rather than keying directly to it, but it allows the setup of the // fake platform to be declarative rather than imperative. // Think fakePlatform { artifacts: ... } rather than fakePlatform.makeArtifactAvailable() for _, run := range f.runs { for _, testArtifact := range run.testArtifacts { if testArtifact.artifact.DownloadURL == url { for _, file := range testArtifact.files { path := filepath.Join(dir.String(), file) return os.WriteFile(path, []byte{}, 0600) } } } } return errors.New("no artifact matches the provided URL") } func Test_runDownload(t *testing.T) { tests := []struct { name string opts DownloadOptions platform *fakePlatform promptStubs func(*prompter.MockPrompter) expectedFiles []string wantErr string }{ { name: "download non-expired to relative directory", opts: DownloadOptions{ RunID: "2345", DestinationDir: "./tmp", }, platform: &fakePlatform{ runs: []run{ { id: "2345", testArtifacts: []testArtifact{ { artifact: shared.Artifact{ Name: "artifact-1", DownloadURL: "http://download.com/artifact1.zip", Expired: false, }, files: []string{ "artifact-1-file", }, }, { artifact: shared.Artifact{ Name: "expired-artifact", DownloadURL: "http://download.com/expired.zip", Expired: true, }, files: []string{ "expired", }, }, { artifact: shared.Artifact{ Name: "artifact-2", DownloadURL: "http://download.com/artifact2.zip", Expired: false, }, files: []string{ "artifact-2-file", }, }, }, }, }, }, expectedFiles: []string{ filepath.Join("artifact-1", "artifact-1-file"), filepath.Join("artifact-2", "artifact-2-file"), }, }, { name: "download non-expired to absolute directory", opts: DownloadOptions{ RunID: "2345", DestinationDir: "/tmp", }, platform: &fakePlatform{ runs: []run{ { id: "2345", testArtifacts: []testArtifact{ { artifact: shared.Artifact{ Name: "artifact-1", DownloadURL: "http://download.com/artifact1.zip", Expired: false, }, files: []string{ "artifact-1-file", }, }, { artifact: shared.Artifact{ Name: "expired-artifact", DownloadURL: "http://download.com/expired.zip", Expired: true, }, files: []string{ "expired", }, }, { artifact: shared.Artifact{ Name: "artifact-2", DownloadURL: "http://download.com/artifact2.zip", Expired: false, }, files: []string{ "artifact-2-file", }, }, }, }, }, }, expectedFiles: []string{ filepath.Join("artifact-1", "artifact-1-file"), filepath.Join("artifact-2", "artifact-2-file"), }, }, { name: "all artifacts are expired", opts: DownloadOptions{ RunID: "2345", }, platform: &fakePlatform{ runs: []run{ { id: "2345", testArtifacts: []testArtifact{ { artifact: shared.Artifact{ Name: "artifact-1", DownloadURL: "http://download.com/artifact1.zip", Expired: true, }, files: []string{ "artifact-1-file", }, }, { artifact: shared.Artifact{ Name: "artifact-2", DownloadURL: "http://download.com/artifact2.zip", Expired: true, }, files: []string{ "artifact-2-file", }, }, }, }, }, }, expectedFiles: []string{}, wantErr: "no valid artifacts found to download", }, { name: "no name matches", opts: DownloadOptions{ RunID: "2345", Names: []string{"artifact-3"}, }, platform: &fakePlatform{ runs: []run{ { id: "2345", testArtifacts: []testArtifact{ { artifact: shared.Artifact{ Name: "artifact-1", DownloadURL: "http://download.com/artifact1.zip", Expired: false, }, files: []string{ "artifact-1-file", }, }, { artifact: shared.Artifact{ Name: "artifact-2", DownloadURL: "http://download.com/artifact2.zip", Expired: false, }, files: []string{ "artifact-2-file", }, }, }, }, }, }, expectedFiles: []string{}, wantErr: "no artifact matches any of the names or patterns provided", }, { name: "pattern matches", opts: DownloadOptions{ RunID: "2345", FilePatterns: []string{"artifact-*"}, }, platform: &fakePlatform{ runs: []run{ { id: "2345", testArtifacts: []testArtifact{ { artifact: shared.Artifact{ Name: "artifact-1", DownloadURL: "http://download.com/artifact1.zip", Expired: false, }, files: []string{ "artifact-1-file", }, }, { artifact: shared.Artifact{ Name: "non-artifact-2", DownloadURL: "http://download.com/non-artifact-2.zip", Expired: false, }, files: []string{ "non-artifact-2-file", }, }, { artifact: shared.Artifact{ Name: "artifact-3", DownloadURL: "http://download.com/artifact3.zip", Expired: false, }, files: []string{ "artifact-3-file", }, }, }, }, }, }, expectedFiles: []string{ filepath.Join("artifact-1", "artifact-1-file"), filepath.Join("artifact-3", "artifact-3-file"), }, }, { name: "no pattern matches", opts: DownloadOptions{ RunID: "2345", FilePatterns: []string{"artifiction-*"}, }, platform: &fakePlatform{ runs: []run{ { id: "2345", testArtifacts: []testArtifact{ { artifact: shared.Artifact{ Name: "artifact-1", DownloadURL: "http://download.com/artifact1.zip", Expired: false, }, files: []string{ "artifact-1-file", }, }, { artifact: shared.Artifact{ Name: "artifact-2", DownloadURL: "http://download.com/artifact2.zip", Expired: false, }, files: []string{ "artifact-2-file", }, }, }, }, }, }, expectedFiles: []string{}, wantErr: "no artifact matches any of the names or patterns provided", }, { name: "want specific single artifact", opts: DownloadOptions{ RunID: "2345", Names: []string{"non-artifact-2"}, }, platform: &fakePlatform{ runs: []run{ { id: "2345", testArtifacts: []testArtifact{ { artifact: shared.Artifact{ Name: "artifact-1", DownloadURL: "http://download.com/artifact1.zip", Expired: false, }, files: []string{ "artifact-1-file", }, }, { artifact: shared.Artifact{ Name: "non-artifact-2", DownloadURL: "http://download.com/non-artifact-2.zip", Expired: false, }, files: []string{ "non-artifact-2-file", }, }, { artifact: shared.Artifact{ Name: "artifact-3", DownloadURL: "http://download.com/artifact3.zip", Expired: false, }, files: []string{ "artifact-3-file", }, }, }, }, }, }, expectedFiles: []string{ "non-artifact-2-file", }, }, { name: "want specific multiple artifacts", opts: DownloadOptions{ RunID: "2345", Names: []string{"artifact-1", "artifact-3"}, }, platform: &fakePlatform{ runs: []run{ { id: "2345", testArtifacts: []testArtifact{ { artifact: shared.Artifact{ Name: "artifact-1", DownloadURL: "http://download.com/artifact1.zip", Expired: false, }, files: []string{ "artifact-1-file", }, }, { artifact: shared.Artifact{ Name: "non-artifact-2", DownloadURL: "http://download.com/non-artifact-2.zip", Expired: false, }, files: []string{ "non-artifact-2-file", }, }, { artifact: shared.Artifact{ Name: "artifact-3", DownloadURL: "http://download.com/artifact3.zip", Expired: false, }, files: []string{ "artifact-3-file", }, }, }, }, }, }, expectedFiles: []string{ filepath.Join("artifact-1", "artifact-1-file"), filepath.Join("artifact-3", "artifact-3-file"), }, }, { name: "avoid redownloading files of the same name", opts: DownloadOptions{ RunID: "2345", }, platform: &fakePlatform{ runs: []run{ { id: "2345", testArtifacts: []testArtifact{ { artifact: shared.Artifact{ Name: "artifact-1", DownloadURL: "http://download.com/artifact1.zip", Expired: false, }, files: []string{ "artifact-1-file", }, }, { artifact: shared.Artifact{ Name: "artifact-1", DownloadURL: "http://download.com/artifact2.zip", Expired: false, }, files: []string{ "artifact-2-file", }, }, }, }, }, }, expectedFiles: []string{ filepath.Join("artifact-1", "artifact-1-file"), }, }, { name: "prompt to select artifact", opts: DownloadOptions{ RunID: "", DoPrompt: true, Names: []string(nil), }, platform: &fakePlatform{ runs: []run{ { id: "2345", testArtifacts: []testArtifact{ { artifact: shared.Artifact{ Name: "artifact-1", DownloadURL: "http://download.com/artifact1.zip", Expired: false, }, files: []string{ "artifact-1-file", }, }, { artifact: shared.Artifact{ Name: "expired-artifact", DownloadURL: "http://download.com/expired.zip", Expired: true, }, files: []string{ "expired", }, }, }, }, { id: "6789", testArtifacts: []testArtifact{ { artifact: shared.Artifact{ Name: "artifact-2", DownloadURL: "http://download.com/artifact2.zip", Expired: false, }, files: []string{ "artifact-2-file", }, }, }, }, }, }, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterMultiSelect("Select artifacts to download:", nil, []string{"artifact-1", "artifact-2"}, func(_ string, _, opts []string) ([]int, error) { for i, o := range opts { if o == "artifact-2" { return []int{i}, nil } } return nil, fmt.Errorf("no artifact-2 found in %v", opts) }) }, expectedFiles: []string{ "artifact-2-file", }, }, { name: "handling artifact name with path traversal exploit", opts: DownloadOptions{ RunID: "2345", }, platform: &fakePlatform{ runs: []run{ { id: "2345", testArtifacts: []testArtifact{ { artifact: shared.Artifact{ Name: "..", DownloadURL: "http://download.com/artifact1.zip", Expired: false, }, files: []string{ "etc/passwd", }, }, }, }, }, }, expectedFiles: []string{}, wantErr: "error downloading ..: would result in path traversal", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { opts := &tt.opts if opts.DestinationDir == "" { opts.DestinationDir = t.TempDir() } else { opts.DestinationDir = filepath.Join(t.TempDir(), opts.DestinationDir) } ios, _, stdout, stderr := iostreams.Test() opts.IO = ios opts.Platform = tt.platform pm := prompter.NewMockPrompter(t) opts.Prompter = pm if tt.promptStubs != nil { tt.promptStubs(pm) } err := runDownload(opts) if tt.wantErr != "" { require.EqualError(t, err, tt.wantErr) } else { require.NoError(t, err) } // Check that the exact number of files exist require.Equal(t, len(tt.expectedFiles), countFilesInDirRecursively(t, opts.DestinationDir)) // Then check that the exact files are correct for _, name := range tt.expectedFiles { require.FileExists(t, filepath.Join(opts.DestinationDir, name)) } assert.Equal(t, "", stdout.String()) assert.Equal(t, "", stderr.String()) }) } } func countFilesInDirRecursively(t *testing.T, dir string) int { t.Helper() count := 0 require.NoError(t, filepath.Walk(dir, func(_ string, info os.FileInfo, err error) error { require.NoError(t, err) if !info.IsDir() { count++ } return nil })) return count }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/run/download/download.go
pkg/cmd/run/download/download.go
package download import ( "errors" "fmt" "path/filepath" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/safepaths" "github.com/cli/cli/v2/pkg/cmd/run/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" ) type DownloadOptions struct { IO *iostreams.IOStreams Platform platform Prompter iprompter DoPrompt bool RunID string DestinationDir string Names []string FilePatterns []string } type platform interface { List(runID string) ([]shared.Artifact, error) Download(url string, dir safepaths.Absolute) error } type iprompter interface { MultiSelect(string, []string, []string) ([]int, error) } func NewCmdDownload(f *cmdutil.Factory, runF func(*DownloadOptions) error) *cobra.Command { opts := &DownloadOptions{ IO: f.IOStreams, Prompter: f.Prompter, } cmd := &cobra.Command{ Use: "download [<run-id>]", Short: "Download artifacts generated by a workflow run", Long: heredoc.Docf(` Download artifacts generated by a GitHub Actions workflow run. The contents of each artifact will be extracted under separate directories based on the artifact name. If only a single artifact is specified, it will be extracted into the current directory. By default, this command downloads the latest artifact created and uploaded through GitHub Actions. Because workflows can delete or overwrite artifacts, %[1]s<run-id>%[1]s must be used to select an artifact from a specific workflow run. `, "`"), Args: cobra.MaximumNArgs(1), Example: heredoc.Doc(` # Download all artifacts generated by a workflow run $ gh run download <run-id> # Download a specific artifact within a run $ gh run download <run-id> -n <name> # Download specific artifacts across all runs in a repository $ gh run download -n <name1> -n <name2> # Select artifacts to download interactively $ gh run download `), RunE: func(cmd *cobra.Command, args []string) error { if len(args) > 0 { opts.RunID = args[0] } else if len(opts.Names) == 0 && len(opts.FilePatterns) == 0 && opts.IO.CanPrompt() { opts.DoPrompt = true } // support `-R, --repo` override baseRepo, err := f.BaseRepo() if err != nil { return err } httpClient, err := f.HttpClient() if err != nil { return err } opts.Platform = &apiPlatform{ client: httpClient, repo: baseRepo, } if runF != nil { return runF(opts) } return runDownload(opts) }, } cmd.Flags().StringVarP(&opts.DestinationDir, "dir", "D", ".", "The directory to download artifacts into") cmd.Flags().StringArrayVarP(&opts.Names, "name", "n", nil, "Download artifacts that match any of the given names") cmd.Flags().StringArrayVarP(&opts.FilePatterns, "pattern", "p", nil, "Download artifacts that match a glob pattern") return cmd } func runDownload(opts *DownloadOptions) error { opts.IO.StartProgressIndicator() artifacts, err := opts.Platform.List(opts.RunID) opts.IO.StopProgressIndicator() if err != nil { return fmt.Errorf("error fetching artifacts: %w", err) } numValidArtifacts := 0 for _, a := range artifacts { if a.Expired { continue } numValidArtifacts++ } if numValidArtifacts == 0 { return errors.New("no valid artifacts found to download") } wantPatterns := opts.FilePatterns wantNames := opts.Names if opts.DoPrompt { artifactNames := set.NewStringSet() for _, a := range artifacts { if !a.Expired { artifactNames.Add(a.Name) } } options := artifactNames.ToSlice() if len(options) > 10 { options = options[:10] } var selected []int if selected, err = opts.Prompter.MultiSelect("Select artifacts to download:", nil, options); err != nil { return err } wantNames = []string{} for _, x := range selected { wantNames = append(wantNames, options[x]) } if len(wantNames) == 0 { return errors.New("no artifacts selected") } } opts.IO.StartProgressIndicator() defer opts.IO.StopProgressIndicator() // track downloaded artifacts and avoid re-downloading any of the same name, isolate if multiple artifacts downloaded := set.NewStringSet() isolateArtifacts := isolateArtifacts(wantNames, wantPatterns) absoluteDestinationDir, err := safepaths.ParseAbsolute(opts.DestinationDir) if err != nil { return fmt.Errorf("error parsing destination directory: %w", err) } for _, a := range artifacts { if a.Expired { continue } if downloaded.Contains(a.Name) { continue } if len(wantNames) > 0 || len(wantPatterns) > 0 { if !matchAnyName(wantNames, a.Name) && !matchAnyPattern(wantPatterns, a.Name) { continue } } destDir := absoluteDestinationDir if isolateArtifacts { destDir, err = absoluteDestinationDir.Join(a.Name) if err != nil { var pathTraversalError safepaths.PathTraversalError if errors.As(err, &pathTraversalError) { return fmt.Errorf("error downloading %s: would result in path traversal", a.Name) } return err } } err := opts.Platform.Download(a.DownloadURL, destDir) if err != nil { return fmt.Errorf("error downloading %s: %w", a.Name, err) } downloaded.Add(a.Name) } if downloaded.Len() == 0 { return errors.New("no artifact matches any of the names or patterns provided") } return nil } func isolateArtifacts(wantNames []string, wantPatterns []string) bool { if len(wantPatterns) > 0 { // Patterns can match multiple artifacts return true } if len(wantNames) == 0 { // All artifacts wanted regardless what they are named return true } if len(wantNames) > 1 { // Multiple, specific artifacts wanted return true } return false } func matchAnyName(names []string, name string) bool { for _, n := range names { if name == n { return true } } return false } func matchAnyPattern(patterns []string, name string) bool { for _, p := range patterns { if isMatch, err := filepath.Match(p, name); err == nil && isMatch { return true } } return false }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/gpg-key/gpg_key.go
pkg/cmd/gpg-key/gpg_key.go
package key import ( cmdAdd "github.com/cli/cli/v2/pkg/cmd/gpg-key/add" cmdDelete "github.com/cli/cli/v2/pkg/cmd/gpg-key/delete" cmdList "github.com/cli/cli/v2/pkg/cmd/gpg-key/list" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/spf13/cobra" ) func NewCmdGPGKey(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "gpg-key <command>", Short: "Manage GPG keys", Long: "Manage GPG keys registered with your GitHub account.", } cmd.AddCommand(cmdAdd.NewCmdAdd(f, nil)) cmd.AddCommand(cmdDelete.NewCmdDelete(f, nil)) cmd.AddCommand(cmdList.NewCmdList(f, nil)) return cmd }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/gpg-key/delete/delete.go
pkg/cmd/gpg-key/delete/delete.go
package delete import ( "fmt" "net/http" "strconv" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type DeleteOptions struct { IO *iostreams.IOStreams Config func() (gh.Config, error) HttpClient func() (*http.Client, error) KeyID string Confirmed bool Prompter prompter.Prompter } func NewCmdDelete(f *cmdutil.Factory, runF func(*DeleteOptions) error) *cobra.Command { opts := &DeleteOptions{ HttpClient: f.HttpClient, Config: f.Config, IO: f.IOStreams, Prompter: f.Prompter, } cmd := &cobra.Command{ Use: "delete <key-id>", Short: "Delete a GPG key from your GitHub account", Args: cmdutil.ExactArgs(1, "cannot delete: key id required"), RunE: func(cmd *cobra.Command, args []string) error { opts.KeyID = args[0] if !opts.IO.CanPrompt() && !opts.Confirmed { return cmdutil.FlagErrorf("--yes required when not running interactively") } if runF != nil { return runF(opts) } return deleteRun(opts) }, } cmd.Flags().BoolVar(&opts.Confirmed, "confirm", false, "Skip the confirmation prompt") _ = cmd.Flags().MarkDeprecated("confirm", "use `--yes` instead") cmd.Flags().BoolVarP(&opts.Confirmed, "yes", "y", false, "Skip the confirmation prompt") return cmd } func deleteRun(opts *DeleteOptions) error { httpClient, err := opts.HttpClient() if err != nil { return err } cfg, err := opts.Config() if err != nil { return err } host, _ := cfg.Authentication().DefaultHost() gpgKeys, err := getGPGKeys(httpClient, host) if err != nil { return err } id := "" for _, gpgKey := range gpgKeys { if gpgKey.KeyID == opts.KeyID { id = strconv.Itoa(gpgKey.ID) break } } if id == "" { return fmt.Errorf("unable to delete GPG key %s: either the GPG key is not found or it is not owned by you", opts.KeyID) } if !opts.Confirmed { if err := opts.Prompter.ConfirmDeletion(opts.KeyID); err != nil { return err } } err = deleteGPGKey(httpClient, host, id) if err != nil { return err } if opts.IO.IsStdoutTTY() { cs := opts.IO.ColorScheme() fmt.Fprintf(opts.IO.Out, "%s GPG key %s deleted from your account\n", cs.SuccessIcon(), opts.KeyID) } return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/gpg-key/delete/delete_test.go
pkg/cmd/gpg-key/delete/delete_test.go
package delete import ( "bytes" "net/http" "testing" "github.com/cli/cli/v2/internal/config" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/go-gh/v2/pkg/api" "github.com/google/shlex" "github.com/stretchr/testify/assert" ) func TestNewCmdDelete(t *testing.T) { tests := []struct { name string tty bool input string output DeleteOptions wantErr bool wantErrMsg string }{ { name: "tty", tty: true, input: "ABC123", output: DeleteOptions{KeyID: "ABC123", Confirmed: false}, }, { name: "confirm flag tty", tty: true, input: "ABC123 --yes", output: DeleteOptions{KeyID: "ABC123", Confirmed: true}, }, { name: "shorthand confirm flag tty", tty: true, input: "ABC123 -y", output: DeleteOptions{KeyID: "ABC123", Confirmed: true}, }, { name: "no tty", input: "ABC123", wantErr: true, wantErrMsg: "--yes required when not running interactively", }, { name: "confirm flag no tty", input: "ABC123 --yes", output: DeleteOptions{KeyID: "ABC123", Confirmed: true}, }, { name: "shorthand confirm flag no tty", input: "ABC123 -y", output: DeleteOptions{KeyID: "ABC123", Confirmed: true}, }, { name: "no args", input: "", wantErr: true, wantErrMsg: "cannot delete: key id required", }, { name: "too many args", input: "ABC123 XYZ", wantErr: true, wantErrMsg: "too many arguments", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() ios.SetStdinTTY(tt.tty) ios.SetStdoutTTY(tt.tty) f := &cmdutil.Factory{ IOStreams: ios, } argv, err := shlex.Split(tt.input) assert.NoError(t, err) var cmdOpts *DeleteOptions cmd := NewCmdDelete(f, func(opts *DeleteOptions) error { cmdOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err = cmd.ExecuteC() if tt.wantErr { assert.Error(t, err) assert.EqualError(t, err, tt.wantErrMsg) return } assert.NoError(t, err) assert.Equal(t, tt.output.KeyID, cmdOpts.KeyID) assert.Equal(t, tt.output.Confirmed, cmdOpts.Confirmed) }) } } func Test_deleteRun(t *testing.T) { keysResp := "[{\"id\":123,\"key_id\":\"ABC123\"}]" tests := []struct { name string tty bool opts DeleteOptions httpStubs func(*httpmock.Registry) prompterStubs func(*prompter.PrompterMock) wantStdout string wantErr bool wantErrMsg string }{ { name: "delete tty", tty: true, opts: DeleteOptions{KeyID: "ABC123", Confirmed: false}, prompterStubs: func(pm *prompter.PrompterMock) { pm.ConfirmDeletionFunc = func(_ string) error { return nil } }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("GET", "user/gpg_keys"), httpmock.StatusStringResponse(200, keysResp)) reg.Register(httpmock.REST("DELETE", "user/gpg_keys/123"), httpmock.StatusStringResponse(204, "")) }, wantStdout: "✓ GPG key ABC123 deleted from your account\n", }, { name: "delete with confirm flag tty", tty: true, opts: DeleteOptions{KeyID: "ABC123", Confirmed: true}, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("GET", "user/gpg_keys"), httpmock.StatusStringResponse(200, keysResp)) reg.Register(httpmock.REST("DELETE", "user/gpg_keys/123"), httpmock.StatusStringResponse(204, "")) }, wantStdout: "✓ GPG key ABC123 deleted from your account\n", }, { name: "not found tty", tty: true, opts: DeleteOptions{KeyID: "ABC123", Confirmed: true}, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("GET", "user/gpg_keys"), httpmock.StatusStringResponse(200, "[]")) }, wantErr: true, wantErrMsg: "unable to delete GPG key ABC123: either the GPG key is not found or it is not owned by you", }, { name: "delete no tty", opts: DeleteOptions{KeyID: "ABC123", Confirmed: true}, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("GET", "user/gpg_keys"), httpmock.StatusStringResponse(200, keysResp)) reg.Register(httpmock.REST("DELETE", "user/gpg_keys/123"), httpmock.StatusStringResponse(204, "")) }, wantStdout: "", }, { name: "not found no tty", opts: DeleteOptions{KeyID: "ABC123", Confirmed: true}, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("GET", "user/gpg_keys"), httpmock.StatusStringResponse(200, "[]")) }, wantErr: true, wantErrMsg: "unable to delete GPG key ABC123: either the GPG key is not found or it is not owned by you", }, { name: "delete failed", opts: DeleteOptions{KeyID: "ABC123", Confirmed: true}, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("GET", "user/gpg_keys"), httpmock.StatusStringResponse(200, keysResp)) reg.Register(httpmock.REST("DELETE", "user/gpg_keys/123"), httpmock.JSONErrorResponse(404, api.HTTPError{ StatusCode: 404, Message: "GPG key 123 not found", })) }, wantErr: true, wantErrMsg: "HTTP 404: GPG key 123 not found (https://api.github.com/user/gpg_keys/123)", }, } for _, tt := range tests { pm := &prompter.PrompterMock{} if tt.prompterStubs != nil { tt.prompterStubs(pm) } tt.opts.Prompter = pm reg := &httpmock.Registry{} if tt.httpStubs != nil { tt.httpStubs(reg) } tt.opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } tt.opts.Config = func() (gh.Config, error) { return config.NewBlankConfig(), nil } ios, _, stdout, _ := iostreams.Test() ios.SetStdinTTY(tt.tty) ios.SetStdoutTTY(tt.tty) tt.opts.IO = ios t.Run(tt.name, func(t *testing.T) { err := deleteRun(&tt.opts) reg.Verify(t) if tt.wantErr { assert.Error(t, err) assert.EqualError(t, err, tt.wantErrMsg) return } assert.NoError(t, err) assert.Equal(t, tt.wantStdout, stdout.String()) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/gpg-key/delete/http.go
pkg/cmd/gpg-key/delete/http.go
package delete import ( "encoding/json" "fmt" "io" "net/http" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghinstance" ) type gpgKey struct { ID int KeyID string `json:"key_id"` } func deleteGPGKey(httpClient *http.Client, host, id string) error { url := fmt.Sprintf("%suser/gpg_keys/%s", ghinstance.RESTPrefix(host), id) req, err := http.NewRequest("DELETE", url, nil) if err != nil { return err } resp, err := httpClient.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode > 299 { return api.HandleHTTPError(resp) } return nil } func getGPGKeys(httpClient *http.Client, host string) ([]gpgKey, error) { resource := "user/gpg_keys" url := fmt.Sprintf("%s%s?per_page=%d", ghinstance.RESTPrefix(host), resource, 100) req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } resp, err := httpClient.Do(req) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode > 299 { return nil, api.HandleHTTPError(resp) } b, err := io.ReadAll(resp.Body) if err != nil { return nil, err } var keys []gpgKey err = json.Unmarshal(b, &keys) if err != nil { return nil, err } return keys, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/gpg-key/list/list_test.go
pkg/cmd/gpg-key/list/list_test.go
package list import ( "fmt" "net/http" "testing" "time" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/config" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/stretchr/testify/assert" ) func Test_listRun(t *testing.T) { tests := []struct { name string opts ListOptions isTTY bool wantStdout string wantStderr string wantErr bool }{ { name: "list tty", opts: ListOptions{HTTPClient: func() (*http.Client, error) { createdAt := time.Now().Add(time.Duration(-24) * time.Hour) expiresAt, _ := time.Parse(time.RFC3339, "2099-01-01T15:44:24+01:00") noExpires := time.Time{} reg := &httpmock.Registry{} reg.Register( httpmock.REST("GET", "user/gpg_keys"), httpmock.StringResponse(fmt.Sprintf(`[ { "id": 1234, "key_id": "ABCDEF1234567890", "public_key": "xJMEWfoofoofoo", "emails": [{"email": "johnny@test.com"}], "created_at": "%[1]s", "expires_at": "%[2]s" }, { "id": 5678, "key_id": "1234567890ABCDEF", "public_key": "xJMEWbarbarbar", "emails": [{"email": "monalisa@github.com"}], "created_at": "%[1]s", "expires_at": "%[3]s" } ]`, createdAt.Format(time.RFC3339), expiresAt.Format(time.RFC3339), noExpires.Format(time.RFC3339))), ) return &http.Client{Transport: reg}, nil }}, isTTY: true, wantStdout: heredoc.Doc(` EMAIL KEY ID PUBLIC KEY ADDED EXPIRES johnny@test.com ABCDEF123456... xJMEWfoofoofoo about 1 day ago 2099-01-01 monalisa@github... 1234567890AB... xJMEWbarbarbar about 1 day ago Never `), wantStderr: "", }, { name: "list non-tty", opts: ListOptions{HTTPClient: func() (*http.Client, error) { createdAt1, _ := time.Parse(time.RFC3339, "2020-06-11T15:44:24+01:00") expiresAt, _ := time.Parse(time.RFC3339, "2099-01-01T15:44:24+01:00") createdAt2, _ := time.Parse(time.RFC3339, "2021-01-11T15:44:24+01:00") noExpires := time.Time{} reg := &httpmock.Registry{} reg.Register( httpmock.REST("GET", "user/gpg_keys"), httpmock.StringResponse(fmt.Sprintf(`[ { "id": 1234, "key_id": "ABCDEF1234567890", "public_key": "xJMEWfoofoofoo", "emails": [{"email": "johnny@test.com"}], "created_at": "%[1]s", "expires_at": "%[2]s" }, { "id": 5678, "key_id": "1234567890ABCDEF", "public_key": "xJMEWbarbarbar", "emails": [{"email": "monalisa@github.com"}], "created_at": "%[3]s", "expires_at": "%[4]s" } ]`, createdAt1.Format(time.RFC3339), expiresAt.Format(time.RFC3339), createdAt2.Format(time.RFC3339), noExpires.Format(time.RFC3339))), ) return &http.Client{Transport: reg}, nil }}, isTTY: false, wantStdout: heredoc.Doc(` johnny@test.com ABCDEF1234567890 xJMEWfoofoofoo 2020-06-11T15:44:24+01:00 2099-01-01T15:44:24+01:00 monalisa@github.com 1234567890ABCDEF xJMEWbarbarbar 2021-01-11T15:44:24+01:00 0001-01-01T00:00:00Z `), wantStderr: "", }, { name: "no keys", opts: ListOptions{ HTTPClient: func() (*http.Client, error) { reg := &httpmock.Registry{} reg.Register( httpmock.REST("GET", "user/gpg_keys"), httpmock.StringResponse(`[]`), ) return &http.Client{Transport: reg}, nil }, }, wantStdout: "", wantStderr: "", wantErr: true, isTTY: true, }, } 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) opts := tt.opts opts.IO = ios opts.Config = func() (gh.Config, error) { return config.NewBlankConfig(), nil } err := listRun(&opts) if tt.wantErr { 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/gpg-key/list/list.go
pkg/cmd/gpg-key/list/list.go
package list import ( "errors" "fmt" "net/http" "time" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/tableprinter" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type ListOptions struct { IO *iostreams.IOStreams Config func() (gh.Config, error) HTTPClient func() (*http.Client, error) } func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Command { opts := &ListOptions{ IO: f.IOStreams, Config: f.Config, HTTPClient: f.HttpClient, } cmd := &cobra.Command{ Use: "list", Short: "Lists GPG keys in your GitHub account", Aliases: []string{"ls"}, Args: cobra.ExactArgs(0), RunE: func(cmd *cobra.Command, args []string) error { if runF != nil { return runF(opts) } return listRun(opts) }, } return cmd } func listRun(opts *ListOptions) error { apiClient, err := opts.HTTPClient() if err != nil { return err } cfg, err := opts.Config() if err != nil { return err } host, _ := cfg.Authentication().DefaultHost() gpgKeys, err := userKeys(apiClient, host, "") if err != nil { if errors.Is(err, errScopes) { cs := opts.IO.ColorScheme() fmt.Fprint(opts.IO.ErrOut, "Error: insufficient OAuth scopes to list GPG keys\n") fmt.Fprintf(opts.IO.ErrOut, "Run the following to grant scopes: %s\n", cs.Bold("gh auth refresh -s read:gpg_key")) return cmdutil.SilentError } return err } if len(gpgKeys) == 0 { return cmdutil.NewNoResultsError("no GPG keys present in the GitHub account") } t := tableprinter.New(opts.IO, tableprinter.WithHeader("EMAIL", "KEY ID", "PUBLIC KEY", "ADDED", "EXPIRES")) cs := opts.IO.ColorScheme() now := time.Now() for _, gpgKey := range gpgKeys { t.AddField(gpgKey.Emails.String()) t.AddField(gpgKey.KeyID) t.AddField(gpgKey.PublicKey, tableprinter.WithTruncate(truncateMiddle)) t.AddTimeField(now, gpgKey.CreatedAt, cs.Muted) expiresAt := gpgKey.ExpiresAt.Format(time.RFC3339) if t.IsTTY() { if gpgKey.ExpiresAt.IsZero() { expiresAt = "Never" } else { expiresAt = gpgKey.ExpiresAt.Format("2006-01-02") } } t.AddField(expiresAt, tableprinter.WithColor(cs.Muted)) t.EndRow() } return t.Render() } func truncateMiddle(maxWidth int, t string) string { if len(t) <= maxWidth { return t } ellipsis := "..." if maxWidth < len(ellipsis)+2 { return t[0:maxWidth] } halfWidth := (maxWidth - len(ellipsis)) / 2 remainder := (maxWidth - len(ellipsis)) % 2 return t[0:halfWidth+remainder] + ellipsis + t[len(t)-halfWidth:] }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/gpg-key/list/http.go
pkg/cmd/gpg-key/list/http.go
package list import ( "encoding/json" "errors" "fmt" "io" "net/http" "strings" "time" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghinstance" ) var errScopes = errors.New("insufficient OAuth scopes") type emails []email type email struct { Email string `json:"email"` } func (es emails) String() string { s := []string{} for _, e := range es { s = append(s, e.Email) } return strings.Join(s, ", ") } type gpgKey struct { KeyID string `json:"key_id"` PublicKey string `json:"public_key"` Emails emails `json:"emails"` CreatedAt time.Time `json:"created_at"` ExpiresAt time.Time `json:"expires_at"` } func userKeys(httpClient *http.Client, host, userHandle string) ([]gpgKey, error) { resource := "user/gpg_keys" if userHandle != "" { resource = fmt.Sprintf("users/%s/gpg_keys", userHandle) } url := fmt.Sprintf("%s%s?per_page=%d", ghinstance.RESTPrefix(host), resource, 100) req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } resp, err := httpClient.Do(req) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode == 404 { return nil, errScopes } else if resp.StatusCode > 299 { return nil, api.HandleHTTPError(resp) } b, err := io.ReadAll(resp.Body) if err != nil { return nil, err } var keys []gpgKey err = json.Unmarshal(b, &keys) if err != nil { return nil, err } return keys, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/gpg-key/add/add.go
pkg/cmd/gpg-key/add/add.go
package add import ( "errors" "fmt" "io" "net/http" "os" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type AddOptions struct { IO *iostreams.IOStreams Config func() (gh.Config, error) HTTPClient func() (*http.Client, error) KeyFile string Title string } func NewCmdAdd(f *cmdutil.Factory, runF func(*AddOptions) error) *cobra.Command { opts := &AddOptions{ HTTPClient: f.HttpClient, Config: f.Config, IO: f.IOStreams, } cmd := &cobra.Command{ Use: "add [<key-file>]", Short: "Add a GPG key to your GitHub account", Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { if len(args) == 0 { if opts.IO.IsStdoutTTY() && opts.IO.IsStdinTTY() { return cmdutil.FlagErrorf("GPG key file missing") } opts.KeyFile = "-" } else { opts.KeyFile = args[0] } if runF != nil { return runF(opts) } return runAdd(opts) }, } cmd.Flags().StringVarP(&opts.Title, "title", "t", "", "Title for the new key") return cmd } func runAdd(opts *AddOptions) error { httpClient, err := opts.HTTPClient() if err != nil { return err } var keyReader io.Reader if opts.KeyFile == "-" { keyReader = opts.IO.In defer opts.IO.In.Close() } else { f, err := os.Open(opts.KeyFile) if err != nil { return err } defer f.Close() keyReader = f } cfg, err := opts.Config() if err != nil { return err } hostname, _ := cfg.Authentication().DefaultHost() err = gpgKeyUpload(httpClient, hostname, keyReader, opts.Title) if err != nil { cs := opts.IO.ColorScheme() if errors.Is(err, errScopesMissing) { fmt.Fprint(opts.IO.ErrOut, "Error: insufficient OAuth scopes to list GPG keys\n") fmt.Fprintf(opts.IO.ErrOut, "Run the following to grant scopes: %s\n", cs.Bold("gh auth refresh -s write:gpg_key")) return cmdutil.SilentError } if errors.Is(err, errDuplicateKey) { fmt.Fprintf(opts.IO.ErrOut, "%s Error: the key already exists in your account\n", cs.FailureIcon()) return cmdutil.SilentError } if errors.Is(err, errWrongFormat) { fmt.Fprint(opts.IO.ErrOut, heredoc.Docf(` %s Error: the GPG key you are trying to upload might not be in ASCII-armored format. Find your GPG key ID with: %s Then add it to your account: %s `, cs.FailureIcon(), cs.Bold("gpg --list-keys"), cs.Bold("gpg --armor --export <ID> | gh gpg-key add -"))) return cmdutil.SilentError } return err } if opts.IO.IsStdoutTTY() { cs := opts.IO.ColorScheme() fmt.Fprintf(opts.IO.Out, "%s GPG key added to your account\n", cs.SuccessIcon()) } return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/gpg-key/add/http.go
pkg/cmd/gpg-key/add/http.go
package add import ( "bytes" "encoding/json" "errors" "io" "net/http" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghinstance" ) var errScopesMissing = errors.New("insufficient OAuth scopes") var errDuplicateKey = errors.New("key already exists") var errWrongFormat = errors.New("key in wrong format") func gpgKeyUpload(httpClient *http.Client, hostname string, keyFile io.Reader, title string) error { url := ghinstance.RESTPrefix(hostname) + "user/gpg_keys" keyBytes, err := io.ReadAll(keyFile) if err != nil { return err } payload := map[string]string{ "armored_public_key": string(keyBytes), } if title != "" { payload["name"] = title } payloadBytes, err := json.Marshal(payload) if err != nil { return err } req, err := http.NewRequest("POST", url, bytes.NewBuffer(payloadBytes)) if err != nil { return err } resp, err := httpClient.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode == 404 { return errScopesMissing } else if resp.StatusCode > 299 { err := api.HandleHTTPError(resp) var httpError api.HTTPError if errors.As(err, &httpError) { for _, e := range httpError.Errors { if resp.StatusCode == 422 && e.Field == "key_id" && e.Message == "key_id already exists" { return errDuplicateKey } } } if resp.StatusCode == 422 && !isGpgKeyArmored(keyBytes) { return errWrongFormat } return err } _, _ = io.Copy(io.Discard, resp.Body) return nil } func isGpgKeyArmored(keyBytes []byte) bool { return bytes.Contains(keyBytes, []byte("-----BEGIN ")) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/gpg-key/add/add_test.go
pkg/cmd/gpg-key/add/add_test.go
package add import ( "net/http" "testing" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/config" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/stretchr/testify/assert" ) func Test_runAdd(t *testing.T) { tests := []struct { name string stdin string httpStubs func(*httpmock.Registry) wantStdout string wantStderr string wantErrMsg string opts AddOptions }{ { name: "valid key", stdin: "-----BEGIN PGP PUBLIC KEY BLOCK-----", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("POST", "user/gpg_keys"), httpmock.RESTPayload(200, ``, func(payload map[string]interface{}) { assert.Contains(t, payload, "armored_public_key") assert.NotContains(t, payload, "title") })) }, wantStdout: "✓ GPG key added to your account\n", wantStderr: "", wantErrMsg: "", opts: AddOptions{KeyFile: "-"}, }, { name: "valid key with title", stdin: "-----BEGIN PGP PUBLIC KEY BLOCK-----", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("POST", "user/gpg_keys"), httpmock.RESTPayload(200, ``, func(payload map[string]interface{}) { assert.Contains(t, payload, "armored_public_key") assert.Contains(t, payload, "name") })) }, wantStdout: "✓ GPG key added to your account\n", wantStderr: "", wantErrMsg: "", opts: AddOptions{KeyFile: "-", Title: "some title"}, }, { name: "binary format fails", stdin: "gCAAAAA7H7MHTZWFLJKD3vP4F7v", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("POST", "user/gpg_keys"), httpmock.StatusStringResponse(422, `{ "message": "Validation Failed", "errors": [{ "resource": "GpgKey", "code": "custom", "message": "We got an error doing that." }], "documentation_url": "https://docs.github.com/v3/users/gpg_keys" }`), ) }, wantStdout: "", wantStderr: heredoc.Doc(` X Error: the GPG key you are trying to upload might not be in ASCII-armored format. Find your GPG key ID with: gpg --list-keys Then add it to your account: gpg --armor --export <ID> | gh gpg-key add - `), wantErrMsg: "SilentError", opts: AddOptions{KeyFile: "-"}, }, { name: "duplicate key", stdin: "-----BEGIN PGP PUBLIC KEY BLOCK-----", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("POST", "user/gpg_keys"), httpmock.WithHeader(httpmock.StatusStringResponse(422, `{ "message": "Validation Failed", "errors": [{ "resource": "GpgKey", "code": "custom", "field": "key_id", "message": "key_id already exists" }, { "resource": "GpgKey", "code": "custom", "field": "public_key", "message": "public_key already exists" }], "documentation_url": "https://docs.github.com/v3/users/gpg_keys" }`), "Content-type", "application/json"), ) }, wantStdout: "", wantStderr: "X Error: the key already exists in your account\n", wantErrMsg: "SilentError", opts: AddOptions{KeyFile: "-"}, }, } for _, tt := range tests { ios, stdin, stdout, stderr := iostreams.Test() ios.SetStdinTTY(true) ios.SetStdoutTTY(true) ios.SetStderrTTY(true) stdin.WriteString(tt.stdin) reg := &httpmock.Registry{} tt.opts.IO = ios tt.opts.HTTPClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } if tt.httpStubs != nil { tt.httpStubs(reg) } tt.opts.Config = func() (gh.Config, error) { return config.NewBlankConfig(), nil } t.Run(tt.name, func(t *testing.T) { defer reg.Verify(t) err := runAdd(&tt.opts) if tt.wantErrMsg != "" { assert.Equal(t, tt.wantErrMsg, err.Error()) } else { assert.NoError(t, err) } assert.Equal(t, tt.wantStdout, stdout.String()) assert.Equal(t, tt.wantStderr, stderr.String()) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/config/config.go
pkg/cmd/config/config.go
package config import ( "fmt" "strings" "github.com/cli/cli/v2/internal/config" cmdClearCache "github.com/cli/cli/v2/pkg/cmd/config/clear-cache" cmdGet "github.com/cli/cli/v2/pkg/cmd/config/get" cmdList "github.com/cli/cli/v2/pkg/cmd/config/list" cmdSet "github.com/cli/cli/v2/pkg/cmd/config/set" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/spf13/cobra" ) func NewCmdConfig(f *cmdutil.Factory) *cobra.Command { longDoc := strings.Builder{} longDoc.WriteString("Display or change configuration settings for gh.\n\n") longDoc.WriteString("Current respected settings:\n") for _, co := range config.Options { longDoc.WriteString(fmt.Sprintf("- `%s`: %s", co.Key, co.Description)) if len(co.AllowedValues) > 0 { longDoc.WriteString(fmt.Sprintf(" `{%s}`", strings.Join(co.AllowedValues, " | "))) } if co.DefaultValue != "" { longDoc.WriteString(fmt.Sprintf(" (default `%s`)", co.DefaultValue)) } longDoc.WriteRune('\n') } cmd := &cobra.Command{ Use: "config <command>", Short: "Manage configuration for gh", Long: longDoc.String(), } cmdutil.DisableAuthCheck(cmd) cmd.AddCommand(cmdGet.NewCmdConfigGet(f, nil)) cmd.AddCommand(cmdSet.NewCmdConfigSet(f, nil)) cmd.AddCommand(cmdList.NewCmdConfigList(f, nil)) cmd.AddCommand(cmdClearCache.NewCmdConfigClearCache(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/config/list/list_test.go
pkg/cmd/config/list/list_test.go
package list import ( "bytes" "testing" "github.com/MakeNowJust/heredoc" "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/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNewCmdConfigList(t *testing.T) { tests := []struct { name string input string output ListOptions wantsErr bool }{ { name: "no arguments", input: "", output: ListOptions{}, wantsErr: false, }, { name: "list with host", input: "--host HOST.com", output: ListOptions{Hostname: "HOST.com"}, wantsErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { f := &cmdutil.Factory{ Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, } argv, err := shlex.Split(tt.input) assert.NoError(t, err) var gotOpts *ListOptions cmd := NewCmdConfigList(f, func(opts *ListOptions) 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.Hostname, gotOpts.Hostname) }) } } func Test_listRun(t *testing.T) { tests := []struct { name string input *ListOptions config gh.Config stdout string wantErr bool }{ { name: "list", config: func() gh.Config { cfg := config.NewBlankConfig() cfg.Set("HOST", "git_protocol", "ssh") cfg.Set("HOST", "editor", "/usr/bin/vim") cfg.Set("HOST", "prompt", "disabled") cfg.Set("HOST", "prefer_editor_prompt", "enabled") cfg.Set("HOST", "pager", "less") cfg.Set("HOST", "http_unix_socket", "") cfg.Set("HOST", "browser", "brave") return cfg }(), input: &ListOptions{Hostname: "HOST"}, stdout: heredoc.Doc(` git_protocol=ssh editor=/usr/bin/vim prompt=disabled prefer_editor_prompt=enabled pager=less http_unix_socket= browser=brave color_labels=disabled accessible_colors=disabled accessible_prompter=disabled spinner=enabled `), }, } for _, tt := range tests { ios, _, stdout, _ := iostreams.Test() tt.input.IO = ios tt.input.Config = func() (gh.Config, error) { return tt.config, nil } t.Run(tt.name, func(t *testing.T) { err := listRun(tt.input) require.NoError(t, err) require.Equal(t, tt.stdout, stdout.String()) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false