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/project/item-delete/item_delete_test.go
pkg/cmd/project/item-delete/item_delete_test.go
package itemdelete import ( "testing" "github.com/cli/cli/v2/pkg/cmd/project/shared/queries" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" "gopkg.in/h2non/gock.v1" ) func TestNewCmdDeleteItem(t *testing.T) { tests := []struct { name string cli string wants deleteItemOpts wantsErr bool wantsErrMsg string wantsExporter bool }{ { name: "missing-id", cli: "", wantsErr: true, wantsErrMsg: "required flag(s) \"id\" not set", }, { name: "not-a-number", cli: "x --id 123", wantsErr: true, wantsErrMsg: "invalid number: x", }, { name: "item-id", cli: "--id 123", wants: deleteItemOpts{ itemID: "123", }, }, { name: "number", cli: "456 --id 123", wants: deleteItemOpts{ number: 456, itemID: "123", }, }, { name: "owner", cli: "--owner monalisa --id 123", wants: deleteItemOpts{ owner: "monalisa", itemID: "123", }, }, { name: "json", cli: "--format json --id 123", wants: deleteItemOpts{ itemID: "123", }, wantsExporter: true, }, } t.Setenv("GH_TOKEN", "auth-token") for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() f := &cmdutil.Factory{ IOStreams: ios, } argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts deleteItemOpts cmd := NewCmdDeleteItem(f, func(config deleteItemConfig) error { gotOpts = config.opts return nil }) cmd.SetArgs(argv) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) assert.Equal(t, tt.wantsErrMsg, err.Error()) return } assert.NoError(t, err) assert.Equal(t, tt.wants.number, gotOpts.number) assert.Equal(t, tt.wants.owner, gotOpts.owner) assert.Equal(t, tt.wants.itemID, gotOpts.itemID) assert.Equal(t, tt.wantsExporter, gotOpts.exporter != nil) }) } } func TestRunDelete_User(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get user ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]interface{}{ "login": "monalisa", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "id": "an ID", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"organization"}, }, }, }) // get project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserProject.*", "variables": map[string]interface{}{ "login": "monalisa", "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "projectV2": map[string]interface{}{ "id": "an ID", }, }, }, }) // delete item gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation DeleteProjectItem.*","variables":{"input":{"projectId":"an ID","itemId":"item ID"}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "deleteProjectV2Item": map[string]interface{}{ "deletedItemId": "item ID", }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) config := deleteItemConfig{ opts: deleteItemOpts{ owner: "monalisa", number: 1, itemID: "item ID", }, client: client, io: ios, } err := runDeleteItem(config) assert.NoError(t, err) assert.Equal( t, "Deleted item\n", stdout.String()) } func TestRunDelete_Org(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get org ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]interface{}{ "login": "github", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "organization": map[string]interface{}{ "id": "an ID", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"user"}, }, }, }) // get project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query OrgProject.*", "variables": map[string]interface{}{ "login": "github", "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "organization": map[string]interface{}{ "projectV2": map[string]interface{}{ "id": "an ID", }, }, }, }) // delete item gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation DeleteProjectItem.*","variables":{"input":{"projectId":"an ID","itemId":"item ID"}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "deleteProjectV2Item": map[string]interface{}{ "deletedItemId": "item ID", }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) config := deleteItemConfig{ opts: deleteItemOpts{ owner: "github", number: 1, itemID: "item ID", }, client: client, io: ios, } err := runDeleteItem(config) assert.NoError(t, err) assert.Equal( t, "Deleted item\n", stdout.String()) } func TestRunDelete_Me(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get viewer ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query ViewerOwner.*", }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "viewer": map[string]interface{}{ "id": "an ID", }, }, }) // get project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query ViewerProject.*", "variables": map[string]interface{}{ "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "viewer": map[string]interface{}{ "projectV2": map[string]interface{}{ "id": "an ID", }, }, }, }) // delete item gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation DeleteProjectItem.*","variables":{"input":{"projectId":"an ID","itemId":"item ID"}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "deleteProjectV2Item": map[string]interface{}{ "deletedItemId": "item ID", }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) config := deleteItemConfig{ opts: deleteItemOpts{ owner: "@me", number: 1, itemID: "item ID", }, client: client, io: ios, } err := runDeleteItem(config) assert.NoError(t, err) assert.Equal( t, "Deleted item\n", stdout.String()) } func TestRunDelete_JSON(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get user ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]interface{}{ "login": "monalisa", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "id": "an ID", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"organization"}, }, }, }) // get project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserProject.*", "variables": map[string]interface{}{ "login": "monalisa", "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "projectV2": map[string]interface{}{ "id": "an ID", }, }, }, }) // delete item gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation DeleteProjectItem.*","variables":{"input":{"projectId":"an ID","itemId":"item ID"}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "deleteProjectV2Item": map[string]interface{}{ "deletedItemId": "item ID", }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() config := deleteItemConfig{ opts: deleteItemOpts{ owner: "monalisa", number: 1, itemID: "item ID", exporter: cmdutil.NewJSONExporter(), }, client: client, io: ios, } err := runDeleteItem(config) assert.NoError(t, err) assert.JSONEq( t, `{"id":"item ID"}`, stdout.String()) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/item-delete/item_delete.go
pkg/cmd/project/item-delete/item_delete.go
package itemdelete import ( "fmt" "strconv" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/pkg/cmd/project/shared/client" "github.com/cli/cli/v2/pkg/cmd/project/shared/queries" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/shurcooL/githubv4" "github.com/spf13/cobra" ) type deleteItemOpts struct { owner string number int32 itemID string projectID string exporter cmdutil.Exporter } type deleteItemConfig struct { client *queries.Client opts deleteItemOpts io *iostreams.IOStreams } type deleteProjectItemMutation struct { DeleteProjectItem struct { DeletedItemId githubv4.ID `graphql:"deletedItemId"` } `graphql:"deleteProjectV2Item(input:$input)"` } func NewCmdDeleteItem(f *cmdutil.Factory, runF func(config deleteItemConfig) error) *cobra.Command { opts := deleteItemOpts{} deleteItemCmd := &cobra.Command{ Short: "Delete an item from a project by ID", Use: "item-delete [<number>]", Example: heredoc.Doc(` # Delete an item in the current user's project "1" $ gh project item-delete 1 --owner "@me" --id <item-id> `), Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { client, err := client.New(f) if err != nil { return err } if len(args) == 1 { num, err := strconv.ParseInt(args[0], 10, 32) if err != nil { return cmdutil.FlagErrorf("invalid number: %v", args[0]) } opts.number = int32(num) } config := deleteItemConfig{ client: client, opts: opts, io: f.IOStreams, } // allow testing of the command without actually running it if runF != nil { return runF(config) } return runDeleteItem(config) }, } deleteItemCmd.Flags().StringVar(&opts.owner, "owner", "", "Login of the owner. Use \"@me\" for the current user.") deleteItemCmd.Flags().StringVar(&opts.itemID, "id", "", "ID of the item to delete") cmdutil.AddFormatFlags(deleteItemCmd, &opts.exporter) _ = deleteItemCmd.MarkFlagRequired("id") return deleteItemCmd } func runDeleteItem(config deleteItemConfig) error { canPrompt := config.io.CanPrompt() owner, err := config.client.NewOwner(canPrompt, config.opts.owner) if err != nil { return err } project, err := config.client.NewProject(canPrompt, owner, config.opts.number, false) if err != nil { return err } config.opts.projectID = project.ID query, variables := deleteItemArgs(config) err = config.client.Mutate("DeleteProjectItem", query, variables) if err != nil { return err } if config.opts.exporter != nil { return printJSON(config, query.DeleteProjectItem.DeletedItemId) } return printResults(config) } func deleteItemArgs(config deleteItemConfig) (*deleteProjectItemMutation, map[string]interface{}) { return &deleteProjectItemMutation{}, map[string]interface{}{ "input": githubv4.DeleteProjectV2ItemInput{ ProjectID: githubv4.ID(config.opts.projectID), ItemID: githubv4.ID(config.opts.itemID), }, } } func printResults(config deleteItemConfig) error { if !config.io.IsStdoutTTY() { return nil } _, err := fmt.Fprintf(config.io.Out, "Deleted item\n") return err } func printJSON(config deleteItemConfig, id githubv4.ID) error { m := map[string]interface{}{ "id": id, } return config.opts.exporter.Write(config.io, m) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/edit/edit.go
pkg/cmd/project/edit/edit.go
package edit import ( "fmt" "strconv" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/pkg/cmd/project/shared/client" "github.com/cli/cli/v2/pkg/cmd/project/shared/queries" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/shurcooL/githubv4" "github.com/spf13/cobra" ) type editOpts struct { number int32 owner string title string readme string visibility string shortDescription string projectID string exporter cmdutil.Exporter } type editConfig struct { client *queries.Client opts editOpts io *iostreams.IOStreams } type updateProjectMutation struct { UpdateProjectV2 struct { ProjectV2 queries.Project `graphql:"projectV2"` } `graphql:"updateProjectV2(input:$input)"` } const projectVisibilityPublic = "PUBLIC" const projectVisibilityPrivate = "PRIVATE" func NewCmdEdit(f *cmdutil.Factory, runF func(config editConfig) error) *cobra.Command { opts := editOpts{} editCmd := &cobra.Command{ Short: "Edit a project", Use: "edit [<number>]", Example: heredoc.Doc(` # Edit the title of monalisa's project "1" $ gh project edit 1 --owner monalisa --title "New title" `), Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { client, err := client.New(f) if err != nil { return err } if len(args) == 1 { num, err := strconv.ParseInt(args[0], 10, 32) if err != nil { return cmdutil.FlagErrorf("invalid number: %v", args[0]) } opts.number = int32(num) } config := editConfig{ client: client, opts: opts, io: f.IOStreams, } if config.opts.title == "" && config.opts.shortDescription == "" && config.opts.readme == "" && config.opts.visibility == "" { return fmt.Errorf("no fields to edit") } // allow testing of the command without actually running it if runF != nil { return runF(config) } return runEdit(config) }, } editCmd.Flags().StringVar(&opts.owner, "owner", "", "Login of the owner. Use \"@me\" for the current user.") cmdutil.StringEnumFlag(editCmd, &opts.visibility, "visibility", "", "", []string{projectVisibilityPublic, projectVisibilityPrivate}, "Change project visibility") editCmd.Flags().StringVar(&opts.title, "title", "", "New title for the project") editCmd.Flags().StringVar(&opts.readme, "readme", "", "New readme for the project") editCmd.Flags().StringVarP(&opts.shortDescription, "description", "d", "", "New description of the project") cmdutil.AddFormatFlags(editCmd, &opts.exporter) return editCmd } func runEdit(config editConfig) error { canPrompt := config.io.CanPrompt() owner, err := config.client.NewOwner(canPrompt, config.opts.owner) if err != nil { return err } project, err := config.client.NewProject(canPrompt, owner, config.opts.number, false) if err != nil { return err } config.opts.projectID = project.ID query, variables := editArgs(config) err = config.client.Mutate("UpdateProjectV2", query, variables) if err != nil { return err } if config.opts.exporter != nil { return config.opts.exporter.Write(config.io, query.UpdateProjectV2.ProjectV2) } return printResults(config, query.UpdateProjectV2.ProjectV2) } func editArgs(config editConfig) (*updateProjectMutation, map[string]interface{}) { variables := githubv4.UpdateProjectV2Input{ProjectID: githubv4.ID(config.opts.projectID)} if config.opts.title != "" { variables.Title = githubv4.NewString(githubv4.String(config.opts.title)) } if config.opts.shortDescription != "" { variables.ShortDescription = githubv4.NewString(githubv4.String(config.opts.shortDescription)) } if config.opts.readme != "" { variables.Readme = githubv4.NewString(githubv4.String(config.opts.readme)) } if config.opts.visibility != "" { if config.opts.visibility == projectVisibilityPublic { variables.Public = githubv4.NewBoolean(githubv4.Boolean(true)) } else if config.opts.visibility == projectVisibilityPrivate { variables.Public = githubv4.NewBoolean(githubv4.Boolean(false)) } } return &updateProjectMutation{}, map[string]interface{}{ "input": variables, "firstItems": githubv4.Int(0), "afterItems": (*githubv4.String)(nil), "firstFields": githubv4.Int(0), "afterFields": (*githubv4.String)(nil), } } func printResults(config editConfig, project queries.Project) error { if !config.io.IsStdoutTTY() { return nil } _, err := fmt.Fprintf(config.io.Out, "%s\n", project.URL) return err }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/edit/edit_test.go
pkg/cmd/project/edit/edit_test.go
package edit import ( "testing" "github.com/cli/cli/v2/pkg/cmd/project/shared/queries" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" "gopkg.in/h2non/gock.v1" ) func TestNewCmdEdit(t *testing.T) { tests := []struct { name string cli string wants editOpts wantsErr bool wantsErrMsg string wantsExporter bool }{ { name: "not-a-number", cli: "x", wantsErr: true, wantsErrMsg: "invalid number: x", }, { name: "visibility-error", cli: "--visibility v", wantsErr: true, wantsErrMsg: "invalid argument \"v\" for \"--visibility\" flag: valid values are {PUBLIC|PRIVATE}", }, { name: "no-args", cli: "", wantsErr: true, wantsErrMsg: "no fields to edit", }, { name: "title", cli: "--title t", wants: editOpts{ title: "t", }, }, { name: "number", cli: "123 --title t", wants: editOpts{ number: 123, title: "t", }, }, { name: "owner", cli: "--owner monalisa --title t", wants: editOpts{ owner: "monalisa", title: "t", }, }, { name: "readme", cli: "--readme r", wants: editOpts{ readme: "r", }, }, { name: "description", cli: "--description d", wants: editOpts{ shortDescription: "d", }, }, { name: "visibility", cli: "--visibility PUBLIC", wants: editOpts{ visibility: "PUBLIC", }, }, { name: "json", cli: "--format json --title t", wants: editOpts{ title: "t", }, wantsExporter: true, }, } t.Setenv("GH_TOKEN", "auth-token") for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() f := &cmdutil.Factory{ IOStreams: ios, } argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts editOpts cmd := NewCmdEdit(f, func(config editConfig) error { gotOpts = config.opts return nil }) cmd.SetArgs(argv) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) assert.Equal(t, tt.wantsErrMsg, err.Error()) return } assert.NoError(t, err) assert.Equal(t, tt.wants.number, gotOpts.number) assert.Equal(t, tt.wants.owner, gotOpts.owner) assert.Equal(t, tt.wants.visibility, gotOpts.visibility) assert.Equal(t, tt.wants.title, gotOpts.title) assert.Equal(t, tt.wants.readme, gotOpts.readme) assert.Equal(t, tt.wants.shortDescription, gotOpts.shortDescription) assert.Equal(t, tt.wantsExporter, gotOpts.exporter != nil) }) } } func TestRunUpdate_User(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get user ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]interface{}{ "login": "monalisa", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "id": "an ID", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"organization"}, }, }, }) // get user project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserProject.*", "variables": map[string]interface{}{ "login": "monalisa", "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "projectV2": map[string]string{ "id": "an ID", }, }, }, }) // edit project gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation UpdateProjectV2.*"variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"projectId":"an ID","title":"a new title","shortDescription":"a new description","readme":"a new readme","public":true}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "updateProjectV2": map[string]interface{}{ "projectV2": map[string]interface{}{ "title": "a title", "url": "http://a-url.com", "owner": map[string]string{ "login": "monalisa", }, }, }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) config := editConfig{ opts: editOpts{ number: 1, owner: "monalisa", title: "a new title", shortDescription: "a new description", visibility: "PUBLIC", readme: "a new readme", }, client: client, io: ios, } err := runEdit(config) assert.NoError(t, err) assert.Equal( t, "http://a-url.com\n", stdout.String()) } func TestRunUpdate_Org(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get org ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]interface{}{ "login": "github", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "organization": map[string]interface{}{ "id": "an ID", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"user"}, }, }, }) // get org project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query OrgProject.*", "variables": map[string]interface{}{ "login": "github", "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "organization": map[string]interface{}{ "projectV2": map[string]string{ "id": "an ID", }, }, }, }) // edit project gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation UpdateProjectV2.*"variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"projectId":"an ID","title":"a new title","shortDescription":"a new description","readme":"a new readme","public":true}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "updateProjectV2": map[string]interface{}{ "projectV2": map[string]interface{}{ "title": "a title", "url": "http://a-url.com", "owner": map[string]string{ "login": "monalisa", }, }, }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) config := editConfig{ opts: editOpts{ number: 1, owner: "github", title: "a new title", shortDescription: "a new description", visibility: "PUBLIC", readme: "a new readme", }, client: client, io: ios, } err := runEdit(config) assert.NoError(t, err) assert.Equal( t, "http://a-url.com\n", stdout.String()) } func TestRunUpdate_Me(t *testing.T) { defer gock.Off() // get viewer ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query ViewerOwner.*", }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "viewer": map[string]interface{}{ "id": "an ID", }, }, }) gock.Observe(gock.DumpRequest) // get viewer project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query ViewerProject.*", "variables": map[string]interface{}{ "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "viewer": map[string]interface{}{ "projectV2": map[string]string{ "id": "an ID", }, }, }, }) // edit project gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation UpdateProjectV2.*"variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"projectId":"an ID","title":"a new title","shortDescription":"a new description","readme":"a new readme","public":false}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "updateProjectV2": map[string]interface{}{ "projectV2": map[string]interface{}{ "title": "a title", "url": "http://a-url.com", "owner": map[string]string{ "login": "me", }, }, }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) config := editConfig{ opts: editOpts{ number: 1, owner: "@me", title: "a new title", shortDescription: "a new description", visibility: "PRIVATE", readme: "a new readme", }, client: client, io: ios, } err := runEdit(config) assert.NoError(t, err) assert.Equal( t, "http://a-url.com\n", stdout.String()) } func TestRunUpdate_OmitParams(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get user ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]interface{}{ "login": "monalisa", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "id": "an ID", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"organization"}, }, }, }) // get user project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserProject.*", "variables": map[string]interface{}{ "login": "monalisa", "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "projectV2": map[string]string{ "id": "an ID", }, }, }, }) // Update project gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation UpdateProjectV2.*"variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"projectId":"an ID","title":"another title"}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "updateProjectV2": map[string]interface{}{ "projectV2": map[string]interface{}{ "title": "a title", "url": "http://a-url.com", "owner": map[string]string{ "login": "monalisa", }, }, }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) config := editConfig{ opts: editOpts{ number: 1, owner: "monalisa", title: "another title", }, client: client, io: ios, } err := runEdit(config) assert.NoError(t, err) assert.Equal( t, "http://a-url.com\n", stdout.String()) } func TestRunUpdate_JSON(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get user ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]interface{}{ "login": "monalisa", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "id": "an ID", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"organization"}, }, }, }) // get user project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserProject.*", "variables": map[string]interface{}{ "login": "monalisa", "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "projectV2": map[string]string{ "id": "an ID", }, }, }, }) // edit project gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation UpdateProjectV2.*"variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"projectId":"an ID","title":"a new title","shortDescription":"a new description","readme":"a new readme","public":true}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "updateProjectV2": map[string]interface{}{ "projectV2": map[string]interface{}{ "number": 1, "title": "a title", "url": "http://a-url.com", "owner": map[string]string{ "login": "monalisa", }, }, }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() config := editConfig{ opts: editOpts{ number: 1, owner: "monalisa", title: "a new title", shortDescription: "a new description", visibility: "PUBLIC", readme: "a new readme", exporter: cmdutil.NewJSONExporter(), }, client: client, io: ios, } err := runEdit(config) assert.NoError(t, err) assert.JSONEq( t, `{"number":1,"url":"http://a-url.com","shortDescription":"","public":false,"closed":false,"title":"a title","id":"","readme":"","items":{"totalCount":0},"fields":{"totalCount":0},"owner":{"type":"","login":"monalisa"}}`, stdout.String()) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/unlink/unlink.go
pkg/cmd/project/unlink/unlink.go
package unlink import ( "fmt" "net/http" "strconv" "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/pkg/cmd/project/shared/client" "github.com/cli/cli/v2/pkg/cmd/project/shared/queries" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type unlinkOpts struct { number int32 host string owner string repo string team string projectID string projectTitle string repoID string teamID string } type unlinkConfig struct { httpClient func() (*http.Client, error) config func() (gh.Config, error) client *queries.Client opts unlinkOpts io *iostreams.IOStreams } func NewCmdUnlink(f *cmdutil.Factory, runF func(config unlinkConfig) error) *cobra.Command { opts := unlinkOpts{} linkCmd := &cobra.Command{ Short: "Unlink a project from a repository or a team", Use: "unlink [<number>]", Example: heredoc.Doc(` # Unlink monalisa's project 1 from her repository "my_repo" $ gh project unlink 1 --owner monalisa --repo my_repo # Unlink monalisa's organization's project 1 from her team "my_team" $ gh project unlink 1 --owner my_organization --team my_team # Unlink monalisa's project 1 from the repository of current directory if neither --repo nor --team is specified $ gh project unlink 1 `), RunE: func(cmd *cobra.Command, args []string) error { client, err := client.New(f) if err != nil { return err } if len(args) == 1 { num, err := strconv.ParseInt(args[0], 10, 32) if err != nil { return cmdutil.FlagErrorf("invalid number: %v", args[0]) } opts.number = int32(num) } if opts.repo == "" && opts.team == "" { repo, err := f.BaseRepo() if err != nil { return err } opts.repo = repo.RepoName() if opts.owner == "" { opts.owner = repo.RepoOwner() } } if err := cmdutil.MutuallyExclusive("specify only one of `--repo` or `--team`", opts.repo != "", opts.team != ""); err != nil { return err } if err = validateRepoOrTeamFlag(&opts); err != nil { return err } config := unlinkConfig{ httpClient: f.HttpClient, config: f.Config, client: client, opts: opts, io: f.IOStreams, } // allow testing of the command without actually running it if runF != nil { return runF(config) } return runUnlink(config) }, } cmdutil.EnableRepoOverride(linkCmd, f) linkCmd.Flags().StringVar(&opts.owner, "owner", "", "Login of the owner. Use \"@me\" for the current user.") linkCmd.Flags().StringVarP(&opts.repo, "repo", "R", "", "The repository to be unlinked from this project") linkCmd.Flags().StringVarP(&opts.team, "team", "T", "", "The team to be unlinked from this project") return linkCmd } func validateRepoOrTeamFlag(opts *unlinkOpts) error { unlinkedTarget := "" if opts.repo != "" { unlinkedTarget = opts.repo } else if opts.team != "" { unlinkedTarget = opts.team } if strings.Contains(unlinkedTarget, "/") { nameArgs := strings.Split(unlinkedTarget, "/") var host, owner, name string if len(nameArgs) == 2 { owner = nameArgs[0] name = nameArgs[1] } else if len(nameArgs) == 3 { host = nameArgs[0] owner = nameArgs[1] name = nameArgs[2] } else { if opts.repo != "" { return fmt.Errorf("expected the \"[HOST/]OWNER/REPO\" or \"REPO\" format, got \"%s\"", unlinkedTarget) } else if opts.team != "" { return fmt.Errorf("expected the \"[HOST/]OWNER/TEAM\" or \"TEAM\" format, got \"%s\"", unlinkedTarget) } } if opts.owner != "" && opts.owner != owner { return fmt.Errorf("'%s' has different owner from '%s'", unlinkedTarget, opts.owner) } opts.owner = owner opts.host = host if opts.repo != "" { opts.repo = name } else if opts.team != "" { opts.team = name } } return nil } func runUnlink(config unlinkConfig) error { canPrompt := config.io.CanPrompt() owner, err := config.client.NewOwner(canPrompt, config.opts.owner) if err != nil { return err } config.opts.owner = owner.Login project, err := config.client.NewProject(canPrompt, owner, config.opts.number, false) if err != nil { return err } config.opts.projectTitle = project.Title config.opts.projectID = project.ID if config.opts.number == 0 { config.opts.number = project.Number } httpClient, err := config.httpClient() if err != nil { return err } c := api.NewClientFromHTTP(httpClient) if config.opts.host == "" { cfg, err := config.config() if err != nil { return err } host, _ := cfg.Authentication().DefaultHost() config.opts.host = host } if config.opts.repo != "" { return unlinkRepo(c, config) } else if config.opts.team != "" { return unlinkTeam(c, config) } return nil } func unlinkRepo(c *api.Client, config unlinkConfig) error { repo, err := api.GitHubRepo(c, ghrepo.NewWithHost(config.opts.owner, config.opts.repo, config.opts.host)) if err != nil { return err } config.opts.repoID = repo.ID err = config.client.UnlinkProjectFromRepository(config.opts.projectID, config.opts.repoID) if err != nil { return err } return printResults(config, config.opts.repo) } func unlinkTeam(c *api.Client, config unlinkConfig) error { team, err := api.OrganizationTeam(c, config.opts.host, config.opts.owner, config.opts.team) if err != nil { return err } config.opts.teamID = team.ID err = config.client.UnlinkProjectFromTeam(config.opts.projectID, config.opts.teamID) if err != nil { return err } return printResults(config, config.opts.team) } func printResults(config unlinkConfig, linkedTarget string) error { if !config.io.IsStdoutTTY() { return nil } _, err := fmt.Fprintf(config.io.Out, "Unlinked '%s/%s' from project #%d '%s'\n", config.opts.owner, linkedTarget, config.opts.number, config.opts.projectTitle) return err }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/unlink/unlink_test.go
pkg/cmd/project/unlink/unlink_test.go
package unlink 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/project/shared/queries" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/require" "gopkg.in/h2non/gock.v1" ) func TestNewCmdUnlink(t *testing.T) { tests := []struct { name string cli string wants unlinkOpts wantsErr bool wantsErrMsg string wantsExporter bool }{ { name: "not-a-number", cli: "x", wantsErr: true, wantsErrMsg: "invalid number: x", }, { name: "specify-repo-and-team", cli: "--repo my-repo --team my-team", wantsErr: true, wantsErrMsg: "specify only one of `--repo` or `--team`", }, { name: "specify-nothing", cli: "", wants: unlinkOpts{ repo: "REPO", owner: "OWNER", }, }, { name: "repo", cli: "--repo my-repo", wants: unlinkOpts{ repo: "my-repo", }, }, { name: "repo-flag-contains-owner", cli: "--repo monalisa/my-repo", wants: unlinkOpts{ owner: "monalisa", repo: "my-repo", }, }, { name: "repo-flag-contains-owner-and-host", cli: "--repo github.com/monalisa/my-repo", wants: unlinkOpts{ host: "github.com", owner: "monalisa", repo: "my-repo", }, }, { name: "repo-flag-contains-wrong-format", cli: "--repo h/e/l/l/o", wantsErr: true, wantsErrMsg: "expected the \"[HOST/]OWNER/REPO\" or \"REPO\" format, got \"h/e/l/l/o\"", }, { name: "repo-flag-with-owner-different-from-owner-flag", cli: "--repo monalisa/my-repo --owner leonardo", wantsErr: true, wantsErrMsg: "'monalisa/my-repo' has different owner from 'leonardo'", }, { name: "team", cli: "--team my-team", wants: unlinkOpts{ team: "my-team", }, }, { name: "team-flag-contains-owner", cli: "--team my-org/my-team", wants: unlinkOpts{ owner: "my-org", team: "my-team", }, }, { name: "team-flag-contains-owner-and-host", cli: "--team github.com/my-org/my-team", wants: unlinkOpts{ host: "github.com", owner: "my-org", team: "my-team", }, }, { name: "team-flag-contains-wrong-format", cli: "--team h/e/l/l/o", wantsErr: true, wantsErrMsg: "expected the \"[HOST/]OWNER/TEAM\" or \"TEAM\" format, got \"h/e/l/l/o\"", }, { name: "team-flag-with-owner-different-from-owner-flag", cli: "--team my-org/my-team --owner her-org", wantsErr: true, wantsErrMsg: "'my-org/my-team' has different owner from 'her-org'", }, { name: "number", cli: "123 --repo my-repo", wants: unlinkOpts{ number: 123, repo: "my-repo", }, }, { name: "owner-with-repo-flag", cli: "--repo my-repo --owner monalisa", wants: unlinkOpts{ owner: "monalisa", repo: "my-repo", }, }, { name: "owner-without-repo-flag", cli: "--owner monalisa", wants: unlinkOpts{ owner: "monalisa", repo: "REPO", }, }, } t.Setenv("GH_TOKEN", "auth-token") for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() f := &cmdutil.Factory{ IOStreams: ios, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil }, } argv, err := shlex.Split(tt.cli) require.NoError(t, err) var gotOpts unlinkOpts cmd := NewCmdUnlink(f, func(config unlinkConfig) error { gotOpts = config.opts return nil }) cmd.SetArgs(argv) _, err = cmd.ExecuteC() if tt.wantsErr { require.Error(t, err) require.Equal(t, tt.wantsErrMsg, err.Error()) return } require.NoError(t, err) require.Equal(t, tt.wants.number, gotOpts.number) require.Equal(t, tt.wants.owner, gotOpts.owner) require.Equal(t, tt.wants.repo, gotOpts.repo) require.Equal(t, tt.wants.team, gotOpts.team) require.Equal(t, tt.wants.projectID, gotOpts.projectID) require.Equal(t, tt.wants.repoID, gotOpts.repoID) require.Equal(t, tt.wants.teamID, gotOpts.teamID) }) } } func TestRunUnlink_Repo(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get user ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]string{ "login": "monalisa", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "id": "an ID", "login": "monalisa", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"organization"}, }, }, }) // get user project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserProject.*", "variables": map[string]interface{}{ "login": "monalisa", "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "projectV2": map[string]string{ "id": "project-ID", "title": "first-project", }, }, }, }) // unlink projectV2 from repository gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "mutation UnlinkProjectV2FromRepository.*", }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "unlinkProjectV2FromRepository": map[string]interface{}{}, }, }) // get repo ID gock.New("https://api.github.com"). Post("/graphql"). BodyString(`.*query RepositoryInfo.*`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "repository": map[string]interface{}{ "id": "repo-ID", }, }, }) ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) cfg := unlinkConfig{ opts: unlinkOpts{ number: 1, repo: "my-repo", owner: "monalisa", }, client: queries.NewTestClient(), httpClient: func() (*http.Client, error) { return http.DefaultClient, nil }, config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, io: ios, } err := runUnlink(cfg) require.NoError(t, err) require.Equal( t, "Unlinked 'monalisa/my-repo' from project #1 'first-project'\n", stdout.String()) } func TestRunUnlink_Team(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get user ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]string{ "login": "monalisa-org", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "id": "an ID", "login": "monalisa-org", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"organization"}, }, }, }) // get user project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserProject.*", "variables": map[string]interface{}{ "login": "monalisa-org", "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "projectV2": map[string]string{ "id": "project-ID", "title": "first-project", }, }, }, }) // unlink projectV2 from team gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "mutation UnlinkProjectV2FromTeam.*", }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "unlinkProjectV2FromTeam": map[string]interface{}{}, }, }) // get team ID gock.New("https://api.github.com"). Post("/graphql"). BodyString(`.*query OrganizationTeam.*`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "organization": map[string]interface{}{ "team": map[string]interface{}{ "id": "team-ID", }, }, }, }) ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) cfg := unlinkConfig{ opts: unlinkOpts{ number: 1, team: "my-team", owner: "monalisa-org", }, client: queries.NewTestClient(), httpClient: func() (*http.Client, error) { return http.DefaultClient, nil }, config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, io: ios, } err := runUnlink(cfg) require.NoError(t, err) require.Equal( t, "Unlinked 'monalisa-org/my-team' from project #1 'first-project'\n", stdout.String()) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/item-add/item_add_test.go
pkg/cmd/project/item-add/item_add_test.go
package itemadd import ( "testing" "github.com/cli/cli/v2/pkg/cmd/project/shared/queries" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" "gopkg.in/h2non/gock.v1" ) func TestNewCmdaddItem(t *testing.T) { tests := []struct { name string cli string wants addItemOpts wantsErr bool wantsErrMsg string wantsExporter bool }{ { name: "missing-url", cli: "", wantsErr: true, wantsErrMsg: "required flag(s) \"url\" not set", }, { name: "not-a-number", cli: "x --url github.com/cli/cli", wantsErr: true, wantsErrMsg: "invalid number: x", }, { name: "url", cli: "--url github.com/cli/cli", wants: addItemOpts{ itemURL: "github.com/cli/cli", }, }, { name: "number", cli: "123 --url github.com/cli/cli", wants: addItemOpts{ number: 123, itemURL: "github.com/cli/cli", }, }, { name: "owner", cli: "--owner monalisa --url github.com/cli/cli", wants: addItemOpts{ owner: "monalisa", itemURL: "github.com/cli/cli", }, }, { name: "json", cli: "--format json --url github.com/cli/cli", wants: addItemOpts{ itemURL: "github.com/cli/cli", }, wantsExporter: true, }, } t.Setenv("GH_TOKEN", "auth-token") for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() f := &cmdutil.Factory{ IOStreams: ios, } argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts addItemOpts cmd := NewCmdAddItem(f, func(config addItemConfig) error { gotOpts = config.opts return nil }) cmd.SetArgs(argv) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) assert.Equal(t, tt.wantsErrMsg, err.Error()) return } assert.NoError(t, err) assert.Equal(t, tt.wants.number, gotOpts.number) assert.Equal(t, tt.wants.owner, gotOpts.owner) assert.Equal(t, tt.wants.itemURL, gotOpts.itemURL) assert.Equal(t, tt.wantsExporter, gotOpts.exporter != nil) }) } } func TestRunAddItem_User(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get user ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]interface{}{ "login": "monalisa", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "id": "an ID", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"organization"}, }, }, }) // get project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserProject.*", "variables": map[string]interface{}{ "login": "monalisa", "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "projectV2": map[string]interface{}{ "id": "an ID", }, }, }, }) // get item ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query GetIssueOrPullRequest.*", "variables": map[string]interface{}{ "url": "https://github.com/cli/go-gh/issues/1", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "resource": map[string]interface{}{ "id": "item ID", "__typename": "Issue", }, }, }) // create item gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation AddItem.*","variables":{"input":{"projectId":"an ID","contentId":"item ID"}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "addProjectV2ItemById": map[string]interface{}{ "item": map[string]interface{}{ "id": "item ID", }, }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) config := addItemConfig{ opts: addItemOpts{ owner: "monalisa", number: 1, itemURL: "https://github.com/cli/go-gh/issues/1", }, client: client, io: ios, } err := runAddItem(config) assert.NoError(t, err) assert.Equal( t, "Added item\n", stdout.String()) } func TestRunAddItem_Org(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get org ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]interface{}{ "login": "github", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "organization": map[string]interface{}{ "id": "an ID", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"user"}, }, }, }) // get project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query OrgProject.*", "variables": map[string]interface{}{ "login": "github", "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "organization": map[string]interface{}{ "projectV2": map[string]interface{}{ "id": "an ID", }, }, }, }) // get item ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query GetIssueOrPullRequest.*", "variables": map[string]interface{}{ "url": "https://github.com/cli/go-gh/issues/1", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "resource": map[string]interface{}{ "id": "item ID", "__typename": "Issue", }, }, }) // create item gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation AddItem.*","variables":{"input":{"projectId":"an ID","contentId":"item ID"}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "addProjectV2ItemById": map[string]interface{}{ "item": map[string]interface{}{ "id": "item ID", }, }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) config := addItemConfig{ opts: addItemOpts{ owner: "github", number: 1, itemURL: "https://github.com/cli/go-gh/issues/1", }, client: client, io: ios, } err := runAddItem(config) assert.NoError(t, err) assert.Equal( t, "Added item\n", stdout.String()) } func TestRunAddItem_Me(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get viewer ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query ViewerOwner.*", }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "viewer": map[string]interface{}{ "id": "an ID", }, }, }) // get project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query ViewerProject.*", "variables": map[string]interface{}{ "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "viewer": map[string]interface{}{ "projectV2": map[string]interface{}{ "id": "an ID", }, }, }, }) // get item ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query GetIssueOrPullRequest.*", "variables": map[string]interface{}{ "url": "https://github.com/cli/go-gh/pull/1", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "resource": map[string]interface{}{ "id": "item ID", "__typename": "PullRequest", }, }, }) // create item gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation AddItem.*","variables":{"input":{"projectId":"an ID","contentId":"item ID"}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "addProjectV2ItemById": map[string]interface{}{ "item": map[string]interface{}{ "id": "item ID", }, }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) config := addItemConfig{ opts: addItemOpts{ owner: "@me", number: 1, itemURL: "https://github.com/cli/go-gh/pull/1", }, client: client, io: ios, } err := runAddItem(config) assert.NoError(t, err) assert.Equal( t, "Added item\n", stdout.String()) } func TestRunAddItem_JSON(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get user ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]interface{}{ "login": "monalisa", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "id": "an ID", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"organization"}, }, }, }) // get project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserProject.*", "variables": map[string]interface{}{ "login": "monalisa", "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "projectV2": map[string]interface{}{ "id": "an ID", }, }, }, }) // get item ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query GetIssueOrPullRequest.*", "variables": map[string]interface{}{ "url": "https://github.com/cli/go-gh/issues/1", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "resource": map[string]interface{}{ "id": "item ID", "__typename": "Issue", }, }, }) // create item gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation AddItem.*","variables":{"input":{"projectId":"an ID","contentId":"item ID"}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "addProjectV2ItemById": map[string]interface{}{ "item": map[string]interface{}{ "id": "item ID", "content": map[string]interface{}{ "__typename": "Issue", "title": "a title", }, }, }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() config := addItemConfig{ opts: addItemOpts{ owner: "monalisa", number: 1, itemURL: "https://github.com/cli/go-gh/issues/1", exporter: cmdutil.NewJSONExporter(), }, client: client, io: ios, } err := runAddItem(config) assert.NoError(t, err) assert.JSONEq( t, `{"id":"item ID","title":"a title","body":"","type":"Issue"}`, stdout.String()) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/item-add/item_add.go
pkg/cmd/project/item-add/item_add.go
package itemadd import ( "fmt" "strconv" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/pkg/cmd/project/shared/client" "github.com/cli/cli/v2/pkg/cmd/project/shared/queries" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/shurcooL/githubv4" "github.com/spf13/cobra" ) type addItemOpts struct { owner string number int32 itemURL string projectID string itemID string exporter cmdutil.Exporter } type addItemConfig struct { client *queries.Client opts addItemOpts io *iostreams.IOStreams } type addProjectItemMutation struct { CreateProjectItem struct { ProjectV2Item queries.ProjectItem `graphql:"item"` } `graphql:"addProjectV2ItemById(input:$input)"` } func NewCmdAddItem(f *cmdutil.Factory, runF func(config addItemConfig) error) *cobra.Command { opts := addItemOpts{} addItemCmd := &cobra.Command{ Short: "Add a pull request or an issue to a project", Use: "item-add [<number>]", Example: heredoc.Doc(` # Add an item to monalisa's project "1" $ gh project item-add 1 --owner monalisa --url https://github.com/monalisa/myproject/issues/23 `), Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { client, err := client.New(f) if err != nil { return err } if len(args) == 1 { num, err := strconv.ParseInt(args[0], 10, 32) if err != nil { return cmdutil.FlagErrorf("invalid number: %v", args[0]) } opts.number = int32(num) } config := addItemConfig{ client: client, opts: opts, io: f.IOStreams, } // allow testing of the command without actually running it if runF != nil { return runF(config) } return runAddItem(config) }, } addItemCmd.Flags().StringVar(&opts.owner, "owner", "", "Login of the owner. Use \"@me\" for the current user.") addItemCmd.Flags().StringVar(&opts.itemURL, "url", "", "URL of the issue or pull request to add to the project") cmdutil.AddFormatFlags(addItemCmd, &opts.exporter) _ = addItemCmd.MarkFlagRequired("url") return addItemCmd } func runAddItem(config addItemConfig) error { canPrompt := config.io.CanPrompt() owner, err := config.client.NewOwner(canPrompt, config.opts.owner) if err != nil { return err } project, err := config.client.NewProject(canPrompt, owner, config.opts.number, false) if err != nil { return err } config.opts.projectID = project.ID itemID, err := config.client.IssueOrPullRequestID(config.opts.itemURL) if err != nil { return err } config.opts.itemID = itemID query, variables := addItemArgs(config) err = config.client.Mutate("AddItem", query, variables) if err != nil { return err } if config.opts.exporter != nil { return config.opts.exporter.Write(config.io, query.CreateProjectItem.ProjectV2Item) } return printResults(config, query.CreateProjectItem.ProjectV2Item) } func addItemArgs(config addItemConfig) (*addProjectItemMutation, map[string]interface{}) { return &addProjectItemMutation{}, map[string]interface{}{ "input": githubv4.AddProjectV2ItemByIdInput{ ProjectID: githubv4.ID(config.opts.projectID), ContentID: githubv4.ID(config.opts.itemID), }, } } func printResults(config addItemConfig, item queries.ProjectItem) error { if !config.io.IsStdoutTTY() { return nil } _, err := fmt.Fprintf(config.io.Out, "Added item\n") return err }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/field-delete/field_delete_test.go
pkg/cmd/project/field-delete/field_delete_test.go
package fielddelete import ( "testing" "github.com/cli/cli/v2/pkg/cmd/project/shared/queries" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" "gopkg.in/h2non/gock.v1" ) func TestNewCmdDeleteField(t *testing.T) { tests := []struct { name string cli string wants deleteFieldOpts wantsErr bool wantsErrMsg string wantsExporter bool }{ { name: "no id", cli: "", wantsErr: true, wantsErrMsg: "required flag(s) \"id\" not set", }, { name: "id", cli: "--id 123", wants: deleteFieldOpts{ fieldID: "123", }, }, { name: "json", cli: "--id 123 --format json", wants: deleteFieldOpts{ fieldID: "123", }, wantsExporter: true, }, } t.Setenv("GH_TOKEN", "auth-token") for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() f := &cmdutil.Factory{ IOStreams: ios, } argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts deleteFieldOpts cmd := NewCmdDeleteField(f, func(config deleteFieldConfig) error { gotOpts = config.opts return nil }) cmd.SetArgs(argv) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) assert.Equal(t, tt.wantsErrMsg, err.Error()) return } assert.NoError(t, err) assert.Equal(t, tt.wants.fieldID, gotOpts.fieldID) assert.Equal(t, tt.wantsExporter, gotOpts.exporter != nil) }) } } func TestRunDeleteField(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // delete Field gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation DeleteField.*","variables":{"input":{"fieldId":"an ID"}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "deleteProjectV2Field": map[string]interface{}{ "projectV2Field": map[string]interface{}{ "id": "Field ID", }, }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) config := deleteFieldConfig{ opts: deleteFieldOpts{ fieldID: "an ID", }, client: client, io: ios, } err := runDeleteField(config) assert.NoError(t, err) assert.Equal( t, "Deleted field\n", stdout.String()) } func TestRunDeleteField_JSON(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // delete Field gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation DeleteField.*","variables":{"input":{"fieldId":"an ID"}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "deleteProjectV2Field": map[string]interface{}{ "projectV2Field": map[string]interface{}{ "__typename": "ProjectV2Field", "id": "Field ID", "name": "a name", }, }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() config := deleteFieldConfig{ opts: deleteFieldOpts{ fieldID: "an ID", exporter: cmdutil.NewJSONExporter(), }, client: client, io: ios, } err := runDeleteField(config) assert.NoError(t, err) assert.JSONEq( t, `{"id":"Field ID","name":"a name","type":"ProjectV2Field"}`, stdout.String()) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/field-delete/field_delete.go
pkg/cmd/project/field-delete/field_delete.go
package fielddelete import ( "fmt" "github.com/cli/cli/v2/pkg/cmd/project/shared/client" "github.com/cli/cli/v2/pkg/cmd/project/shared/queries" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/shurcooL/githubv4" "github.com/spf13/cobra" ) type deleteFieldOpts struct { fieldID string exporter cmdutil.Exporter } type deleteFieldConfig struct { client *queries.Client opts deleteFieldOpts io *iostreams.IOStreams } type deleteProjectV2FieldMutation struct { DeleteProjectV2Field struct { Field queries.ProjectField `graphql:"projectV2Field"` } `graphql:"deleteProjectV2Field(input:$input)"` } func NewCmdDeleteField(f *cmdutil.Factory, runF func(config deleteFieldConfig) error) *cobra.Command { opts := deleteFieldOpts{} deleteFieldCmd := &cobra.Command{ Short: "Delete a field in a project", Use: "field-delete", RunE: func(cmd *cobra.Command, args []string) error { client, err := client.New(f) if err != nil { return err } config := deleteFieldConfig{ client: client, opts: opts, io: f.IOStreams, } // allow testing of the command without actually running it if runF != nil { return runF(config) } return runDeleteField(config) }, } deleteFieldCmd.Flags().StringVar(&opts.fieldID, "id", "", "ID of the field to delete") cmdutil.AddFormatFlags(deleteFieldCmd, &opts.exporter) _ = deleteFieldCmd.MarkFlagRequired("id") return deleteFieldCmd } func runDeleteField(config deleteFieldConfig) error { query, variables := deleteFieldArgs(config) err := config.client.Mutate("DeleteField", query, variables) if err != nil { return err } if config.opts.exporter != nil { return config.opts.exporter.Write(config.io, query.DeleteProjectV2Field.Field) } return printResults(config, query.DeleteProjectV2Field.Field) } func deleteFieldArgs(config deleteFieldConfig) (*deleteProjectV2FieldMutation, map[string]interface{}) { return &deleteProjectV2FieldMutation{}, map[string]interface{}{ "input": githubv4.DeleteProjectV2FieldInput{ FieldID: githubv4.ID(config.opts.fieldID), }, } } func printResults(config deleteFieldConfig, field queries.ProjectField) error { if !config.io.IsStdoutTTY() { return nil } _, err := fmt.Fprintf(config.io.Out, "Deleted field\n") return err }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/view/view.go
pkg/cmd/project/view/view.go
package view import ( "fmt" "strconv" "strings" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/pkg/cmd/project/shared/client" "github.com/cli/cli/v2/pkg/cmd/project/shared/queries" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/pkg/markdown" "github.com/spf13/cobra" ) type viewOpts struct { web bool owner string number int32 exporter cmdutil.Exporter } type viewConfig struct { client *queries.Client opts viewOpts io *iostreams.IOStreams URLOpener func(string) error } func NewCmdView(f *cmdutil.Factory, runF func(config viewConfig) error) *cobra.Command { opts := viewOpts{} viewCmd := &cobra.Command{ Short: "View a project", Use: "view [<number>]", Example: heredoc.Doc(` # View the current user's project "1" $ gh project view 1 # Open user monalisa's project "1" in the browser $ gh project view 1 --owner monalisa --web `), Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { client, err := client.New(f) if err != nil { return err } URLOpener := func(url string) error { return f.Browser.Browse(url) } if len(args) == 1 { num, err := strconv.ParseInt(args[0], 10, 32) if err != nil { return cmdutil.FlagErrorf("invalid number: %v", args[0]) } opts.number = int32(num) } config := viewConfig{ client: client, opts: opts, io: f.IOStreams, URLOpener: URLOpener, } // allow testing of the command without actually running it if runF != nil { return runF(config) } return runView(config) }, } viewCmd.Flags().StringVar(&opts.owner, "owner", "", "Login of the owner. Use \"@me\" for the current user.") viewCmd.Flags().BoolVarP(&opts.web, "web", "w", false, "Open a project in the browser") cmdutil.AddFormatFlags(viewCmd, &opts.exporter) return viewCmd } func runView(config viewConfig) error { canPrompt := config.io.CanPrompt() owner, err := config.client.NewOwner(canPrompt, config.opts.owner) if err != nil { return err } project, err := config.client.NewProject(canPrompt, owner, config.opts.number, true) if err != nil { return err } if config.opts.web { return config.URLOpener(project.URL) } if config.opts.exporter != nil { return config.opts.exporter.Write(config.io, *project) } return printResults(config, project) } func printResults(config viewConfig, project *queries.Project) error { var sb strings.Builder sb.WriteString("# Title\n") sb.WriteString(project.Title) sb.WriteString("\n") sb.WriteString("## Description\n") if project.ShortDescription == "" { sb.WriteString(" -- ") } else { sb.WriteString(project.ShortDescription) } sb.WriteString("\n") sb.WriteString("## Visibility\n") if project.Public { sb.WriteString("Public") } else { sb.WriteString("Private") } sb.WriteString("\n") sb.WriteString("## URL\n") sb.WriteString(project.URL) sb.WriteString("\n") sb.WriteString("## Item count\n") sb.WriteString(fmt.Sprintf("%d", project.Items.TotalCount)) sb.WriteString("\n") sb.WriteString("## Readme\n") if project.Readme == "" { sb.WriteString(" -- ") } else { sb.WriteString(project.Readme) } sb.WriteString("\n") sb.WriteString("## Field Name (Field Type)\n") for _, f := range project.Fields.Nodes { sb.WriteString(fmt.Sprintf("%s (%s)\n\n", f.Name(), f.Type())) } out, err := markdown.Render(sb.String(), markdown.WithTheme(config.io.TerminalTheme()), markdown.WithWrap(config.io.TerminalWidth())) if err != nil { return err } _, err = fmt.Fprint(config.io.Out, out) return err }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/view/view_test.go
pkg/cmd/project/view/view_test.go
package view import ( "bytes" "testing" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/pkg/cmd/project/shared/queries" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" "gopkg.in/h2non/gock.v1" ) func TestNewCmdview(t *testing.T) { tests := []struct { name string cli string wants viewOpts wantsErr bool wantsErrMsg string wantsExporter bool }{ { name: "not-a-number", cli: "x", wantsErr: true, wantsErrMsg: "invalid number: x", }, { name: "number", cli: "123", wants: viewOpts{ number: 123, }, }, { name: "owner", cli: "--owner monalisa", wants: viewOpts{ owner: "monalisa", }, }, { name: "web", cli: "--web", wants: viewOpts{ web: true, }, }, { name: "json", cli: "--format json", wantsExporter: true, }, } t.Setenv("GH_TOKEN", "auth-token") for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() f := &cmdutil.Factory{ IOStreams: ios, } argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts viewOpts cmd := NewCmdView(f, func(config viewConfig) error { gotOpts = config.opts return nil }) cmd.SetArgs(argv) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) assert.Equal(t, tt.wantsErrMsg, err.Error()) return } assert.NoError(t, err) assert.Equal(t, tt.wants.number, gotOpts.number) assert.Equal(t, tt.wants.owner, gotOpts.owner) assert.Equal(t, tt.wantsExporter, gotOpts.exporter != nil) assert.Equal(t, tt.wants.web, gotOpts.web) }) } } func TestRunView_User(t *testing.T) { defer gock.Off() // get user ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]interface{}{ "login": "monalisa", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "id": "an ID", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"organization"}, }, }, }) gock.New("https://api.github.com"). Post("/graphql"). Reply(200). JSON(` {"data": {"user": { "login":"monalisa", "projectV2": { "number": 1, "items": { "totalCount": 10 }, "readme": null, "fields": { "nodes": [ { "name": "Title" } ] } } } } } `) client := queries.NewTestClient() ios, _, _, _ := iostreams.Test() config := viewConfig{ opts: viewOpts{ owner: "monalisa", number: 1, }, io: ios, client: client, } err := runView(config) assert.NoError(t, err) } func TestRunView_Viewer(t *testing.T) { defer gock.Off() // get viewer ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query ViewerOwner.*", }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "viewer": map[string]interface{}{ "id": "an ID", }, }, }) gock.New("https://api.github.com"). Post("/graphql"). Reply(200). JSON(` {"data": {"viewer": { "login":"monalisa", "projectV2": { "number": 1, "items": { "totalCount": 10 }, "url":"https://github.com/orgs/github/projects/8", "readme": null, "fields": { "nodes": [ { "name": "Title" } ] } } } } } `) client := queries.NewTestClient() ios, _, _, _ := iostreams.Test() config := viewConfig{ opts: viewOpts{ owner: "@me", number: 1, }, io: ios, client: client, } err := runView(config) assert.NoError(t, err) } func TestRunView_Org(t *testing.T) { defer gock.Off() // get org ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]interface{}{ "login": "github", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "organization": map[string]interface{}{ "id": "an ID", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"user"}, }, }, }) gock.New("https://api.github.com"). Post("/graphql"). Reply(200). JSON(` {"data": {"organization": { "login":"monalisa", "projectV2": { "number": 1, "items": { "totalCount": 10 }, "url":"https://github.com/orgs/github/projects/8", "readme": null, "fields": { "nodes": [ { "name": "Title" } ] } } } } } `) client := queries.NewTestClient() ios, _, _, _ := iostreams.Test() config := viewConfig{ opts: viewOpts{ owner: "github", number: 1, }, io: ios, client: client, } err := runView(config) assert.NoError(t, err) } func TestRunViewWeb_User(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get user ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]interface{}{ "login": "monalisa", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "id": "an ID", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"organization"}, }, }, }) gock.New("https://api.github.com"). Post("/graphql"). Reply(200). JSON(` {"data": {"user": { "login":"monalisa", "projectV2": { "number": 8, "items": { "totalCount": 10 }, "url":"https://github.com/users/monalisa/projects/8", "readme": null, "fields": { "nodes": [ { "name": "Title" } ] } } } } } `) client := queries.NewTestClient() buf := bytes.Buffer{} ios, _, _, _ := iostreams.Test() config := viewConfig{ opts: viewOpts{ owner: "monalisa", web: true, number: 8, }, URLOpener: func(url string) error { buf.WriteString(url) return nil }, client: client, io: ios, } err := runView(config) assert.NoError(t, err) assert.Equal(t, "https://github.com/users/monalisa/projects/8", buf.String()) } func TestRunViewWeb_Org(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get org ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]interface{}{ "login": "github", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "organization": map[string]interface{}{ "id": "an ID", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"user"}, }, }, }) gock.New("https://api.github.com"). Post("/graphql"). Reply(200). JSON(` {"data": {"organization": { "login":"github", "projectV2": { "number": 8, "items": { "totalCount": 10 }, "url": "https://github.com/orgs/github/projects/8", "readme": null, "fields": { "nodes": [ { "name": "Title" } ] } } } } } `) client := queries.NewTestClient() buf := bytes.Buffer{} ios, _, _, _ := iostreams.Test() config := viewConfig{ opts: viewOpts{ owner: "github", web: true, number: 8, }, URLOpener: func(url string) error { buf.WriteString(url) return nil }, client: client, io: ios, } err := runView(config) assert.NoError(t, err) assert.Equal(t, "https://github.com/orgs/github/projects/8", buf.String()) } func TestRunViewWeb_Me(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get viewer ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query Viewer.*", }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "viewer": map[string]interface{}{ "id": "an ID", "login": "theviewer", }, }, }) gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query ViewerProject.*", "variables": map[string]interface{}{"afterFields": nil, "afterItems": nil, "firstFields": 100, "firstItems": 0, "number": 8}, }). Reply(200). JSON(` {"data": {"viewer": { "login":"github", "projectV2": { "number": 8, "items": { "totalCount": 10 }, "readme": null, "url": "https://github.com/users/theviewer/projects/8", "fields": { "nodes": [ { "name": "Title" } ] } } } } } `) client := queries.NewTestClient() buf := bytes.Buffer{} ios, _, _, _ := iostreams.Test() config := viewConfig{ opts: viewOpts{ owner: "@me", web: true, number: 8, }, URLOpener: func(url string) error { buf.WriteString(url) return nil }, client: client, io: ios, } err := runView(config) assert.NoError(t, err) assert.Equal(t, "https://github.com/users/theviewer/projects/8", buf.String()) } func TestRunViewWeb_TTY(t *testing.T) { tests := []struct { name string setup func(*viewOpts, *testing.T) func() promptStubs func(*prompter.PrompterMock) gqlStubs func(*testing.T) expectedBrowse string tty bool }{ { name: "Org project --web with tty", tty: true, setup: func(vo *viewOpts, t *testing.T) func() { return func() { vo.web = true } }, gqlStubs: func(t *testing.T) { gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query ViewerLoginAndOrgs.*", "variables": map[string]interface{}{ "after": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "viewer": map[string]interface{}{ "id": "monalisa-ID", "login": "monalisa", "organizations": map[string]interface{}{ "nodes": []interface{}{ map[string]interface{}{ "login": "github", "viewerCanCreateProjects": true, }, }, }, }, }, }) gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query OrgProjects.*", "variables": map[string]interface{}{ "after": nil, "afterFields": nil, "afterItems": nil, "first": 30, "firstFields": 100, "firstItems": 0, "login": "github", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "organization": map[string]interface{}{ "login": "github", "projectsV2": map[string]interface{}{ "nodes": []interface{}{ map[string]interface{}{ "id": "a-project-ID", "title": "Get it done!", "url": "https://github.com/orgs/github/projects/1", "number": 1, }, }, }, }, }, }) }, promptStubs: func(pm *prompter.PrompterMock) { pm.SelectFunc = func(prompt, _ string, opts []string) (int, error) { switch prompt { case "Which owner would you like to use?": return prompter.IndexFor(opts, "github") case "Which project would you like to use?": return prompter.IndexFor(opts, "Get it done! (#1)") default: return -1, prompter.NoSuchPromptErr(prompt) } } }, expectedBrowse: "https://github.com/orgs/github/projects/1", }, { name: "User project --web with tty", tty: true, setup: func(vo *viewOpts, t *testing.T) func() { return func() { vo.web = true } }, gqlStubs: func(t *testing.T) { gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query ViewerLoginAndOrgs.*", "variables": map[string]interface{}{ "after": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "viewer": map[string]interface{}{ "id": "monalisa-ID", "login": "monalisa", "organizations": map[string]interface{}{ "nodes": []interface{}{ map[string]interface{}{ "login": "github", "viewerCanCreateProjects": true, }, }, }, }, }, }) gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query ViewerProjects.*", "variables": map[string]interface{}{ "after": nil, "afterFields": nil, "afterItems": nil, "first": 30, "firstFields": 100, "firstItems": 0, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "viewer": map[string]interface{}{ "login": "monalisa", "projectsV2": map[string]interface{}{ "totalCount": 1, "nodes": []interface{}{ map[string]interface{}{ "id": "a-project-ID", "number": 1, "title": "@monalia's first project", "url": "https://github.com/users/monalisa/projects/1", }, }, }, }, }, }) }, promptStubs: func(pm *prompter.PrompterMock) { pm.SelectFunc = func(prompt, _ string, opts []string) (int, error) { switch prompt { case "Which owner would you like to use?": return prompter.IndexFor(opts, "monalisa") case "Which project would you like to use?": return prompter.IndexFor(opts, "@monalia's first project (#1)") default: return -1, prompter.NoSuchPromptErr(prompt) } } }, expectedBrowse: "https://github.com/users/monalisa/projects/1", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) if tt.gqlStubs != nil { tt.gqlStubs(t) } pm := &prompter.PrompterMock{} if tt.promptStubs != nil { tt.promptStubs(pm) } opts := viewOpts{} if tt.setup != nil { tt.setup(&opts, t)() } ios, _, _, _ := iostreams.Test() ios.SetStdoutTTY(tt.tty) ios.SetStdinTTY(tt.tty) ios.SetStderrTTY(tt.tty) buf := bytes.Buffer{} client := queries.NewTestClient(queries.WithPrompter(pm)) config := viewConfig{ opts: opts, URLOpener: func(url string) error { _, err := buf.WriteString(url) return err }, client: client, io: ios, } err := runView(config) assert.NoError(t, err) assert.Equal(t, tt.expectedBrowse, buf.String()) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/mark-template/mark_template.go
pkg/cmd/project/mark-template/mark_template.go
package marktemplate import ( "fmt" "strconv" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/pkg/cmd/project/shared/client" "github.com/cli/cli/v2/pkg/cmd/project/shared/queries" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/shurcooL/githubv4" "github.com/spf13/cobra" ) type markTemplateOpts struct { owner string undo bool number int32 projectID string exporter cmdutil.Exporter } type markTemplateConfig struct { client *queries.Client opts markTemplateOpts io *iostreams.IOStreams } type markProjectTemplateMutation struct { TemplateProject struct { Project queries.Project `graphql:"projectV2"` } `graphql:"markProjectV2AsTemplate(input:$input)"` } type unmarkProjectTemplateMutation struct { TemplateProject struct { Project queries.Project `graphql:"projectV2"` } `graphql:"unmarkProjectV2AsTemplate(input:$input)"` } func NewCmdMarkTemplate(f *cmdutil.Factory, runF func(config markTemplateConfig) error) *cobra.Command { opts := markTemplateOpts{} markTemplateCmd := &cobra.Command{ Short: "Mark a project as a template", Use: "mark-template [<number>]", Example: heredoc.Doc(` # Mark the github org's project "1" as a template $ gh project mark-template 1 --owner "github" # Unmark the github org's project "1" as a template $ gh project mark-template 1 --owner "github" --undo `), Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { client, err := client.New(f) if err != nil { return err } if len(args) == 1 { num, err := strconv.ParseInt(args[0], 10, 32) if err != nil { return cmdutil.FlagErrorf("invalid number: %v", args[0]) } opts.number = int32(num) } config := markTemplateConfig{ client: client, opts: opts, io: f.IOStreams, } // allow testing of the command without actually running it if runF != nil { return runF(config) } return runMarkTemplate(config) }, } markTemplateCmd.Flags().StringVar(&opts.owner, "owner", "", "Login of the org owner.") markTemplateCmd.Flags().BoolVar(&opts.undo, "undo", false, "Unmark the project as a template.") cmdutil.AddFormatFlags(markTemplateCmd, &opts.exporter) return markTemplateCmd } func runMarkTemplate(config markTemplateConfig) error { canPrompt := config.io.CanPrompt() owner, err := config.client.NewOwner(canPrompt, config.opts.owner) if err != nil { return err } project, err := config.client.NewProject(canPrompt, owner, config.opts.number, false) if err != nil { return err } config.opts.projectID = project.ID if config.opts.undo { query, variables := unmarkTemplateArgs(config) err = config.client.Mutate("UnmarkProjectTemplate", query, variables) if err != nil { return err } if config.opts.exporter != nil { return config.opts.exporter.Write(config.io, *project) } return printResults(config, query.TemplateProject.Project) } query, variables := markTemplateArgs(config) err = config.client.Mutate("MarkProjectTemplate", query, variables) if err != nil { return err } if config.opts.exporter != nil { return config.opts.exporter.Write(config.io, query.TemplateProject.Project) } return printResults(config, query.TemplateProject.Project) } func markTemplateArgs(config markTemplateConfig) (*markProjectTemplateMutation, map[string]interface{}) { return &markProjectTemplateMutation{}, map[string]interface{}{ "input": githubv4.MarkProjectV2AsTemplateInput{ ProjectID: githubv4.ID(config.opts.projectID), }, "firstItems": githubv4.Int(0), "afterItems": (*githubv4.String)(nil), "firstFields": githubv4.Int(0), "afterFields": (*githubv4.String)(nil), } } func unmarkTemplateArgs(config markTemplateConfig) (*unmarkProjectTemplateMutation, map[string]interface{}) { return &unmarkProjectTemplateMutation{}, map[string]interface{}{ "input": githubv4.UnmarkProjectV2AsTemplateInput{ ProjectID: githubv4.ID(config.opts.projectID), }, "firstItems": githubv4.Int(0), "afterItems": (*githubv4.String)(nil), "firstFields": githubv4.Int(0), "afterFields": (*githubv4.String)(nil), } } func printResults(config markTemplateConfig, project queries.Project) error { if !config.io.IsStdoutTTY() { return nil } if config.opts.undo { _, err := fmt.Fprintf(config.io.Out, "Unmarked project %d as a template.\n", project.Number) return err } _, err := fmt.Fprintf(config.io.Out, "Marked project %d as a template.\n", project.Number) return err }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/mark-template/mark_template_test.go
pkg/cmd/project/mark-template/mark_template_test.go
package marktemplate import ( "testing" "github.com/cli/cli/v2/pkg/cmd/project/shared/queries" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" "gopkg.in/h2non/gock.v1" ) func TestNewCmdMarkTemplate(t *testing.T) { tests := []struct { name string cli string wants markTemplateOpts wantsErr bool wantsErrMsg string wantsExporter bool }{ { name: "not-a-number", cli: "x", wantsErr: true, wantsErrMsg: "invalid number: x", }, { name: "number", cli: "123", wants: markTemplateOpts{ number: 123, }, }, { name: "owner", cli: "--owner monalisa", wants: markTemplateOpts{ owner: "monalisa", }, }, { name: "undo", cli: "--undo", wants: markTemplateOpts{ undo: true, }, }, { name: "json", cli: "--format json", wantsExporter: true, }, } t.Setenv("GH_TOKEN", "auth-token") for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() f := &cmdutil.Factory{ IOStreams: ios, } argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts markTemplateOpts cmd := NewCmdMarkTemplate(f, func(config markTemplateConfig) error { gotOpts = config.opts return nil }) cmd.SetArgs(argv) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) assert.Equal(t, tt.wantsErrMsg, err.Error()) return } assert.NoError(t, err) assert.Equal(t, tt.wants.number, gotOpts.number) assert.Equal(t, tt.wants.owner, gotOpts.owner) assert.Equal(t, tt.wantsExporter, gotOpts.exporter != nil) }) } } func TestRunMarkTemplate_Org(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get org ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]interface{}{ "login": "github", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "organization": map[string]interface{}{ "id": "an ID", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"user"}, }, }, }) // get project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query OrgProject.*", "variables": map[string]interface{}{ "login": "github", "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "organization": map[string]interface{}{ "projectV2": map[string]interface{}{ "id": "an ID", }, }, }, }) // template project gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation MarkProjectTemplate.*","variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"projectId":"an ID"}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "markProjectV2AsTemplate": map[string]interface{}{ "projectV2": map[string]interface{}{ "id": "project ID", "number": 1, }, }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) config := markTemplateConfig{ opts: markTemplateOpts{ owner: "github", number: 1, }, client: client, io: ios, } err := runMarkTemplate(config) assert.NoError(t, err) assert.Equal( t, "Marked project 1 as a template.\n", stdout.String()) } func TestRunUnmarkTemplate_Org(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get org ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]interface{}{ "login": "github", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "organization": map[string]interface{}{ "id": "an ID", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"user"}, }, }, }) // get project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query OrgProject.*", "variables": map[string]interface{}{ "login": "github", "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "organization": map[string]interface{}{ "projectV2": map[string]interface{}{ "id": "an ID", }, }, }, }) // template project gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation UnmarkProjectTemplate.*","variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"projectId":"an ID"}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "unmarkProjectV2AsTemplate": map[string]interface{}{ "projectV2": map[string]interface{}{ "id": "project ID", "number": 1, }, }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) config := markTemplateConfig{ opts: markTemplateOpts{ owner: "github", number: 1, undo: true, }, client: client, io: ios, } err := runMarkTemplate(config) assert.NoError(t, err) assert.Equal( t, "Unmarked project 1 as a template.\n", stdout.String()) } func TestRunMarkTemplate_JSON(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get org ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]interface{}{ "login": "github", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "organization": map[string]interface{}{ "id": "an ID", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"user"}, }, }, }) // get project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query OrgProject.*", "variables": map[string]interface{}{ "login": "github", "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "organization": map[string]interface{}{ "projectV2": map[string]interface{}{ "id": "an ID", }, }, }, }) // template project gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation MarkProjectTemplate.*","variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"projectId":"an ID"}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "markProjectV2AsTemplate": map[string]interface{}{ "projectV2": map[string]interface{}{ "id": "project ID", "number": 1, "owner": map[string]interface{}{ "__typename": "Organization", "login": "github", }, }, }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() config := markTemplateConfig{ opts: markTemplateOpts{ owner: "github", number: 1, exporter: cmdutil.NewJSONExporter(), }, client: client, io: ios, } err := runMarkTemplate(config) assert.NoError(t, err) assert.JSONEq( t, `{"number":1,"url":"","shortDescription":"","public":false,"closed":false,"title":"","id":"project ID","readme":"","items":{"totalCount":0},"fields":{"totalCount":0},"owner":{"type":"Organization","login":"github"}}`, stdout.String()) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/field-create/field_create.go
pkg/cmd/project/field-create/field_create.go
package fieldcreate import ( "fmt" "strconv" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/pkg/cmd/project/shared/client" "github.com/cli/cli/v2/pkg/cmd/project/shared/queries" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/shurcooL/githubv4" "github.com/spf13/cobra" ) type createFieldOpts struct { name string dataType string owner string singleSelectOptions []string number int32 projectID string exporter cmdutil.Exporter } type createFieldConfig struct { client *queries.Client opts createFieldOpts io *iostreams.IOStreams } type createProjectV2FieldMutation struct { CreateProjectV2Field struct { Field queries.ProjectField `graphql:"projectV2Field"` } `graphql:"createProjectV2Field(input:$input)"` } func NewCmdCreateField(f *cmdutil.Factory, runF func(config createFieldConfig) error) *cobra.Command { opts := createFieldOpts{} createFieldCmd := &cobra.Command{ Short: "Create a field in a project", Use: "field-create [<number>]", Example: heredoc.Doc(` # Create a field in the current user's project "1" $ gh project field-create 1 --owner "@me" --name "new field" --data-type "text" # Create a field with three options to select from for owner monalisa $ gh project field-create 1 --owner monalisa --name "new field" --data-type "SINGLE_SELECT" --single-select-options "one,two,three" `), Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { client, err := client.New(f) if err != nil { return err } if len(args) == 1 { num, err := strconv.ParseInt(args[0], 10, 32) if err != nil { return cmdutil.FlagErrorf("invalid number: %v", args[0]) } opts.number = int32(num) } config := createFieldConfig{ client: client, opts: opts, io: f.IOStreams, } if config.opts.dataType == "SINGLE_SELECT" && len(config.opts.singleSelectOptions) == 0 { return fmt.Errorf("passing `--single-select-options` is required for SINGLE_SELECT data type") } // allow testing of the command without actually running it if runF != nil { return runF(config) } return runCreateField(config) }, } createFieldCmd.Flags().StringVar(&opts.owner, "owner", "", "Login of the owner. Use \"@me\" for the current user.") createFieldCmd.Flags().StringVar(&opts.name, "name", "", "Name of the new field") cmdutil.StringEnumFlag(createFieldCmd, &opts.dataType, "data-type", "", "", []string{"TEXT", "SINGLE_SELECT", "DATE", "NUMBER"}, "DataType of the new field.") createFieldCmd.Flags().StringSliceVar(&opts.singleSelectOptions, "single-select-options", []string{}, "Options for SINGLE_SELECT data type") cmdutil.AddFormatFlags(createFieldCmd, &opts.exporter) _ = createFieldCmd.MarkFlagRequired("name") _ = createFieldCmd.MarkFlagRequired("data-type") return createFieldCmd } func runCreateField(config createFieldConfig) error { canPrompt := config.io.CanPrompt() owner, err := config.client.NewOwner(canPrompt, config.opts.owner) if err != nil { return err } project, err := config.client.NewProject(canPrompt, owner, config.opts.number, false) if err != nil { return err } config.opts.projectID = project.ID query, variables := createFieldArgs(config) err = config.client.Mutate("CreateField", query, variables) if err != nil { return err } if config.opts.exporter != nil { return config.opts.exporter.Write(config.io, query.CreateProjectV2Field.Field) } return printResults(config, query.CreateProjectV2Field.Field) } func createFieldArgs(config createFieldConfig) (*createProjectV2FieldMutation, map[string]interface{}) { input := githubv4.CreateProjectV2FieldInput{ ProjectID: githubv4.ID(config.opts.projectID), DataType: githubv4.ProjectV2CustomFieldType(config.opts.dataType), Name: githubv4.String(config.opts.name), } if len(config.opts.singleSelectOptions) != 0 { opts := make([]githubv4.ProjectV2SingleSelectFieldOptionInput, 0) for _, opt := range config.opts.singleSelectOptions { opts = append(opts, githubv4.ProjectV2SingleSelectFieldOptionInput{ Name: githubv4.String(opt), Color: githubv4.ProjectV2SingleSelectFieldOptionColor("GRAY"), }) } input.SingleSelectOptions = &opts } return &createProjectV2FieldMutation{}, map[string]interface{}{ "input": input, } } func printResults(config createFieldConfig, field queries.ProjectField) error { if !config.io.IsStdoutTTY() { return nil } _, err := fmt.Fprintf(config.io.Out, "Created field\n") return err }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/field-create/field_create_test.go
pkg/cmd/project/field-create/field_create_test.go
package fieldcreate import ( "testing" "github.com/cli/cli/v2/pkg/cmd/project/shared/queries" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" "gopkg.in/h2non/gock.v1" ) func TestNewCmdCreateField(t *testing.T) { tests := []struct { name string cli string wants createFieldOpts wantsErr bool wantsErrMsg string wantsExporter bool }{ { name: "missing-name-and-data-type", cli: "", wantsErr: true, wantsErrMsg: "required flag(s) \"data-type\", \"name\" not set", }, { name: "not-a-number", cli: "x --name n --data-type TEXT", wantsErr: true, wantsErrMsg: "invalid number: x", }, { name: "single-select-no-options", cli: "123 --name n --data-type SINGLE_SELECT", wantsErr: true, wantsErrMsg: "passing `--single-select-options` is required for SINGLE_SELECT data type", }, { name: "number", cli: "123 --name n --data-type TEXT", wants: createFieldOpts{ number: 123, name: "n", dataType: "TEXT", singleSelectOptions: []string{}, }, }, { name: "owner", cli: "--owner monalisa --name n --data-type TEXT", wants: createFieldOpts{ owner: "monalisa", name: "n", dataType: "TEXT", singleSelectOptions: []string{}, }, }, { name: "single-select-options", cli: "--name n --data-type TEXT --single-select-options a,b", wants: createFieldOpts{ singleSelectOptions: []string{"a", "b"}, name: "n", dataType: "TEXT", }, }, { name: "json", cli: "--format json --name n --data-type TEXT ", wants: createFieldOpts{ name: "n", dataType: "TEXT", singleSelectOptions: []string{}, }, wantsExporter: true, }, } t.Setenv("GH_TOKEN", "auth-token") for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() f := &cmdutil.Factory{ IOStreams: ios, } argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts createFieldOpts cmd := NewCmdCreateField(f, func(config createFieldConfig) error { gotOpts = config.opts return nil }) cmd.SetArgs(argv) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) assert.Equal(t, tt.wantsErrMsg, err.Error()) return } assert.NoError(t, err) assert.Equal(t, tt.wants.number, gotOpts.number) assert.Equal(t, tt.wants.owner, gotOpts.owner) assert.Equal(t, tt.wants.name, gotOpts.name) assert.Equal(t, tt.wants.dataType, gotOpts.dataType) assert.Equal(t, tt.wants.singleSelectOptions, gotOpts.singleSelectOptions) assert.Equal(t, tt.wantsExporter, gotOpts.exporter != nil) }) } } func TestRunCreateField_User(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get user ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]interface{}{ "login": "monalisa", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "id": "an ID", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"organization"}, }, }, }) // get project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserProject.*", "variables": map[string]interface{}{ "login": "monalisa", "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "projectV2": map[string]interface{}{ "id": "an ID", }, }, }, }) // create Field gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation CreateField.*","variables":{"input":{"projectId":"an ID","dataType":"TEXT","name":"a name"}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "createProjectV2Field": map[string]interface{}{ "projectV2Field": map[string]interface{}{ "id": "Field ID", }, }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) config := createFieldConfig{ opts: createFieldOpts{ name: "a name", owner: "monalisa", number: 1, dataType: "TEXT", }, client: client, io: ios, } err := runCreateField(config) assert.NoError(t, err) assert.Equal( t, "Created field\n", stdout.String()) } func TestRunCreateField_Org(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get org ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]interface{}{ "login": "github", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "organization": map[string]interface{}{ "id": "an ID", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"user"}, }, }, }) // get project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query OrgProject.*", "variables": map[string]interface{}{ "login": "github", "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "organization": map[string]interface{}{ "projectV2": map[string]interface{}{ "id": "an ID", }, }, }, }) // create Field gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation CreateField.*","variables":{"input":{"projectId":"an ID","dataType":"TEXT","name":"a name"}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "createProjectV2Field": map[string]interface{}{ "projectV2Field": map[string]interface{}{ "id": "Field ID", }, }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) config := createFieldConfig{ opts: createFieldOpts{ name: "a name", owner: "github", number: 1, dataType: "TEXT", }, client: client, io: ios, } err := runCreateField(config) assert.NoError(t, err) assert.Equal( t, "Created field\n", stdout.String()) } func TestRunCreateField_Me(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get viewer ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query ViewerOwner.*", }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "viewer": map[string]interface{}{ "id": "an ID", }, }, }) // get project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query ViewerProject.*", "variables": map[string]interface{}{ "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "viewer": map[string]interface{}{ "projectV2": map[string]interface{}{ "id": "an ID", }, }, }, }) // create Field gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation CreateField.*","variables":{"input":{"projectId":"an ID","dataType":"TEXT","name":"a name"}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "createProjectV2Field": map[string]interface{}{ "projectV2Field": map[string]interface{}{ "id": "Field ID", }, }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) config := createFieldConfig{ opts: createFieldOpts{ owner: "@me", number: 1, name: "a name", dataType: "TEXT", }, client: client, io: ios, } err := runCreateField(config) assert.NoError(t, err) assert.Equal( t, "Created field\n", stdout.String()) } func TestRunCreateField_TEXT(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get viewer ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query ViewerOwner.*", }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "viewer": map[string]interface{}{ "id": "an ID", }, }, }) // get project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query ViewerProject.*", "variables": map[string]interface{}{ "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "viewer": map[string]interface{}{ "projectV2": map[string]interface{}{ "id": "an ID", }, }, }, }) // create Field gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation CreateField.*","variables":{"input":{"projectId":"an ID","dataType":"TEXT","name":"a name"}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "createProjectV2Field": map[string]interface{}{ "projectV2Field": map[string]interface{}{ "id": "Field ID", }, }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) config := createFieldConfig{ opts: createFieldOpts{ owner: "@me", number: 1, name: "a name", dataType: "TEXT", }, client: client, io: ios, } err := runCreateField(config) assert.NoError(t, err) assert.Equal( t, "Created field\n", stdout.String()) } func TestRunCreateField_DATE(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get viewer ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query ViewerOwner.*", }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "viewer": map[string]interface{}{ "id": "an ID", }, }, }) // get project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query ViewerProject.*", "variables": map[string]interface{}{ "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "viewer": map[string]interface{}{ "projectV2": map[string]interface{}{ "id": "an ID", }, }, }, }) // create Field gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation CreateField.*","variables":{"input":{"projectId":"an ID","dataType":"DATE","name":"a name"}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "createProjectV2Field": map[string]interface{}{ "projectV2Field": map[string]interface{}{ "id": "Field ID", }, }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) config := createFieldConfig{ opts: createFieldOpts{ owner: "@me", number: 1, name: "a name", dataType: "DATE", }, client: client, io: ios, } err := runCreateField(config) assert.NoError(t, err) assert.Equal( t, "Created field\n", stdout.String()) } func TestRunCreateField_NUMBER(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get viewer ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query ViewerOwner.*", }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "viewer": map[string]interface{}{ "id": "an ID", }, }, }) // get project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query ViewerProject.*", "variables": map[string]interface{}{ "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "viewer": map[string]interface{}{ "projectV2": map[string]interface{}{ "id": "an ID", }, }, }, }) // create Field gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation CreateField.*","variables":{"input":{"projectId":"an ID","dataType":"NUMBER","name":"a name"}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "createProjectV2Field": map[string]interface{}{ "projectV2Field": map[string]interface{}{ "id": "Field ID", }, }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) config := createFieldConfig{ opts: createFieldOpts{ owner: "@me", number: 1, name: "a name", dataType: "NUMBER", }, client: client, io: ios, } err := runCreateField(config) assert.NoError(t, err) assert.Equal( t, "Created field\n", stdout.String()) } func TestRunCreateField_JSON(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get user ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]interface{}{ "login": "monalisa", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "id": "an ID", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"organization"}, }, }, }) // get project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserProject.*", "variables": map[string]interface{}{ "login": "monalisa", "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "projectV2": map[string]interface{}{ "id": "an ID", }, }, }, }) // create Field gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation CreateField.*","variables":{"input":{"projectId":"an ID","dataType":"TEXT","name":"a name"}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "createProjectV2Field": map[string]interface{}{ "projectV2Field": map[string]interface{}{ "__typename": "ProjectV2Field", "id": "Field ID", "name": "a name", }, }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() config := createFieldConfig{ opts: createFieldOpts{ name: "a name", owner: "monalisa", number: 1, dataType: "TEXT", exporter: cmdutil.NewJSONExporter(), }, client: client, io: ios, } err := runCreateField(config) assert.NoError(t, err) assert.JSONEq( t, `{"id":"Field ID","name":"a name","type":"ProjectV2Field"}`, stdout.String()) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/create/create.go
pkg/cmd/project/create/create.go
package create import ( "fmt" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/pkg/cmd/project/shared/client" "github.com/cli/cli/v2/pkg/cmd/project/shared/queries" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/shurcooL/githubv4" "github.com/spf13/cobra" ) type createOpts struct { title string owner string ownerID string exporter cmdutil.Exporter } type createConfig struct { client *queries.Client opts createOpts io *iostreams.IOStreams } type createProjectMutation struct { CreateProjectV2 struct { ProjectV2 queries.Project `graphql:"projectV2"` } `graphql:"createProjectV2(input:$input)"` } func NewCmdCreate(f *cmdutil.Factory, runF func(config createConfig) error) *cobra.Command { opts := createOpts{} createCmd := &cobra.Command{ Short: "Create a project", Use: "create", Example: heredoc.Doc(` # Create a new project owned by login monalisa $ gh project create --owner monalisa --title "a new project" `), RunE: func(cmd *cobra.Command, args []string) error { client, err := client.New(f) if err != nil { return err } config := createConfig{ client: client, opts: opts, io: f.IOStreams, } // allow testing of the command without actually running it if runF != nil { return runF(config) } return runCreate(config) }, } createCmd.Flags().StringVar(&opts.title, "title", "", "Title for the project") createCmd.Flags().StringVar(&opts.owner, "owner", "", "Login of the owner. Use \"@me\" for the current user.") cmdutil.AddFormatFlags(createCmd, &opts.exporter) _ = createCmd.MarkFlagRequired("title") return createCmd } func runCreate(config createConfig) error { canPrompt := config.io.CanPrompt() owner, err := config.client.NewOwner(canPrompt, config.opts.owner) if err != nil { return err } config.opts.ownerID = owner.ID query, variables := createArgs(config) err = config.client.Mutate("CreateProjectV2", query, variables) if err != nil { return err } if config.opts.exporter != nil { return config.opts.exporter.Write(config.io, query.CreateProjectV2.ProjectV2) } return printResults(config, query.CreateProjectV2.ProjectV2) } func createArgs(config createConfig) (*createProjectMutation, map[string]interface{}) { return &createProjectMutation{}, map[string]interface{}{ "input": githubv4.CreateProjectV2Input{ OwnerID: githubv4.ID(config.opts.ownerID), Title: githubv4.String(config.opts.title), }, "firstItems": githubv4.Int(0), "afterItems": (*githubv4.String)(nil), "firstFields": githubv4.Int(0), "afterFields": (*githubv4.String)(nil), } } func printResults(config createConfig, project queries.Project) error { if !config.io.IsStdoutTTY() { return nil } _, err := fmt.Fprintf(config.io.Out, "%s\n", project.URL) return err }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/create/create_test.go
pkg/cmd/project/create/create_test.go
package create import ( "testing" "github.com/cli/cli/v2/pkg/cmd/project/shared/queries" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" "gopkg.in/h2non/gock.v1" ) func TestNewCmdCreate(t *testing.T) { tests := []struct { name string cli string wants createOpts wantsErr bool wantsErrMsg string wantsExporter bool }{ { name: "title", cli: "--title t", wants: createOpts{ title: "t", }, }, { name: "owner", cli: "--title t --owner monalisa", wants: createOpts{ owner: "monalisa", title: "t", }, }, { name: "json", cli: "--title t --format json", wants: createOpts{ title: "t", }, wantsExporter: true, }, } t.Setenv("GH_TOKEN", "auth-token") for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() f := &cmdutil.Factory{ IOStreams: ios, } argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts createOpts cmd := NewCmdCreate(f, func(config createConfig) error { gotOpts = config.opts return nil }) cmd.SetArgs(argv) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) assert.Equal(t, tt.wantsErrMsg, err.Error()) return } assert.NoError(t, err) assert.Equal(t, tt.wants.title, gotOpts.title) assert.Equal(t, tt.wants.owner, gotOpts.owner) assert.Equal(t, tt.wantsExporter, gotOpts.exporter != nil) }) } } func TestRunCreate_User(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get user ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]string{ "login": "monalisa", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "id": "an ID", "login": "monalisa", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"organization"}, }, }, }) // create project gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation CreateProjectV2.*"variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"ownerId":"an ID","title":"a title"}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "createProjectV2": map[string]interface{}{ "projectV2": map[string]interface{}{ "title": "a title", "url": "http://a-url.com", "owner": map[string]string{ "login": "monalisa", }, }, }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) config := createConfig{ opts: createOpts{ title: "a title", owner: "monalisa", }, client: client, io: ios, } err := runCreate(config) assert.NoError(t, err) assert.Equal( t, "http://a-url.com\n", stdout.String()) } func TestRunCreate_Org(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get org ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]string{ "login": "github", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "organization": map[string]interface{}{ "id": "an ID", "login": "github", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"user"}, }, }, }) // create project gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation CreateProjectV2.*"variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"ownerId":"an ID","title":"a title"}}}`).Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "createProjectV2": map[string]interface{}{ "projectV2": map[string]interface{}{ "title": "a title", "url": "http://a-url.com", "owner": map[string]string{ "login": "monalisa", }, }, }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) config := createConfig{ opts: createOpts{ title: "a title", owner: "github", }, client: client, io: ios, } err := runCreate(config) assert.NoError(t, err) assert.Equal( t, "http://a-url.com\n", stdout.String()) } func TestRunCreate_Me(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get viewer ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query ViewerOwner.*", }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "viewer": map[string]interface{}{ "id": "an ID", "login": "me", }, }, }) // create project gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation CreateProjectV2.*"variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"ownerId":"an ID","title":"a title"}}}`).Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "createProjectV2": map[string]interface{}{ "projectV2": map[string]interface{}{ "title": "a title", "url": "http://a-url.com", "owner": map[string]string{ "login": "me", }, }, }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) config := createConfig{ opts: createOpts{ title: "a title", owner: "@me", }, client: client, io: ios, } err := runCreate(config) assert.NoError(t, err) assert.Equal( t, "http://a-url.com\n", stdout.String()) } func TestRunCreate_JSON(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get user ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]string{ "login": "monalisa", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "id": "an ID", "login": "monalisa", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"organization"}, }, }, }) // create project gock.New("https://api.github.com"). Post("/graphql"). BodyString(`{"query":"mutation CreateProjectV2.*"variables":{"afterFields":null,"afterItems":null,"firstFields":0,"firstItems":0,"input":{"ownerId":"an ID","title":"a title"}}}`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "createProjectV2": map[string]interface{}{ "projectV2": map[string]interface{}{ "number": 1, "title": "a title", "url": "http://a-url.com", "owner": map[string]string{ "login": "monalisa", }, }, }, }, }) client := queries.NewTestClient() ios, _, stdout, _ := iostreams.Test() config := createConfig{ opts: createOpts{ title: "a title", owner: "monalisa", exporter: cmdutil.NewJSONExporter(), }, client: client, io: ios, } err := runCreate(config) assert.NoError(t, err) assert.JSONEq( t, `{"number":1,"url":"http://a-url.com","shortDescription":"","public":false,"closed":false,"title":"a title","id":"","readme":"","items":{"totalCount":0},"fields":{"totalCount":0},"owner":{"type":"","login":"monalisa"}}`, stdout.String()) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/link/link.go
pkg/cmd/project/link/link.go
package link import ( "fmt" "net/http" "strconv" "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/pkg/cmd/project/shared/client" "github.com/cli/cli/v2/pkg/cmd/project/shared/queries" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type linkOpts struct { number int32 host string owner string repo string team string projectID string projectTitle string repoID string teamID string } type linkConfig struct { httpClient func() (*http.Client, error) config func() (gh.Config, error) client *queries.Client opts linkOpts io *iostreams.IOStreams } func NewCmdLink(f *cmdutil.Factory, runF func(config linkConfig) error) *cobra.Command { opts := linkOpts{} linkCmd := &cobra.Command{ Short: "Link a project to a repository or a team", Use: "link [<number>]", Example: heredoc.Doc(` # Link monalisa's project 1 to her repository "my_repo" $ gh project link 1 --owner monalisa --repo my_repo # Link monalisa's organization's project 1 to her team "my_team" $ gh project link 1 --owner my_organization --team my_team # Link monalisa's project 1 to the repository of current directory if neither --repo nor --team is specified $ gh project link 1 `), RunE: func(cmd *cobra.Command, args []string) error { client, err := client.New(f) if err != nil { return err } if len(args) == 1 { num, err := strconv.ParseInt(args[0], 10, 32) if err != nil { return cmdutil.FlagErrorf("invalid number: %v", args[0]) } opts.number = int32(num) } if opts.repo == "" && opts.team == "" { repo, err := f.BaseRepo() if err != nil { return err } opts.repo = repo.RepoName() if opts.owner == "" { opts.owner = repo.RepoOwner() } } if err := cmdutil.MutuallyExclusive("specify only one of `--repo` or `--team`", opts.repo != "", opts.team != ""); err != nil { return err } if err = validateRepoOrTeamFlag(&opts); err != nil { return err } config := linkConfig{ httpClient: f.HttpClient, config: f.Config, client: client, opts: opts, io: f.IOStreams, } // allow testing of the command without actually running it if runF != nil { return runF(config) } return runLink(config) }, } cmdutil.EnableRepoOverride(linkCmd, f) linkCmd.Flags().StringVar(&opts.owner, "owner", "", "Login of the owner. Use \"@me\" for the current user.") linkCmd.Flags().StringVarP(&opts.repo, "repo", "R", "", "The repository to be linked to this project") linkCmd.Flags().StringVarP(&opts.team, "team", "T", "", "The team to be linked to this project") return linkCmd } func validateRepoOrTeamFlag(opts *linkOpts) error { linkedTarget := "" if opts.repo != "" { linkedTarget = opts.repo } else if opts.team != "" { linkedTarget = opts.team } if strings.Contains(linkedTarget, "/") { nameArgs := strings.Split(linkedTarget, "/") var host, owner, name string if len(nameArgs) == 2 { owner = nameArgs[0] name = nameArgs[1] } else if len(nameArgs) == 3 { host = nameArgs[0] owner = nameArgs[1] name = nameArgs[2] } else { if opts.repo != "" { return fmt.Errorf("expected the \"[HOST/]OWNER/REPO\" or \"REPO\" format, got \"%s\"", linkedTarget) } else if opts.team != "" { return fmt.Errorf("expected the \"[HOST/]OWNER/TEAM\" or \"TEAM\" format, got \"%s\"", linkedTarget) } } if opts.owner != "" && opts.owner != owner { return fmt.Errorf("'%s' has different owner from '%s'", linkedTarget, opts.owner) } opts.owner = owner opts.host = host if opts.repo != "" { opts.repo = name } else if opts.team != "" { opts.team = name } } return nil } func runLink(config linkConfig) error { canPrompt := config.io.CanPrompt() owner, err := config.client.NewOwner(canPrompt, config.opts.owner) if err != nil { return err } config.opts.owner = owner.Login project, err := config.client.NewProject(canPrompt, owner, config.opts.number, false) if err != nil { return err } config.opts.projectTitle = project.Title config.opts.projectID = project.ID if config.opts.number == 0 { config.opts.number = project.Number } httpClient, err := config.httpClient() if err != nil { return err } c := api.NewClientFromHTTP(httpClient) if config.opts.host == "" { cfg, err := config.config() if err != nil { return err } host, _ := cfg.Authentication().DefaultHost() config.opts.host = host } if config.opts.repo != "" { return linkRepo(c, config) } else if config.opts.team != "" { return linkTeam(c, config) } return nil } func linkRepo(c *api.Client, config linkConfig) error { repo, err := api.GitHubRepo(c, ghrepo.NewWithHost(config.opts.owner, config.opts.repo, config.opts.host)) if err != nil { return err } config.opts.repoID = repo.ID err = config.client.LinkProjectToRepository(config.opts.projectID, config.opts.repoID) if err != nil { return err } return printResults(config, config.opts.repo) } func linkTeam(c *api.Client, config linkConfig) error { team, err := api.OrganizationTeam(c, config.opts.host, config.opts.owner, config.opts.team) if err != nil { return err } config.opts.teamID = team.ID err = config.client.LinkProjectToTeam(config.opts.projectID, config.opts.teamID) if err != nil { return err } return printResults(config, config.opts.team) } func printResults(config linkConfig, linkedTarget string) error { if !config.io.IsStdoutTTY() { return nil } _, err := fmt.Fprintf(config.io.Out, "Linked '%s/%s' to project #%d '%s'\n", config.opts.owner, linkedTarget, config.opts.number, config.opts.projectTitle) return err }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/link/link_test.go
pkg/cmd/project/link/link_test.go
package link 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/project/shared/queries" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/require" "gopkg.in/h2non/gock.v1" ) func TestNewCmdLink(t *testing.T) { tests := []struct { name string cli string wants linkOpts wantsErr bool wantsErrMsg string wantsExporter bool }{ { name: "not-a-number", cli: "x", wantsErr: true, wantsErrMsg: "invalid number: x", }, { name: "specify-repo-and-team", cli: "--repo my-repo --team my-team", wantsErr: true, wantsErrMsg: "specify only one of `--repo` or `--team`", }, { name: "specify-nothing", cli: "", wants: linkOpts{ owner: "OWNER", repo: "REPO", }, }, { name: "repo", cli: "--repo my-repo", wants: linkOpts{ repo: "my-repo", }, }, { name: "repo-flag-contains-owner", cli: "--repo monalisa/my-repo", wants: linkOpts{ owner: "monalisa", repo: "my-repo", }, }, { name: "repo-flag-contains-owner-and-host", cli: "--repo github.com/monalisa/my-repo", wants: linkOpts{ host: "github.com", owner: "monalisa", repo: "my-repo", }, }, { name: "repo-flag-contains-wrong-format", cli: "--repo h/e/l/l/o", wantsErr: true, wantsErrMsg: "expected the \"[HOST/]OWNER/REPO\" or \"REPO\" format, got \"h/e/l/l/o\"", }, { name: "repo-flag-with-owner-different-from-owner-flag", cli: "--repo monalisa/my-repo --owner leonardo", wantsErr: true, wantsErrMsg: "'monalisa/my-repo' has different owner from 'leonardo'", }, { name: "team", cli: "--team my-team", wants: linkOpts{ team: "my-team", }, }, { name: "team-flag-contains-owner", cli: "--team my-org/my-team", wants: linkOpts{ owner: "my-org", team: "my-team", }, }, { name: "team-flag-contains-owner-and-host", cli: "--team github.com/my-org/my-team", wants: linkOpts{ host: "github.com", owner: "my-org", team: "my-team", }, }, { name: "team-flag-contains-wrong-format", cli: "--team h/e/l/l/o", wantsErr: true, wantsErrMsg: "expected the \"[HOST/]OWNER/TEAM\" or \"TEAM\" format, got \"h/e/l/l/o\"", }, { name: "team-flag-with-owner-different-from-owner-flag", cli: "--team my-org/my-team --owner her-org", wantsErr: true, wantsErrMsg: "'my-org/my-team' has different owner from 'her-org'", }, { name: "number", cli: "123 --repo my-repo", wants: linkOpts{ number: 123, repo: "my-repo", }, }, { name: "owner-with-repo-flag", cli: "--repo my-repo --owner monalisa", wants: linkOpts{ owner: "monalisa", repo: "my-repo", }, }, { name: "owner-without-repo-flag", cli: "--owner monalisa", wants: linkOpts{ owner: "monalisa", repo: "REPO", }, }, } t.Setenv("GH_TOKEN", "auth-token") for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() f := &cmdutil.Factory{ IOStreams: ios, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil }, } argv, err := shlex.Split(tt.cli) require.NoError(t, err) var gotOpts linkOpts cmd := NewCmdLink(f, func(config linkConfig) error { gotOpts = config.opts return nil }) cmd.SetArgs(argv) _, err = cmd.ExecuteC() if tt.wantsErr { require.Error(t, err) require.Equal(t, tt.wantsErrMsg, err.Error()) return } require.NoError(t, err) require.Equal(t, tt.wants.number, gotOpts.number) require.Equal(t, tt.wants.owner, gotOpts.owner) require.Equal(t, tt.wants.repo, gotOpts.repo) require.Equal(t, tt.wants.team, gotOpts.team) require.Equal(t, tt.wants.projectID, gotOpts.projectID) require.Equal(t, tt.wants.repoID, gotOpts.repoID) require.Equal(t, tt.wants.teamID, gotOpts.teamID) }) } } func TestRunLink_Repo(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get user ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]string{ "login": "monalisa", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "id": "an ID", "login": "monalisa", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"organization"}, }, }, }) // get user project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserProject.*", "variables": map[string]interface{}{ "login": "monalisa", "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "projectV2": map[string]string{ "id": "project-ID", "title": "first-project", }, }, }, }) // link projectV2 to repository gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "mutation LinkProjectV2ToRepository.*", }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "linkProjectV2ToRepository": map[string]interface{}{}, }, }) // get repo ID gock.New("https://api.github.com"). Post("/graphql"). BodyString(`.*query RepositoryInfo.*`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "repository": map[string]interface{}{ "id": "repo-ID", }, }, }) ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) cfg := linkConfig{ opts: linkOpts{ number: 1, repo: "my-repo", owner: "monalisa", }, client: queries.NewTestClient(), httpClient: func() (*http.Client, error) { return http.DefaultClient, nil }, config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, io: ios, } err := runLink(cfg) require.NoError(t, err) require.Equal( t, "Linked 'monalisa/my-repo' to project #1 'first-project'\n", stdout.String()) } func TestRunLink_Team(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // get user ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserOrgOwner.*", "variables": map[string]string{ "login": "monalisa-org", }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "id": "an ID", "login": "monalisa-org", }, }, "errors": []interface{}{ map[string]interface{}{ "type": "NOT_FOUND", "path": []string{"organization"}, }, }, }) // get user project ID gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "query UserProject.*", "variables": map[string]interface{}{ "login": "monalisa-org", "number": 1, "firstItems": 0, "afterItems": nil, "firstFields": 0, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "projectV2": map[string]string{ "id": "project-ID", "title": "first-project", }, }, }, }) // link projectV2 to team gock.New("https://api.github.com"). Post("/graphql"). MatchType("json"). JSON(map[string]interface{}{ "query": "mutation LinkProjectV2ToTeam.*", }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "linkProjectV2ToTeam": map[string]interface{}{}, }, }) // get team ID gock.New("https://api.github.com"). Post("/graphql"). BodyString(`.*query OrganizationTeam.*`). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "organization": map[string]interface{}{ "team": map[string]interface{}{ "id": "team-ID", }, }, }, }) ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) cfg := linkConfig{ opts: linkOpts{ number: 1, team: "my-team", owner: "monalisa-org", }, client: queries.NewTestClient(), httpClient: func() (*http.Client, error) { return http.DefaultClient, nil }, config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, io: ios, } err := runLink(cfg) require.NoError(t, err) require.Equal( t, "Linked 'monalisa-org/my-team' to project #1 'first-project'\n", stdout.String()) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/shared/queries/export_data_test.go
pkg/cmd/project/shared/queries/export_data_test.go
package queries import ( "encoding/json" "testing" "github.com/stretchr/testify/assert" ) // Regression test from before ExportData was implemented. func TestJSONProject_User(t *testing.T) { project := Project{ ID: "123", Number: 2, URL: "a url", ShortDescription: "short description", Public: true, Readme: "readme", } project.Items.TotalCount = 1 project.Fields.TotalCount = 2 project.Owner.TypeName = "User" project.Owner.User.Login = "monalisa" b, err := json.Marshal(project.ExportData(nil)) assert.NoError(t, err) assert.JSONEq(t, `{"number":2,"url":"a url","shortDescription":"short description","public":true,"closed":false,"title":"","id":"123","readme":"readme","items":{"totalCount":1},"fields":{"totalCount":2},"owner":{"type":"User","login":"monalisa"}}`, string(b)) } // Regression test from before ExportData was implemented. func TestJSONProject_Org(t *testing.T) { project := Project{ ID: "123", Number: 2, URL: "a url", ShortDescription: "short description", Public: true, Readme: "readme", } project.Items.TotalCount = 1 project.Fields.TotalCount = 2 project.Owner.TypeName = "Organization" project.Owner.Organization.Login = "github" b, err := json.Marshal(project.ExportData(nil)) assert.NoError(t, err) assert.JSONEq(t, `{"number":2,"url":"a url","shortDescription":"short description","public":true,"closed":false,"title":"","id":"123","readme":"readme","items":{"totalCount":1},"fields":{"totalCount":2},"owner":{"type":"Organization","login":"github"}}`, string(b)) } // Regression test from before ExportData was implemented. func TestJSONProjects(t *testing.T) { userProject := Project{ ID: "123", Number: 2, URL: "a url", ShortDescription: "short description", Public: true, Readme: "readme", } userProject.Items.TotalCount = 1 userProject.Fields.TotalCount = 2 userProject.Owner.TypeName = "User" userProject.Owner.User.Login = "monalisa" orgProject := Project{ ID: "123", Number: 2, URL: "a url", ShortDescription: "short description", Public: true, Readme: "readme", } orgProject.Items.TotalCount = 1 orgProject.Fields.TotalCount = 2 orgProject.Owner.TypeName = "Organization" orgProject.Owner.Organization.Login = "github" projects := Projects{ Nodes: []Project{userProject, orgProject}, TotalCount: 2, } b, err := json.Marshal(projects.ExportData(nil)) assert.NoError(t, err) assert.JSONEq( t, `{"projects":[{"number":2,"url":"a url","shortDescription":"short description","public":true,"closed":false,"title":"","id":"123","readme":"readme","items":{"totalCount":1},"fields":{"totalCount":2},"owner":{"type":"User","login":"monalisa"}},{"number":2,"url":"a url","shortDescription":"short description","public":true,"closed":false,"title":"","id":"123","readme":"readme","items":{"totalCount":1},"fields":{"totalCount":2},"owner":{"type":"Organization","login":"github"}}],"totalCount":2}`, string(b)) } func TestJSONProjectField_FieldType(t *testing.T) { field := ProjectField{} field.TypeName = "ProjectV2Field" field.Field.ID = "123" field.Field.Name = "name" b, err := json.Marshal(field.ExportData(nil)) assert.NoError(t, err) assert.Equal(t, `{"id":"123","name":"name","type":"ProjectV2Field"}`, string(b)) } func TestJSONProjectField_SingleSelectType(t *testing.T) { field := ProjectField{} field.TypeName = "ProjectV2SingleSelectField" field.SingleSelectField.ID = "123" field.SingleSelectField.Name = "name" field.SingleSelectField.Options = []SingleSelectFieldOptions{ { ID: "123", Name: "name", }, { ID: "456", Name: "name2", }, } b, err := json.Marshal(field.ExportData(nil)) assert.NoError(t, err) assert.JSONEq(t, `{"id":"123","name":"name","type":"ProjectV2SingleSelectField","options":[{"id":"123","name":"name"},{"id":"456","name":"name2"}]}`, string(b)) } func TestJSONProjectField_ProjectV2IterationField(t *testing.T) { field := ProjectField{} field.TypeName = "ProjectV2IterationField" field.IterationField.ID = "123" field.IterationField.Name = "name" b, err := json.Marshal(field.ExportData(nil)) assert.NoError(t, err) assert.Equal(t, `{"id":"123","name":"name","type":"ProjectV2IterationField"}`, string(b)) } func TestJSONProjectFields(t *testing.T) { field := ProjectField{} field.TypeName = "ProjectV2Field" field.Field.ID = "123" field.Field.Name = "name" field2 := ProjectField{} field2.TypeName = "ProjectV2SingleSelectField" field2.SingleSelectField.ID = "123" field2.SingleSelectField.Name = "name" field2.SingleSelectField.Options = []SingleSelectFieldOptions{ { ID: "123", Name: "name", }, { ID: "456", Name: "name2", }, } p := &Project{ Fields: struct { TotalCount int Nodes []ProjectField PageInfo PageInfo }{ Nodes: []ProjectField{field, field2}, TotalCount: 5, }, } b, err := json.Marshal(p.Fields.ExportData(nil)) assert.NoError(t, err) assert.JSONEq(t, `{"fields":[{"id":"123","name":"name","type":"ProjectV2Field"},{"id":"123","name":"name","type":"ProjectV2SingleSelectField","options":[{"id":"123","name":"name"},{"id":"456","name":"name2"}]}],"totalCount":5}`, string(b)) } func TestJSONProjectItem_DraftIssue(t *testing.T) { item := ProjectItem{} item.Content.TypeName = "DraftIssue" item.Id = "123" item.Content.DraftIssue.Title = "title" item.Content.DraftIssue.Body = "a body" b, err := json.Marshal(item.ExportData(nil)) assert.NoError(t, err) assert.JSONEq(t, `{"id":"123","title":"title","body":"a body","type":"DraftIssue"}`, string(b)) } func TestJSONProjectItem_Issue(t *testing.T) { item := ProjectItem{} item.Content.TypeName = "Issue" item.Id = "123" item.Content.Issue.Title = "title" item.Content.Issue.Body = "a body" item.Content.Issue.URL = "a-url" b, err := json.Marshal(item.ExportData(nil)) assert.NoError(t, err) assert.JSONEq(t, `{"id":"123","title":"title","body":"a body","type":"Issue","url":"a-url"}`, string(b)) } func TestJSONProjectItem_PullRequest(t *testing.T) { item := ProjectItem{} item.Content.TypeName = "PullRequest" item.Id = "123" item.Content.PullRequest.Title = "title" item.Content.PullRequest.Body = "a body" item.Content.PullRequest.URL = "a-url" b, err := json.Marshal(item.ExportData(nil)) assert.NoError(t, err) assert.JSONEq(t, `{"id":"123","title":"title","body":"a body","type":"PullRequest","url":"a-url"}`, string(b)) } func TestJSONProjectDetailedItems(t *testing.T) { p := &Project{} p.Items.TotalCount = 5 p.Items.Nodes = []ProjectItem{ { Id: "issueId", Content: ProjectItemContent{ TypeName: "Issue", Issue: Issue{ Title: "Issue title", Body: "a body", Number: 1, URL: "issue-url", Repository: struct { NameWithOwner string }{ NameWithOwner: "cli/go-gh", }, }, }, }, { Id: "pullRequestId", Content: ProjectItemContent{ TypeName: "PullRequest", PullRequest: PullRequest{ Title: "Pull Request title", Body: "a body", Number: 2, URL: "pr-url", Repository: struct { NameWithOwner string }{ NameWithOwner: "cli/go-gh", }, }, }, }, { Id: "draftIssueId", Content: ProjectItemContent{ TypeName: "DraftIssue", DraftIssue: DraftIssue{ ID: "draftIssueId", Title: "Pull Request title", Body: "a body", }, }, }, } out, err := json.Marshal(p.DetailedItems()) assert.NoError(t, err) assert.JSONEq( t, `{"items":[{"content":{"type":"Issue","body":"a body","title":"Issue title","number":1,"repository":"cli/go-gh","url":"issue-url"},"id":"issueId"},{"content":{"type":"PullRequest","body":"a body","title":"Pull Request title","number":2,"repository":"cli/go-gh","url":"pr-url"},"id":"pullRequestId"},{"content":{"type":"DraftIssue","body":"a body","title":"Pull Request title","id":"draftIssueId"},"id":"draftIssueId"}],"totalCount":5}`, string(out)) } func TestJSONProjectDraftIssue(t *testing.T) { item := DraftIssue{} item.ID = "123" item.Title = "title" item.Body = "a body" b, err := json.Marshal(item.ExportData(nil)) assert.NoError(t, err) assert.JSONEq(t, `{"id":"123","title":"title","body":"a body","type":"DraftIssue"}`, string(b)) } func TestJSONProjectItem_DraftIssue_ProjectV2ItemFieldIterationValue(t *testing.T) { iterationField := ProjectField{TypeName: "ProjectV2IterationField"} iterationField.IterationField.ID = "sprint" iterationField.IterationField.Name = "Sprint" iterationFieldValue := FieldValueNodes{Type: "ProjectV2ItemFieldIterationValue"} iterationFieldValue.ProjectV2ItemFieldIterationValue.Title = "Iteration Title" iterationFieldValue.ProjectV2ItemFieldIterationValue.Field = iterationField iterationFieldValue.ProjectV2ItemFieldIterationValue.IterationId = "iterationId" draftIssue := ProjectItem{ Id: "draftIssueId", Content: ProjectItemContent{ TypeName: "DraftIssue", DraftIssue: DraftIssue{ ID: "draftIssueId", Title: "Pull Request title", Body: "a body", }, }, } draftIssue.FieldValues.Nodes = []FieldValueNodes{ iterationFieldValue, } p := &Project{} p.Fields.Nodes = []ProjectField{iterationField} p.Items.TotalCount = 5 p.Items.Nodes = []ProjectItem{ draftIssue, } out, err := json.Marshal(p.DetailedItems()) assert.NoError(t, err) assert.JSONEq( t, `{"items":[{"sprint":{"title":"Iteration Title","startDate":"","duration":0,"iterationId":"iterationId"},"content":{"type":"DraftIssue","body":"a body","title":"Pull Request title","id":"draftIssueId"},"id":"draftIssueId"}],"totalCount":5}`, string(out)) } func TestJSONProjectItem_DraftIssue_ProjectV2ItemFieldMilestoneValue(t *testing.T) { milestoneField := ProjectField{TypeName: "ProjectV2IterationField"} milestoneField.IterationField.ID = "milestone" milestoneField.IterationField.Name = "Milestone" milestoneFieldValue := FieldValueNodes{Type: "ProjectV2ItemFieldMilestoneValue"} milestoneFieldValue.ProjectV2ItemFieldMilestoneValue.Milestone.Title = "Milestone Title" milestoneFieldValue.ProjectV2ItemFieldMilestoneValue.Field = milestoneField draftIssue := ProjectItem{ Id: "draftIssueId", Content: ProjectItemContent{ TypeName: "DraftIssue", DraftIssue: DraftIssue{ ID: "draftIssueId", Title: "Pull Request title", Body: "a body", }, }, } draftIssue.FieldValues.Nodes = []FieldValueNodes{ milestoneFieldValue, } p := &Project{} p.Fields.Nodes = []ProjectField{milestoneField} p.Items.TotalCount = 5 p.Items.Nodes = []ProjectItem{ draftIssue, } out, err := json.Marshal(p.DetailedItems()) assert.NoError(t, err) assert.JSONEq( t, `{"items":[{"milestone":{"title":"Milestone Title","dueOn":"","description":""},"content":{"type":"DraftIssue","body":"a body","title":"Pull Request title","id":"draftIssueId"},"id":"draftIssueId"}],"totalCount":5}`, string(out)) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/shared/queries/queries_test.go
pkg/cmd/project/shared/queries/queries_test.go
package queries import ( "reflect" "testing" "github.com/stretchr/testify/assert" "gopkg.in/h2non/gock.v1" ) func TestProjectItems_DefaultLimit(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // list project items gock.New("https://api.github.com"). Post("/graphql"). JSON(map[string]interface{}{ "query": "query UserProjectWithItems.*", "variables": map[string]interface{}{ "firstItems": LimitMax, "afterItems": nil, "firstFields": LimitMax, "afterFields": nil, "login": "monalisa", "number": 1, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "projectV2": map[string]interface{}{ "items": map[string]interface{}{ "nodes": []map[string]interface{}{ { "id": "issue ID", }, { "id": "pull request ID", }, { "id": "draft issue ID", }, }, }, }, }, }, }) client := NewTestClient() owner := &Owner{ Type: "USER", Login: "monalisa", ID: "user ID", } project, err := client.ProjectItems(owner, 1, LimitMax) assert.NoError(t, err) assert.Len(t, project.Items.Nodes, 3) } func TestProjectItems_LowerLimit(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // list project items gock.New("https://api.github.com"). Post("/graphql"). JSON(map[string]interface{}{ "query": "query UserProjectWithItems.*", "variables": map[string]interface{}{ "firstItems": 2, "afterItems": nil, "firstFields": LimitMax, "afterFields": nil, "login": "monalisa", "number": 1, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "projectV2": map[string]interface{}{ "items": map[string]interface{}{ "nodes": []map[string]interface{}{ { "id": "issue ID", }, { "id": "pull request ID", }, }, }, }, }, }, }) client := NewTestClient() owner := &Owner{ Type: "USER", Login: "monalisa", ID: "user ID", } project, err := client.ProjectItems(owner, 1, 2) assert.NoError(t, err) assert.Len(t, project.Items.Nodes, 2) } func TestProjectItems_NoLimit(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // list project items gock.New("https://api.github.com"). Post("/graphql"). JSON(map[string]interface{}{ "query": "query UserProjectWithItems.*", "variables": map[string]interface{}{ "firstItems": LimitDefault, "afterItems": nil, "firstFields": LimitMax, "afterFields": nil, "login": "monalisa", "number": 1, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "projectV2": map[string]interface{}{ "items": map[string]interface{}{ "nodes": []map[string]interface{}{ { "id": "issue ID", }, { "id": "pull request ID", }, { "id": "draft issue ID", }, }, }, }, }, }, }) client := NewTestClient() owner := &Owner{ Type: "USER", Login: "monalisa", ID: "user ID", } project, err := client.ProjectItems(owner, 1, 0) assert.NoError(t, err) assert.Len(t, project.Items.Nodes, 3) } func TestProjectFields_LowerLimit(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // list project fields gock.New("https://api.github.com"). Post("/graphql"). JSON(map[string]interface{}{ "query": "query UserProject.*", "variables": map[string]interface{}{ "login": "monalisa", "number": 1, "firstItems": LimitMax, "afterItems": nil, "firstFields": 2, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "projectV2": map[string]interface{}{ "fields": map[string]interface{}{ "nodes": []map[string]interface{}{ { "id": "field ID", }, { "id": "status ID", }, }, }, }, }, }, }) client := NewTestClient() owner := &Owner{ Type: "USER", Login: "monalisa", ID: "user ID", } project, err := client.ProjectFields(owner, 1, 2) assert.NoError(t, err) assert.Len(t, project.Fields.Nodes, 2) } func TestProjectFields_DefaultLimit(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // list project fields // list project fields gock.New("https://api.github.com"). Post("/graphql"). JSON(map[string]interface{}{ "query": "query UserProject.*", "variables": map[string]interface{}{ "login": "monalisa", "number": 1, "firstItems": LimitMax, "afterItems": nil, "firstFields": LimitMax, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "projectV2": map[string]interface{}{ "fields": map[string]interface{}{ "nodes": []map[string]interface{}{ { "id": "field ID", }, { "id": "status ID", }, { "id": "iteration ID", }, }, }, }, }, }, }) client := NewTestClient() owner := &Owner{ Type: "USER", Login: "monalisa", ID: "user ID", } project, err := client.ProjectFields(owner, 1, LimitMax) assert.NoError(t, err) assert.Len(t, project.Fields.Nodes, 3) } func TestProjectFields_NoLimit(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // list project fields gock.New("https://api.github.com"). Post("/graphql"). JSON(map[string]interface{}{ "query": "query UserProject.*", "variables": map[string]interface{}{ "login": "monalisa", "number": 1, "firstItems": LimitMax, "afterItems": nil, "firstFields": LimitDefault, "afterFields": nil, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "projectV2": map[string]interface{}{ "fields": map[string]interface{}{ "nodes": []map[string]interface{}{ { "id": "field ID", }, { "id": "status ID", }, { "id": "iteration ID", }, }, }, }, }, }, }) client := NewTestClient() owner := &Owner{ Type: "USER", Login: "monalisa", ID: "user ID", } project, err := client.ProjectFields(owner, 1, 0) assert.NoError(t, err) assert.Len(t, project.Fields.Nodes, 3) } func Test_requiredScopesFromServerMessage(t *testing.T) { tests := []struct { name string msg string want []string }{ { name: "no scopes", msg: "SERVER OOPSIE", want: []string(nil), }, { name: "one scope", msg: "Your token has not been granted the required scopes to execute this query. The 'dataType' field requires one of the following scopes: ['read:project'], but your token has only been granted the: ['codespace', repo'] scopes. Please modify your token's scopes at: https://github.com/settings/tokens.", want: []string{"read:project"}, }, { name: "multiple scopes", msg: "Your token has not been granted the required scopes to execute this query. The 'dataType' field requires one of the following scopes: ['read:project', 'read:discussion', 'codespace'], but your token has only been granted the: [repo'] scopes. Please modify your token's scopes at: https://github.com/settings/tokens.", want: []string{"read:project", "read:discussion", "codespace"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := requiredScopesFromServerMessage(tt.msg); !reflect.DeepEqual(got, tt.want) { t.Errorf("requiredScopesFromServerMessage() = %v, want %v", got, tt.want) } }) } } func TestNewProject_nonTTY(t *testing.T) { client := NewTestClient() _, err := client.NewProject(false, &Owner{}, 0, false) assert.EqualError(t, err, "project number is required when not running interactively") } func TestNewOwner_nonTTY(t *testing.T) { client := NewTestClient() _, err := client.NewOwner(false, "") assert.EqualError(t, err, "owner is required when not running interactively") } func TestProjectItems_FieldTitle(t *testing.T) { defer gock.Off() gock.Observe(gock.DumpRequest) // list project items gock.New("https://api.github.com"). Post("/graphql"). JSON(map[string]interface{}{ "query": "query UserProjectWithItems.*", "variables": map[string]interface{}{ "firstItems": LimitMax, "afterItems": nil, "firstFields": LimitMax, "afterFields": nil, "login": "monalisa", "number": 1, }, }). Reply(200). JSON(map[string]interface{}{ "data": map[string]interface{}{ "user": map[string]interface{}{ "projectV2": map[string]interface{}{ "items": map[string]interface{}{ "nodes": []map[string]interface{}{ { "id": "draft issue ID", "fieldValues": map[string]interface{}{ "nodes": []map[string]interface{}{ { "__typename": "ProjectV2ItemFieldIterationValue", "title": "Iteration Title 1", "iterationId": "iterationId1", }, { "__typename": "ProjectV2ItemFieldMilestoneValue", "milestone": map[string]interface{}{ "title": "Milestone Title 1", }, }, }, }, }, }, }, }, }, }, }) client := NewTestClient() owner := &Owner{ Type: "USER", Login: "monalisa", ID: "user ID", } project, err := client.ProjectItems(owner, 1, LimitMax) assert.NoError(t, err) assert.Len(t, project.Items.Nodes, 1) assert.Len(t, project.Items.Nodes[0].FieldValues.Nodes, 2) assert.Equal(t, project.Items.Nodes[0].FieldValues.Nodes[0].ProjectV2ItemFieldIterationValue.Title, "Iteration Title 1") assert.Equal(t, project.Items.Nodes[0].FieldValues.Nodes[0].ProjectV2ItemFieldIterationValue.IterationId, "iterationId1") assert.Equal(t, project.Items.Nodes[0].FieldValues.Nodes[1].ProjectV2ItemFieldMilestoneValue.Milestone.Title, "Milestone Title 1") } func TestCamelCase(t *testing.T) { assert.Equal(t, "camelCase", camelCase("camelCase")) assert.Equal(t, "camelCase", camelCase("CamelCase")) assert.Equal(t, "c", camelCase("C")) assert.Equal(t, "", camelCase("")) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/shared/queries/queries.go
pkg/cmd/project/shared/queries/queries.go
package queries import ( "errors" "fmt" "net/http" "net/url" "regexp" "strings" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/pkg/set" "github.com/shurcooL/githubv4" ) func NewClient(httpClient *http.Client, hostname string, ios *iostreams.IOStreams) *Client { apiClient := &hostScopedClient{ hostname: hostname, Client: api.NewClientFromHTTP(httpClient), } return &Client{ apiClient: apiClient, io: ios, prompter: prompter.New("", ios), } } // TestClientOpt is a test option for the test client. type TestClientOpt func(*Client) // WithPrompter is a test option to set the prompter for the test client. func WithPrompter(p iprompter) TestClientOpt { return func(c *Client) { c.prompter = p } } func NewTestClient(opts ...TestClientOpt) *Client { apiClient := &hostScopedClient{ hostname: "github.com", Client: api.NewClientFromHTTP(http.DefaultClient), } io, _, _, _ := iostreams.Test() c := &Client{ apiClient: apiClient, io: io, prompter: nil, } for _, o := range opts { o(c) } return c } type iprompter interface { Select(string, string, []string) (int, error) } type hostScopedClient struct { *api.Client hostname string } func (c *hostScopedClient) Query(queryName string, query interface{}, variables map[string]interface{}) error { return c.Client.Query(c.hostname, queryName, query, variables) } func (c *hostScopedClient) Mutate(queryName string, query interface{}, variables map[string]interface{}) error { return c.Client.Mutate(c.hostname, queryName, query, variables) } type graphqlClient interface { Query(queryName string, query interface{}, variables map[string]interface{}) error Mutate(queryName string, query interface{}, variables map[string]interface{}) error } type Client struct { apiClient graphqlClient io *iostreams.IOStreams prompter iprompter } const ( LimitDefault = 30 LimitMax = 100 // https://docs.github.com/en/graphql/overview/resource-limitations#node-limit ) // doQueryWithProgressIndicator wraps API calls with a progress indicator. // The query name is used in the progress indicator label. func (c *Client) doQueryWithProgressIndicator(name string, query interface{}, variables map[string]interface{}) error { c.io.StartProgressIndicatorWithLabel(fmt.Sprintf("Fetching %s", name)) defer c.io.StopProgressIndicator() err := c.apiClient.Query(name, query, variables) return handleError(err) } // TODO: un-export this since it couples the caller heavily to api.GraphQLClient func (c *Client) Mutate(operationName string, query interface{}, variables map[string]interface{}) error { err := c.apiClient.Mutate(operationName, query, variables) return handleError(err) } // PageInfo is a PageInfo GraphQL object https://docs.github.com/en/graphql/reference/objects#pageinfo. type PageInfo struct { EndCursor githubv4.String HasNextPage bool } // Project is a ProjectV2 GraphQL object https://docs.github.com/en/graphql/reference/objects#projectv2. type Project struct { Number int32 URL string ShortDescription string Public bool Closed bool // The Template field is commented out due to https://github.com/cli/cli/issues/8103. // We released gh v2.34.0 without realizing the Template field does not exist // on GHES 3.8 and older. This broke all project commands for users targeting GHES 3.8 // and older. In order to fix this we will no longer query the Template field until // GHES 3.8 gets deprecated on 2024-03-07. This solution was simpler and quicker // than adding a feature detection measure to every place this query is used. // It does have the negative consequence that we have had to remove the // Template field when outputting projects to JSON using the --format flag supported // by a number of project commands. See `pkg/cmd/project/shared/format/json.go` for // implementation. // Template bool Title string ID string Readme string Items struct { PageInfo PageInfo TotalCount int Nodes []ProjectItem } `graphql:"items(first: $firstItems, after: $afterItems)"` Fields ProjectFields `graphql:"fields(first: $firstFields, after: $afterFields)"` Owner struct { TypeName string `graphql:"__typename"` User struct { Login string } `graphql:"... on User"` Organization struct { Login string } `graphql:"... on Organization"` } } func (p Project) DetailedItems() map[string]interface{} { return map[string]interface{}{ "items": serializeProjectWithItems(&p), "totalCount": p.Items.TotalCount, } } func (p Project) ExportData(_ []string) map[string]interface{} { return map[string]interface{}{ "number": p.Number, "url": p.URL, "shortDescription": p.ShortDescription, "public": p.Public, "closed": p.Closed, "title": p.Title, "id": p.ID, "readme": p.Readme, "items": map[string]interface{}{ "totalCount": p.Items.TotalCount, }, "fields": map[string]interface{}{ "totalCount": p.Fields.TotalCount, }, "owner": map[string]interface{}{ "type": p.OwnerType(), "login": p.OwnerLogin(), }, } } func (p Project) OwnerType() string { return p.Owner.TypeName } func (p Project) OwnerLogin() string { if p.OwnerType() == "User" { return p.Owner.User.Login } return p.Owner.Organization.Login } type Projects struct { Nodes []Project TotalCount int } func (p Projects) ExportData(_ []string) map[string]interface{} { v := make([]map[string]interface{}, len(p.Nodes)) for i := range p.Nodes { v[i] = p.Nodes[i].ExportData(nil) } return map[string]interface{}{ "projects": v, "totalCount": p.TotalCount, } } // ProjectItem is a ProjectV2Item GraphQL object https://docs.github.com/en/graphql/reference/objects#projectv2item. type ProjectItem struct { Content ProjectItemContent Id string FieldValues struct { Nodes []FieldValueNodes } `graphql:"fieldValues(first: 100)"` // hardcoded to 100 for now on the assumption that this is a reasonable limit } type ProjectItemContent struct { TypeName string `graphql:"__typename"` DraftIssue DraftIssue `graphql:"... on DraftIssue"` PullRequest PullRequest `graphql:"... on PullRequest"` Issue Issue `graphql:"... on Issue"` } type FieldValueNodes struct { Type string `graphql:"__typename"` ProjectV2ItemFieldDateValue struct { Date string Field ProjectField } `graphql:"... on ProjectV2ItemFieldDateValue"` ProjectV2ItemFieldIterationValue struct { Title string StartDate string Duration int Field ProjectField IterationId string } `graphql:"... on ProjectV2ItemFieldIterationValue"` ProjectV2ItemFieldLabelValue struct { Labels struct { Nodes []struct { Name string } } `graphql:"labels(first: 10)"` // experienced issues with larger limits, 10 seems like enough for now Field ProjectField } `graphql:"... on ProjectV2ItemFieldLabelValue"` ProjectV2ItemFieldNumberValue struct { Number float64 Field ProjectField } `graphql:"... on ProjectV2ItemFieldNumberValue"` ProjectV2ItemFieldSingleSelectValue struct { Name string Field ProjectField } `graphql:"... on ProjectV2ItemFieldSingleSelectValue"` ProjectV2ItemFieldTextValue struct { Text string Field ProjectField } `graphql:"... on ProjectV2ItemFieldTextValue"` ProjectV2ItemFieldMilestoneValue struct { Milestone struct { Title string Description string DueOn string } Field ProjectField } `graphql:"... on ProjectV2ItemFieldMilestoneValue"` ProjectV2ItemFieldPullRequestValue struct { PullRequests struct { Nodes []struct { Url string } } `graphql:"pullRequests(first:10)"` // experienced issues with larger limits, 10 seems like enough for now Field ProjectField } `graphql:"... on ProjectV2ItemFieldPullRequestValue"` ProjectV2ItemFieldRepositoryValue struct { Repository struct { Url string } Field ProjectField } `graphql:"... on ProjectV2ItemFieldRepositoryValue"` ProjectV2ItemFieldUserValue struct { Users struct { Nodes []struct { Login string } } `graphql:"users(first: 10)"` // experienced issues with larger limits, 10 seems like enough for now Field ProjectField } `graphql:"... on ProjectV2ItemFieldUserValue"` ProjectV2ItemFieldReviewerValue struct { Reviewers struct { Nodes []struct { Type string `graphql:"__typename"` Team struct { Name string } `graphql:"... on Team"` User struct { Login string } `graphql:"... on User"` } } `graphql:"reviewers(first: 10)"` // experienced issues with larger limits, 10 seems like enough for now Field ProjectField } `graphql:"... on ProjectV2ItemFieldReviewerValue"` } func (v FieldValueNodes) ID() string { switch v.Type { case "ProjectV2ItemFieldDateValue": return v.ProjectV2ItemFieldDateValue.Field.ID() case "ProjectV2ItemFieldIterationValue": return v.ProjectV2ItemFieldIterationValue.Field.ID() case "ProjectV2ItemFieldNumberValue": return v.ProjectV2ItemFieldNumberValue.Field.ID() case "ProjectV2ItemFieldSingleSelectValue": return v.ProjectV2ItemFieldSingleSelectValue.Field.ID() case "ProjectV2ItemFieldTextValue": return v.ProjectV2ItemFieldTextValue.Field.ID() case "ProjectV2ItemFieldMilestoneValue": return v.ProjectV2ItemFieldMilestoneValue.Field.ID() case "ProjectV2ItemFieldLabelValue": return v.ProjectV2ItemFieldLabelValue.Field.ID() case "ProjectV2ItemFieldPullRequestValue": return v.ProjectV2ItemFieldPullRequestValue.Field.ID() case "ProjectV2ItemFieldRepositoryValue": return v.ProjectV2ItemFieldRepositoryValue.Field.ID() case "ProjectV2ItemFieldUserValue": return v.ProjectV2ItemFieldUserValue.Field.ID() case "ProjectV2ItemFieldReviewerValue": return v.ProjectV2ItemFieldReviewerValue.Field.ID() } return "" } type DraftIssue struct { ID string Body string Title string } func (i DraftIssue) ExportData(_ []string) map[string]interface{} { v := map[string]interface{}{ "title": i.Title, "body": i.Body, "type": "DraftIssue", } // Emulate omitempty. if i.ID != "" { v["id"] = i.ID } return v } type PullRequest struct { Body string Title string Number int URL string Repository struct { NameWithOwner string } } func (pr PullRequest) ExportData(_ []string) map[string]interface{} { return map[string]interface{}{ "type": "PullRequest", "body": pr.Body, "title": pr.Title, "number": pr.Number, "repository": pr.Repository.NameWithOwner, "url": pr.URL, } } type Issue struct { Body string Title string Number int URL string Repository struct { NameWithOwner string } } func (i Issue) ExportData(_ []string) map[string]interface{} { return map[string]interface{}{ "type": "Issue", "body": i.Body, "title": i.Title, "number": i.Number, "repository": i.Repository.NameWithOwner, "url": i.URL, } } func (p ProjectItem) DetailedItem() exportable { switch p.Type() { case "DraftIssue": return DraftIssue{ ID: p.Content.DraftIssue.ID, Body: p.Body(), Title: p.Title(), } case "Issue": return Issue{ Body: p.Body(), Title: p.Title(), Number: p.Number(), Repository: struct{ NameWithOwner string }{ NameWithOwner: p.Repo(), }, URL: p.URL(), } case "PullRequest": return PullRequest{ Body: p.Body(), Title: p.Title(), Number: p.Number(), Repository: struct{ NameWithOwner string }{ NameWithOwner: p.Repo(), }, URL: p.URL(), } } return nil } // Type is the underlying type of the project item. func (p ProjectItem) Type() string { return p.Content.TypeName } // Title is the title of the project item. func (p ProjectItem) Title() string { switch p.Content.TypeName { case "Issue": return p.Content.Issue.Title case "PullRequest": return p.Content.PullRequest.Title case "DraftIssue": return p.Content.DraftIssue.Title } return "" } // Body is the body of the project item. func (p ProjectItem) Body() string { switch p.Content.TypeName { case "Issue": return p.Content.Issue.Body case "PullRequest": return p.Content.PullRequest.Body case "DraftIssue": return p.Content.DraftIssue.Body } return "" } // Number is the number of the project item. It is only valid for issues and pull requests. func (p ProjectItem) Number() int { switch p.Content.TypeName { case "Issue": return p.Content.Issue.Number case "PullRequest": return p.Content.PullRequest.Number } return 0 } // ID is the id of the ProjectItem. func (p ProjectItem) ID() string { return p.Id } // Repo is the repository of the project item. It is only valid for issues and pull requests. func (p ProjectItem) Repo() string { switch p.Content.TypeName { case "Issue": return p.Content.Issue.Repository.NameWithOwner case "PullRequest": return p.Content.PullRequest.Repository.NameWithOwner } return "" } // URL is the URL of the project item. Note the draft issues do not have URLs func (p ProjectItem) URL() string { switch p.Content.TypeName { case "Issue": return p.Content.Issue.URL case "PullRequest": return p.Content.PullRequest.URL } return "" } func (p ProjectItem) ExportData(_ []string) map[string]interface{} { v := map[string]interface{}{ "id": p.ID(), "title": p.Title(), "body": p.Body(), "type": p.Type(), } // Emulate omitempty. if url := p.URL(); url != "" { v["url"] = url } return v } // ProjectItems returns the items of a project. If the OwnerType is VIEWER, no login is required. // If limit is 0, the default limit is used. func (c *Client) ProjectItems(o *Owner, number int32, limit int) (*Project, error) { project := &Project{} if limit == 0 { limit = LimitDefault } // set first to the min of limit and LimitMax first := LimitMax if limit < first { first = limit } variables := map[string]interface{}{ "firstItems": githubv4.Int(first), "afterItems": (*githubv4.String)(nil), "firstFields": githubv4.Int(LimitMax), "afterFields": (*githubv4.String)(nil), "number": githubv4.Int(number), } var query pager[ProjectItem] var queryName string switch o.Type { case UserOwner: variables["login"] = githubv4.String(o.Login) query = &userOwnerWithItems{} // must be a pointer to work with graphql queries queryName = "UserProjectWithItems" case OrgOwner: variables["login"] = githubv4.String(o.Login) query = &orgOwnerWithItems{} // must be a pointer to work with graphql queries queryName = "OrgProjectWithItems" case ViewerOwner: query = &viewerOwnerWithItems{} // must be a pointer to work with graphql queries queryName = "ViewerProjectWithItems" } err := c.doQueryWithProgressIndicator(queryName, query, variables) if err != nil { return project, err } project = query.Project() items, err := paginateAttributes(c, query, variables, queryName, "firstItems", "afterItems", limit, query.Nodes()) if err != nil { return project, err } project.Items.Nodes = items return project, nil } // pager is an interface for paginating over the attributes of a Project. type pager[N projectAttribute] interface { HasNextPage() bool EndCursor() string Nodes() []N Project() *Project } // userOwnerWithItems func (q userOwnerWithItems) HasNextPage() bool { return q.Owner.Project.Items.PageInfo.HasNextPage } func (q userOwnerWithItems) EndCursor() string { return string(q.Owner.Project.Items.PageInfo.EndCursor) } func (q userOwnerWithItems) Nodes() []ProjectItem { return q.Owner.Project.Items.Nodes } func (q userOwnerWithItems) Project() *Project { return &q.Owner.Project } // orgOwnerWithItems func (q orgOwnerWithItems) HasNextPage() bool { return q.Owner.Project.Items.PageInfo.HasNextPage } func (q orgOwnerWithItems) EndCursor() string { return string(q.Owner.Project.Items.PageInfo.EndCursor) } func (q orgOwnerWithItems) Nodes() []ProjectItem { return q.Owner.Project.Items.Nodes } func (q orgOwnerWithItems) Project() *Project { return &q.Owner.Project } // viewerOwnerWithItems func (q viewerOwnerWithItems) HasNextPage() bool { return q.Owner.Project.Items.PageInfo.HasNextPage } func (q viewerOwnerWithItems) EndCursor() string { return string(q.Owner.Project.Items.PageInfo.EndCursor) } func (q viewerOwnerWithItems) Nodes() []ProjectItem { return q.Owner.Project.Items.Nodes } func (q viewerOwnerWithItems) Project() *Project { return &q.Owner.Project } // userOwnerWithFields func (q userOwnerWithFields) HasNextPage() bool { return q.Owner.Project.Fields.PageInfo.HasNextPage } func (q userOwnerWithFields) EndCursor() string { return string(q.Owner.Project.Fields.PageInfo.EndCursor) } func (q userOwnerWithFields) Nodes() []ProjectField { return q.Owner.Project.Fields.Nodes } func (q userOwnerWithFields) Project() *Project { return &q.Owner.Project } // orgOwnerWithFields func (q orgOwnerWithFields) HasNextPage() bool { return q.Owner.Project.Fields.PageInfo.HasNextPage } func (q orgOwnerWithFields) EndCursor() string { return string(q.Owner.Project.Fields.PageInfo.EndCursor) } func (q orgOwnerWithFields) Nodes() []ProjectField { return q.Owner.Project.Fields.Nodes } func (q orgOwnerWithFields) Project() *Project { return &q.Owner.Project } // viewerOwnerWithFields func (q viewerOwnerWithFields) HasNextPage() bool { return q.Owner.Project.Fields.PageInfo.HasNextPage } func (q viewerOwnerWithFields) EndCursor() string { return string(q.Owner.Project.Fields.PageInfo.EndCursor) } func (q viewerOwnerWithFields) Nodes() []ProjectField { return q.Owner.Project.Fields.Nodes } func (q viewerOwnerWithFields) Project() *Project { return &q.Owner.Project } type projectAttribute interface { ProjectItem | ProjectField } // paginateAttributes is for paginating over the attributes of a project, such as items or fields // // firstKey and afterKey are the keys in the variables map that are used to set the first and after // as these are set independently based on the attribute type, such as item or field. // // limit is the maximum number of attributes to return, or 0 for no limit. // // nodes is the list of attributes that have already been fetched. // // the return value is a slice of the newly fetched attributes appended to nodes. func paginateAttributes[N projectAttribute](c *Client, p pager[N], variables map[string]any, queryName string, firstKey string, afterKey string, limit int, nodes []N) ([]N, error) { hasNextPage := p.HasNextPage() cursor := p.EndCursor() for { if !hasNextPage || len(nodes) >= limit { return nodes, nil } if len(nodes)+LimitMax > limit { first := limit - len(nodes) variables[firstKey] = githubv4.Int(first) } // set the cursor to the end of the last page variables[afterKey] = (*githubv4.String)(&cursor) err := c.doQueryWithProgressIndicator(queryName, p, variables) if err != nil { return nodes, err } nodes = append(nodes, p.Nodes()...) hasNextPage = p.HasNextPage() cursor = p.EndCursor() } } // ProjectField is a ProjectV2FieldConfiguration GraphQL object https://docs.github.com/en/graphql/reference/unions#projectv2fieldconfiguration. type ProjectField struct { TypeName string `graphql:"__typename"` Field struct { ID string Name string DataType string } `graphql:"... on ProjectV2Field"` IterationField struct { ID string Name string DataType string } `graphql:"... on ProjectV2IterationField"` SingleSelectField struct { ID string Name string DataType string Options []SingleSelectFieldOptions } `graphql:"... on ProjectV2SingleSelectField"` } // ID is the ID of the project field. func (p ProjectField) ID() string { if p.TypeName == "ProjectV2Field" { return p.Field.ID } else if p.TypeName == "ProjectV2IterationField" { return p.IterationField.ID } else if p.TypeName == "ProjectV2SingleSelectField" { return p.SingleSelectField.ID } return "" } // Name is the name of the project field. func (p ProjectField) Name() string { if p.TypeName == "ProjectV2Field" { return p.Field.Name } else if p.TypeName == "ProjectV2IterationField" { return p.IterationField.Name } else if p.TypeName == "ProjectV2SingleSelectField" { return p.SingleSelectField.Name } return "" } // Type is the typename of the project field. func (p ProjectField) Type() string { return p.TypeName } type SingleSelectFieldOptions struct { ID string Name string } func (f SingleSelectFieldOptions) ExportData(_ []string) map[string]interface{} { return map[string]interface{}{ "id": f.ID, "name": f.Name, } } func (p ProjectField) Options() []SingleSelectFieldOptions { if p.TypeName == "ProjectV2SingleSelectField" { var options []SingleSelectFieldOptions for _, o := range p.SingleSelectField.Options { options = append(options, SingleSelectFieldOptions{ ID: o.ID, Name: o.Name, }) } return options } return nil } func (p ProjectField) ExportData(_ []string) map[string]interface{} { v := map[string]interface{}{ "id": p.ID(), "name": p.Name(), "type": p.Type(), } // Emulate omitempty if opts := p.Options(); len(opts) != 0 { options := make([]map[string]interface{}, len(opts)) for i, opt := range opts { options[i] = opt.ExportData(nil) } v["options"] = options } return v } type ProjectFields struct { TotalCount int Nodes []ProjectField PageInfo PageInfo } func (p ProjectFields) ExportData(_ []string) map[string]interface{} { fields := make([]map[string]interface{}, len(p.Nodes)) for i := range p.Nodes { fields[i] = p.Nodes[i].ExportData(nil) } return map[string]interface{}{ "fields": fields, "totalCount": p.TotalCount, } } // ProjectFields returns a project with fields. If the OwnerType is VIEWER, no login is required. // If limit is 0, the default limit is used. func (c *Client) ProjectFields(o *Owner, number int32, limit int) (*Project, error) { project := &Project{} if limit == 0 { limit = LimitDefault } // set first to the min of limit and LimitMax first := LimitMax if limit < first { first = limit } variables := map[string]interface{}{ "firstItems": githubv4.Int(LimitMax), "afterItems": (*githubv4.String)(nil), "firstFields": githubv4.Int(first), "afterFields": (*githubv4.String)(nil), "number": githubv4.Int(number), } var query pager[ProjectField] var queryName string switch o.Type { case UserOwner: variables["login"] = githubv4.String(o.Login) query = &userOwnerWithFields{} // must be a pointer to work with graphql queries queryName = "UserProjectWithFields" case OrgOwner: variables["login"] = githubv4.String(o.Login) query = &orgOwnerWithFields{} // must be a pointer to work with graphql queries queryName = "OrgProjectWithFields" case ViewerOwner: query = &viewerOwnerWithFields{} // must be a pointer to work with graphql queries queryName = "ViewerProjectWithFields" } err := c.doQueryWithProgressIndicator(queryName, query, variables) if err != nil { return project, err } project = query.Project() fields, err := paginateAttributes(c, query, variables, queryName, "firstFields", "afterFields", limit, query.Nodes()) if err != nil { return project, err } project.Fields.Nodes = fields return project, nil } // viewerLogin is used to query the Login of the viewer. type viewerLogin struct { Viewer struct { Login string Id string } } type viewerLoginOrgs struct { Viewer struct { Login string ID string Organizations struct { PageInfo PageInfo Nodes []struct { Login string ViewerCanCreateProjects bool ID string } } `graphql:"organizations(first: 100, after: $after)"` } } // userOwner is used to query the project of a user. type userOwner struct { Owner struct { Project Project `graphql:"projectV2(number: $number)"` Login string } `graphql:"user(login: $login)"` } // userOwnerWithItems is used to query the project of a user with its items. type userOwnerWithItems struct { Owner struct { Project Project `graphql:"projectV2(number: $number)"` } `graphql:"user(login: $login)"` } // userOwnerWithFields is used to query the project of a user with its fields. type userOwnerWithFields struct { Owner struct { Project Project `graphql:"projectV2(number: $number)"` } `graphql:"user(login: $login)"` } // orgOwner is used to query the project of an organization. type orgOwner struct { Owner struct { Project Project `graphql:"projectV2(number: $number)"` Login string } `graphql:"organization(login: $login)"` } // orgOwnerWithItems is used to query the project of an organization with its items. type orgOwnerWithItems struct { Owner struct { Project Project `graphql:"projectV2(number: $number)"` } `graphql:"organization(login: $login)"` } // orgOwnerWithFields is used to query the project of an organization with its fields. type orgOwnerWithFields struct { Owner struct { Project Project `graphql:"projectV2(number: $number)"` } `graphql:"organization(login: $login)"` } // viewerOwner is used to query the project of the viewer. type viewerOwner struct { Owner struct { Project Project `graphql:"projectV2(number: $number)"` Login string } `graphql:"viewer"` } // viewerOwnerWithItems is used to query the project of the viewer with its items. type viewerOwnerWithItems struct { Owner struct { Project Project `graphql:"projectV2(number: $number)"` } `graphql:"viewer"` } // viewerOwnerWithFields is used to query the project of the viewer with its fields. type viewerOwnerWithFields struct { Owner struct { Project Project `graphql:"projectV2(number: $number)"` } `graphql:"viewer"` } // OwnerType is the type of the owner of a project, which can be either a user or an organization. Viewer is the current user. type OwnerType string const UserOwner OwnerType = "USER" const OrgOwner OwnerType = "ORGANIZATION" const ViewerOwner OwnerType = "VIEWER" // ViewerLoginName returns the login name of the viewer. func (c *Client) ViewerLoginName() (string, error) { var query viewerLogin err := c.doQueryWithProgressIndicator("Viewer", &query, map[string]interface{}{}) if err != nil { return "", err } return query.Viewer.Login, nil } // OwnerIDAndType returns the ID and OwnerType. The special login "@me" or an empty string queries the current user. func (c *Client) OwnerIDAndType(login string) (string, OwnerType, error) { if login == "@me" || login == "" { var query viewerLogin err := c.doQueryWithProgressIndicator("ViewerOwner", &query, nil) if err != nil { return "", "", err } return query.Viewer.Id, ViewerOwner, nil } variables := map[string]interface{}{ "login": githubv4.String(login), } var query struct { User struct { Login string Id string } `graphql:"user(login: $login)"` Organization struct { Login string Id string } `graphql:"organization(login: $login)"` } err := c.doQueryWithProgressIndicator("UserOrgOwner", &query, variables) if err != nil { // Due to the way the queries are structured, we don't know if a login belongs to a user // or to an org, even though they are unique. To deal with this, we try both - if neither // is found, we return the error. var graphErr api.GraphQLError if errors.As(err, &graphErr) { if graphErr.Match("NOT_FOUND", "user") && graphErr.Match("NOT_FOUND", "organization") { return "", "", err } else if graphErr.Match("NOT_FOUND", "organization") { // org isn't found must be a user return query.User.Id, UserOwner, nil } else if graphErr.Match("NOT_FOUND", "user") { // user isn't found must be an org return query.Organization.Id, OrgOwner, nil } } } return "", "", errors.New("unknown owner type") } // issueOrPullRequest is used to query the global id of an issue or pull request by its URL. type issueOrPullRequest struct { Resource struct { Typename string `graphql:"__typename"` Issue struct { ID string } `graphql:"... on Issue"` PullRequest struct { ID string } `graphql:"... on PullRequest"` } `graphql:"resource(url: $url)"` } // IssueOrPullRequestID returns the ID of the issue or pull request from a URL. func (c *Client) IssueOrPullRequestID(rawURL string) (string, error) { uri, err := url.Parse(rawURL) if err != nil { return "", err } variables := map[string]interface{}{ "url": githubv4.URI{URL: uri}, } var query issueOrPullRequest err = c.doQueryWithProgressIndicator("GetIssueOrPullRequest", &query, variables) if err != nil { return "", err } if query.Resource.Typename == "Issue" { return query.Resource.Issue.ID, nil } else if query.Resource.Typename == "PullRequest" { return query.Resource.PullRequest.ID, nil } return "", errors.New("resource not found, please check the URL") } // userProjects queries the $first projects of a user. type userProjects struct { Owner struct { Projects struct { TotalCount int PageInfo PageInfo Nodes []Project } `graphql:"projectsV2(first: $first, after: $after)"` Login string } `graphql:"user(login: $login)"` } // orgProjects queries the $first projects of an organization. type orgProjects struct { Owner struct { Projects struct { TotalCount int PageInfo PageInfo Nodes []Project } `graphql:"projectsV2(first: $first, after: $after)"` Login string } `graphql:"organization(login: $login)"` } // viewerProjects queries the $first projects of the viewer. type viewerProjects struct { Owner struct { Projects struct { TotalCount int PageInfo PageInfo Nodes []Project } `graphql:"projectsV2(first: $first, after: $after)"` Login string } `graphql:"viewer"` } type loginTypes struct { Login string Type OwnerType ID string } // userOrgLogins gets all the logins of the viewer and the organizations the viewer is a member of. func (c *Client) userOrgLogins() ([]loginTypes, error) { l := make([]loginTypes, 0) var v viewerLoginOrgs variables := map[string]interface{}{ "after": (*githubv4.String)(nil), } err := c.doQueryWithProgressIndicator("ViewerLoginAndOrgs", &v, variables) if err != nil { return l, err } // add the user l = append(l, loginTypes{ Login: v.Viewer.Login, Type: ViewerOwner, ID: v.Viewer.ID, }) // add orgs where the user can create projects for _, org := range v.Viewer.Organizations.Nodes { if org.ViewerCanCreateProjects { l = append(l, loginTypes{ Login: org.Login, Type: OrgOwner, ID: org.ID, }) } } // this seem unlikely, but if there are more org logins, paginate the rest if v.Viewer.Organizations.PageInfo.HasNextPage { return c.paginateOrgLogins(l, string(v.Viewer.Organizations.PageInfo.EndCursor)) } return l, nil } // paginateOrgLogins after cursor and append them to the list of logins. func (c *Client) paginateOrgLogins(l []loginTypes, cursor string) ([]loginTypes, error) { var v viewerLoginOrgs variables := map[string]interface{}{ "after": githubv4.String(cursor), } err := c.doQueryWithProgressIndicator("ViewerLoginAndOrgs", &v, variables) if err != nil { return l, err } for _, org := range v.Viewer.Organizations.Nodes { if org.ViewerCanCreateProjects { l = append(l, loginTypes{ Login: org.Login, Type: OrgOwner, ID: org.ID, }) } } if v.Viewer.Organizations.PageInfo.HasNextPage { return c.paginateOrgLogins(l, string(v.Viewer.Organizations.PageInfo.EndCursor)) } return l, nil } type Owner struct { Login string Type OwnerType ID string } // NewOwner creates a project Owner // If canPrompt is false, login is required as we cannot prompt for it. // If login is not empty, it is used to lookup the project owner. // If login is empty, interactive mode is used to select an owner. // from the current viewer and their organizations func (c *Client) NewOwner(canPrompt bool, login string) (*Owner, error) { if login != "" { id, ownerType, err := c.OwnerIDAndType(login) if err != nil { return nil, err } return &Owner{ Login: login, Type: ownerType, ID: id, }, nil } if !canPrompt { return nil, fmt.Errorf("owner is required when not running interactively") } logins, err := c.userOrgLogins() if err != nil { return nil, err } options := make([]string, 0, len(logins)) for _, l := range logins { options = append(options, l.Login) } answerIndex, err := c.prompter.Select("Which owner would you like to use?", "", options)
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
true
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/shared/client/client.go
pkg/cmd/project/shared/client/client.go
package client import ( "os" "github.com/cli/cli/v2/pkg/cmd/project/shared/queries" "github.com/cli/cli/v2/pkg/cmdutil" ) func New(f *cmdutil.Factory) (*queries.Client, error) { if f.HttpClient == nil { // This is for compatibility with tests that exercise Cobra command functionality. // These tests do not define a `HttpClient` nor do they need to. return nil, nil } httpClient, err := f.HttpClient() if err != nil { return nil, err } return queries.NewClient(httpClient, os.Getenv("GH_HOST"), f.IOStreams), nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/shared/format/display_test.go
pkg/cmd/project/shared/format/display_test.go
package format import ( "testing" "github.com/cli/cli/v2/pkg/cmd/project/shared/queries" "github.com/stretchr/testify/assert" ) func TestProjectState(t *testing.T) { assert.Equal(t, "open", ProjectState(queries.Project{})) assert.Equal(t, "closed", ProjectState(queries.Project{Closed: true})) } func TestColorForProjectState(t *testing.T) { assert.Equal(t, "green", ColorForProjectState(queries.Project{})) assert.Equal(t, "gray", ColorForProjectState(queries.Project{Closed: true})) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/project/shared/format/display.go
pkg/cmd/project/shared/format/display.go
package format import ( "github.com/cli/cli/v2/pkg/cmd/project/shared/queries" ) func ProjectState(project queries.Project) string { if project.Closed { return "closed" } return "open" } func ColorForProjectState(project queries.Project) string { if project.Closed { return "gray" } return "green" }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/api/api.go
pkg/cmd/api/api.go
package api import ( "bytes" "encoding/json" "errors" "fmt" "io" "net/http" "os" "path/filepath" "regexp" "runtime" "sort" "strings" "time" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghinstance" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/factory" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/pkg/jsoncolor" "github.com/cli/go-gh/v2/pkg/jq" "github.com/cli/go-gh/v2/pkg/template" "github.com/spf13/cobra" ) const ( ttyIndent = " " ) type ApiOptions struct { AppVersion string BaseRepo func() (ghrepo.Interface, error) Branch func() (string, error) Config func() (gh.Config, error) HttpClient func() (*http.Client, error) IO *iostreams.IOStreams Hostname string RequestMethod string RequestMethodPassed bool RequestPath string RequestInputFile string MagicFields []string RawFields []string RequestHeaders []string Previews []string ShowResponseHeaders bool Paginate bool Slurp bool Silent bool Template string CacheTTL time.Duration FilterOutput string Verbose bool } func NewCmdApi(f *cmdutil.Factory, runF func(*ApiOptions) error) *cobra.Command { opts := ApiOptions{ AppVersion: f.AppVersion, BaseRepo: f.BaseRepo, Branch: f.Branch, Config: f.Config, IO: f.IOStreams, } cmd := &cobra.Command{ Use: "api <endpoint>", Short: "Make an authenticated GitHub API request", Long: heredoc.Docf(` Makes an authenticated HTTP request to the GitHub API and prints the response. The endpoint argument should either be a path of a GitHub API v3 endpoint, or %[1]sgraphql%[1]s to access the GitHub API v4. Placeholder values %[1]s{owner}%[1]s, %[1]s{repo}%[1]s, and %[1]s{branch}%[1]s in the endpoint argument will get replaced with values from the repository of the current directory or the repository specified in the %[1]sGH_REPO%[1]s environment variable. Note that in some shells, for example PowerShell, you may need to enclose any value that contains %[1]s{...}%[1]s in quotes to prevent the shell from applying special meaning to curly braces. The %[1]s-p/--preview%[1]s flag enables opting into previews, which are feature-flagged, experimental API endpoints or behaviors. The API expects opt-in via the %[1]sAccept%[1]s header with format %[1]sapplication/vnd.github.<preview-name>-preview+json%[1]s and this command facilitates that via %[1]s--preview <preview-name>%[1]s. To send a request for the corsair and scarlet witch previews, you could use %[1]s-p corsair,scarlet-witch%[1]s or %[1]s--preview corsair --preview scarlet-witch%[1]s. The default HTTP request method is %[1]sGET%[1]s normally and %[1]sPOST%[1]s if any parameters were added. Override the method with %[1]s--method%[1]s. Pass one or more %[1]s-f/--raw-field%[1]s values in %[1]skey=value%[1]s format to add static string parameters to the request payload. To add non-string or placeholder-determined values, see %[1]s-F/--field%[1]s below. Note that adding request parameters will automatically switch the request method to %[1]sPOST%[1]s. To send the parameters as a %[1]sGET%[1]s query string instead, use %[1]s--method GET%[1]s. The %[1]s-F/--field%[1]s flag has magic type conversion based on the format of the value: - literal values %[1]strue%[1]s, %[1]sfalse%[1]s, %[1]snull%[1]s, and integer numbers get converted to appropriate JSON types; - placeholder values %[1]s{owner}%[1]s, %[1]s{repo}%[1]s, and %[1]s{branch}%[1]s get populated with values from the repository of the current directory; - if the value starts with %[1]s@%[1]s, the rest of the value is interpreted as a filename to read the value from. Pass %[1]s-%[1]s to read from standard input. For GraphQL requests, all fields other than %[1]squery%[1]s and %[1]soperationName%[1]s are interpreted as GraphQL variables. To pass nested parameters in the request payload, use %[1]skey[subkey]=value%[1]s syntax when declaring fields. To pass nested values as arrays, declare multiple fields with the syntax %[1]skey[]=value1%[1]s, %[1]skey[]=value2%[1]s. To pass an empty array, use %[1]skey[]%[1]s without a value. To pass pre-constructed JSON or payloads in other formats, a request body may be read from file specified by %[1]s--input%[1]s. Use %[1]s-%[1]s to read from standard input. When passing the request body this way, any parameters specified via field flags are added to the query string of the endpoint URL. In %[1]s--paginate%[1]s mode, all pages of results will sequentially be requested until there are no more pages of results. For GraphQL requests, this requires that the original query accepts an %[1]s$endCursor: String%[1]s variable and that it fetches the %[1]spageInfo{ hasNextPage, endCursor }%[1]s set of fields from a collection. Each page is a separate JSON array or object. Pass %[1]s--slurp%[1]s to wrap all pages of JSON arrays or objects into an outer JSON array. `, "`"), Example: heredoc.Doc(` # List releases in the current repository $ gh api repos/{owner}/{repo}/releases # Post an issue comment $ gh api repos/{owner}/{repo}/issues/123/comments -f body='Hi from CLI' # Post nested parameter read from a file $ gh api gists -F 'files[myfile.txt][content]=@myfile.txt' # Add parameters to a GET request $ gh api -X GET search/issues -f q='repo:cli/cli is:open remote' # Use a JSON file as request body $ gh api repos/{owner}/{repo}/rulesets --input file.json # Set a custom HTTP header $ gh api -H 'Accept: application/vnd.github.v3.raw+json' ... # Opt into GitHub API previews $ gh api --preview baptiste,nebula ... # Print only specific fields from the response $ gh api repos/{owner}/{repo}/issues --jq '.[].title' # Use a template for the output $ gh api repos/{owner}/{repo}/issues --template \ '{{range .}}{{.title}} ({{.labels | pluck "name" | join ", " | color "yellow"}}){{"\n"}}{{end}}' # Update allowed values of the "environment" custom property in a deeply nested array $ gh api -X PATCH /orgs/{org}/properties/schema \ -F 'properties[][property_name]=environment' \ -F 'properties[][default_value]=production' \ -F 'properties[][allowed_values][]=staging' \ -F 'properties[][allowed_values][]=production' # List releases with GraphQL $ gh api graphql -F owner='{owner}' -F name='{repo}' -f query=' query($name: String!, $owner: String!) { repository(owner: $owner, name: $name) { releases(last: 3) { nodes { tagName } } } } ' # List all repositories for a user $ gh api graphql --paginate -f query=' query($endCursor: String) { viewer { repositories(first: 100, after: $endCursor) { nodes { nameWithOwner } pageInfo { hasNextPage endCursor } } } } ' # Get the percentage of forks for the current user $ gh api graphql --paginate --slurp -f query=' query($endCursor: String) { viewer { repositories(first: 100, after: $endCursor) { nodes { isFork } pageInfo { hasNextPage endCursor } } } } ' | jq 'def count(e): reduce e as $_ (0;.+1); [.[].data.viewer.repositories.nodes[]] as $r | count(select($r[].isFork))/count($r[])' `), Annotations: map[string]string{ "help:environment": heredoc.Docf(` GH_TOKEN, GITHUB_TOKEN (in order of precedence): an authentication token for %[1]sgithub.com%[1]s API requests. GH_ENTERPRISE_TOKEN, GITHUB_ENTERPRISE_TOKEN (in order of precedence): an authentication token for API requests to GitHub Enterprise. GH_HOST: make the request to a GitHub host other than %[1]sgithub.com%[1]s. `, "`"), }, Args: cobra.ExactArgs(1), PreRun: func(c *cobra.Command, args []string) { opts.BaseRepo = cmdutil.OverrideBaseRepoFunc(f, "") }, RunE: func(c *cobra.Command, args []string) error { opts.RequestPath = args[0] opts.RequestMethodPassed = c.Flags().Changed("method") if runtime.GOOS == "windows" && filepath.IsAbs(opts.RequestPath) { return fmt.Errorf(`invalid API endpoint: "%s". Your shell might be rewriting URL paths as filesystem paths. To avoid this, omit the leading slash from the endpoint argument`, opts.RequestPath) } if c.Flags().Changed("hostname") { if err := ghinstance.HostnameValidator(opts.Hostname); err != nil { return cmdutil.FlagErrorf("error parsing `--hostname`: %w", err) } } if opts.Paginate && !strings.EqualFold(opts.RequestMethod, "GET") && opts.RequestPath != "graphql" { return cmdutil.FlagErrorf("the `--paginate` option is not supported for non-GET requests") } if err := cmdutil.MutuallyExclusive( "the `--paginate` option is not supported with `--input`", opts.Paginate, opts.RequestInputFile != "", ); err != nil { return err } if opts.Slurp { if err := cmdutil.MutuallyExclusive( "the `--slurp` option is not supported with `--jq` or `--template`", opts.Slurp, opts.FilterOutput != "", opts.Template != "", ); err != nil { return err } if !opts.Paginate { return cmdutil.FlagErrorf("`--paginate` required when passing `--slurp`") } } if err := cmdutil.MutuallyExclusive( "only one of `--template`, `--jq`, `--silent`, or `--verbose` may be used", opts.Verbose, opts.Silent, opts.FilterOutput != "", opts.Template != "", ); err != nil { return err } if runF != nil { return runF(&opts) } return apiRun(&opts) }, } cmd.Flags().StringVar(&opts.Hostname, "hostname", "", "The GitHub hostname for the request (default \"github.com\")") cmd.Flags().StringVarP(&opts.RequestMethod, "method", "X", "GET", "The HTTP method for the request") cmd.Flags().StringArrayVarP(&opts.MagicFields, "field", "F", nil, "Add a typed parameter in `key=value` format (use \"@<path>\" or \"@-\" to read value from file or stdin)") cmd.Flags().StringArrayVarP(&opts.RawFields, "raw-field", "f", nil, "Add a string parameter in `key=value` format") cmd.Flags().StringArrayVarP(&opts.RequestHeaders, "header", "H", nil, "Add a HTTP request header in `key:value` format") cmd.Flags().StringSliceVarP(&opts.Previews, "preview", "p", nil, "Opt into GitHub API previews (names should omit '-preview')") cmd.Flags().BoolVarP(&opts.ShowResponseHeaders, "include", "i", false, "Include HTTP response status line and headers in the output") cmd.Flags().BoolVar(&opts.Slurp, "slurp", false, "Use with \"--paginate\" to return an array of all pages of either JSON arrays or objects") cmd.Flags().BoolVar(&opts.Paginate, "paginate", false, "Make additional HTTP requests to fetch all pages of results") cmd.Flags().StringVar(&opts.RequestInputFile, "input", "", "The `file` to use as body for the HTTP request (use \"-\" to read from standard input)") cmd.Flags().BoolVar(&opts.Silent, "silent", false, "Do not print the response body") cmd.Flags().StringVarP(&opts.Template, "template", "t", "", "Format JSON output using a Go template; see \"gh help formatting\"") cmd.Flags().StringVarP(&opts.FilterOutput, "jq", "q", "", "Query to select values from the response using jq syntax") cmd.Flags().DurationVar(&opts.CacheTTL, "cache", 0, "Cache the response, e.g. \"3600s\", \"60m\", \"1h\"") cmd.Flags().BoolVar(&opts.Verbose, "verbose", false, "Include full HTTP request and response in the output") return cmd } func apiRun(opts *ApiOptions) error { params, err := parseFields(opts) if err != nil { return err } isGraphQL := opts.RequestPath == "graphql" requestPath, err := fillPlaceholders(opts.RequestPath, opts) if err != nil { return fmt.Errorf("unable to expand placeholder in path: %w", err) } method := opts.RequestMethod requestHeaders := opts.RequestHeaders var requestBody interface{} if len(params) > 0 { requestBody = params } if !opts.RequestMethodPassed && (len(params) > 0 || opts.RequestInputFile != "") { method = "POST" } if !opts.Silent { if err := opts.IO.StartPager(); err == nil { defer opts.IO.StopPager() } else { fmt.Fprintf(opts.IO.ErrOut, "failed to start pager: %v\n", err) } } var bodyWriter io.Writer = opts.IO.Out var headersWriter io.Writer = opts.IO.Out if opts.Silent { bodyWriter = io.Discard } if opts.Verbose { // httpClient handles output when verbose flag is specified. bodyWriter = io.Discard headersWriter = io.Discard } if opts.Paginate && !isGraphQL { requestPath = addPerPage(requestPath, 100, params) } // Similar to `jq --slurp`, write all pages JSON arrays or objects into a JSON array. if opts.Paginate && opts.Slurp { w := &jsonArrayWriter{ Writer: bodyWriter, color: opts.IO.ColorEnabled(), } defer w.Close() bodyWriter = w } if opts.RequestInputFile != "" { file, size, err := openUserFile(opts.RequestInputFile, opts.IO.In) if err != nil { return err } defer file.Close() requestPath = addQuery(requestPath, params) requestBody = file if size >= 0 { requestHeaders = append([]string{fmt.Sprintf("Content-Length: %d", size)}, requestHeaders...) } } if len(opts.Previews) > 0 { requestHeaders = append(requestHeaders, "Accept: "+previewNamesToMIMETypes(opts.Previews)) } cfg, err := opts.Config() if err != nil { return err } if opts.HttpClient == nil { opts.HttpClient = func() (*http.Client, error) { log := opts.IO.ErrOut if opts.Verbose { log = opts.IO.Out } opts := api.HTTPClientOptions{ AppVersion: opts.AppVersion, CacheTTL: opts.CacheTTL, Config: cfg.Authentication(), EnableCache: opts.CacheTTL > 0, Log: log, LogColorize: opts.IO.ColorEnabled(), LogVerboseHTTP: opts.Verbose, } return api.NewHTTPClient(opts) } } httpClient, err := opts.HttpClient() if err != nil { return err } host, _ := cfg.Authentication().DefaultHost() if opts.Hostname != "" { host = opts.Hostname } tmpl := template.New(bodyWriter, opts.IO.TerminalWidth(), opts.IO.ColorEnabled()) err = tmpl.Parse(opts.Template) if err != nil { return err } isFirstPage := true hasNextPage := true for hasNextPage { resp, err := httpRequest(httpClient, host, method, requestPath, requestBody, requestHeaders) if err != nil { return err } if !isGraphQL { requestPath, hasNextPage = findNextPage(resp) requestBody = nil // prevent repeating GET parameters } // Tell optional jsonArrayWriter to start a new page. err = startPage(bodyWriter) if err != nil { return err } endCursor, err := processResponse(resp, opts, bodyWriter, headersWriter, tmpl, isFirstPage, !hasNextPage) if err != nil { return err } isFirstPage = false if !opts.Paginate { break } if isGraphQL { hasNextPage = endCursor != "" if hasNextPage { params["endCursor"] = endCursor } } if hasNextPage && opts.ShowResponseHeaders { fmt.Fprint(opts.IO.Out, "\n") } } return tmpl.Flush() } func processResponse(resp *http.Response, opts *ApiOptions, bodyWriter, headersWriter io.Writer, template *template.Template, isFirstPage, isLastPage bool) (endCursor string, err error) { if opts.ShowResponseHeaders { fmt.Fprintln(headersWriter, resp.Proto, resp.Status) printHeaders(headersWriter, resp.Header, opts.IO.ColorEnabled()) fmt.Fprint(headersWriter, "\r\n") } if resp.StatusCode == 204 { return } var responseBody io.Reader = resp.Body defer resp.Body.Close() isJSON, _ := regexp.MatchString(`[/+]json(;|$)`, resp.Header.Get("Content-Type")) var serverError string if isJSON && (opts.RequestPath == "graphql" || resp.StatusCode >= 400) { if !strings.EqualFold(opts.RequestMethod, "HEAD") { responseBody, serverError, err = parseErrorResponse(responseBody, resp.StatusCode) if err != nil { return } } } var bodyCopy *bytes.Buffer isGraphQLPaginate := isJSON && resp.StatusCode == 200 && opts.Paginate && opts.RequestPath == "graphql" if isGraphQLPaginate { bodyCopy = &bytes.Buffer{} responseBody = io.TeeReader(responseBody, bodyCopy) } if opts.FilterOutput != "" && serverError == "" { // TODO: reuse parsed query across pagination invocations indent := "" if opts.IO.IsStdoutTTY() { indent = ttyIndent } err = jq.EvaluateFormatted(responseBody, bodyWriter, opts.FilterOutput, indent, opts.IO.ColorEnabled()) if err != nil { return } } else if opts.Template != "" && serverError == "" { err = template.Execute(responseBody) if err != nil { return } } else if isJSON && opts.IO.ColorEnabled() { err = jsoncolor.Write(bodyWriter, responseBody, ttyIndent) } else { if isJSON && opts.Paginate && !opts.Slurp && !isGraphQLPaginate && !opts.ShowResponseHeaders { responseBody = &paginatedArrayReader{ Reader: responseBody, isFirstPage: isFirstPage, isLastPage: isLastPage, } } _, err = io.Copy(bodyWriter, responseBody) } if err != nil { return } if serverError == "" && resp.StatusCode > 299 { serverError = fmt.Sprintf("HTTP %d", resp.StatusCode) } if serverError != "" { fmt.Fprintf(opts.IO.ErrOut, "gh: %s\n", serverError) if msg := api.ScopesSuggestion(resp); msg != "" { fmt.Fprintf(opts.IO.ErrOut, "gh: %s\n", msg) } if u := factory.SSOURL(); u != "" { fmt.Fprintf(opts.IO.ErrOut, "Authorize in your web browser: %s\n", u) } err = cmdutil.SilentError return } if isGraphQLPaginate { endCursor = findEndCursor(bodyCopy) } return } var placeholderRE = regexp.MustCompile(`(\:(owner|repo|branch)\b|\{[a-z]+\})`) // fillPlaceholders replaces placeholders with values from the current repository func fillPlaceholders(value string, opts *ApiOptions) (string, error) { var err error return placeholderRE.ReplaceAllStringFunc(value, func(m string) string { var name string if m[0] == ':' { name = m[1:] } else { name = m[1 : len(m)-1] } switch name { case "owner": if baseRepo, e := opts.BaseRepo(); e == nil { return baseRepo.RepoOwner() } else { err = e } case "repo": if baseRepo, e := opts.BaseRepo(); e == nil { return baseRepo.RepoName() } else { err = e } case "branch": if os.Getenv("GH_REPO") != "" { err = errors.New("unable to determine an appropriate value for the 'branch' placeholder") return m } if branch, e := opts.Branch(); e == nil { return branch } else { err = e } } return m }), err } func printHeaders(w io.Writer, headers http.Header, colorize bool) { var names []string for name := range headers { if name == "Status" { continue } names = append(names, name) } sort.Strings(names) var headerColor, headerColorReset string if colorize { headerColor = "\x1b[1;34m" // bright blue headerColorReset = "\x1b[m" } for _, name := range names { fmt.Fprintf(w, "%s%s%s: %s\r\n", headerColor, name, headerColorReset, strings.Join(headers[name], ", ")) } } func openUserFile(fn string, stdin io.ReadCloser) (io.ReadCloser, int64, error) { if fn == "-" { return stdin, -1, nil } r, err := os.Open(fn) if err != nil { return r, -1, err } s, err := os.Stat(fn) if err != nil { return r, -1, err } return r, s.Size(), nil } func parseErrorResponse(r io.Reader, statusCode int) (io.Reader, string, error) { bodyCopy := &bytes.Buffer{} b, err := io.ReadAll(io.TeeReader(r, bodyCopy)) if err != nil { return r, "", err } var parsedBody struct { Message string Errors json.RawMessage } err = json.Unmarshal(b, &parsedBody) if err != nil { return bodyCopy, "", err } if len(parsedBody.Errors) > 0 && parsedBody.Errors[0] == '"' { var stringError string if err := json.Unmarshal(parsedBody.Errors, &stringError); err != nil { return bodyCopy, "", err } if stringError != "" { if parsedBody.Message != "" { return bodyCopy, fmt.Sprintf("%s (%s)", stringError, parsedBody.Message), nil } return bodyCopy, stringError, nil } } if parsedBody.Message != "" { return bodyCopy, fmt.Sprintf("%s (HTTP %d)", parsedBody.Message, statusCode), nil } if len(parsedBody.Errors) == 0 || parsedBody.Errors[0] != '[' { return bodyCopy, "", nil } var errorObjects []json.RawMessage if err := json.Unmarshal(parsedBody.Errors, &errorObjects); err != nil { return bodyCopy, "", err } var objectError struct { Message string } var errors []string for _, rawErr := range errorObjects { if len(rawErr) == 0 { continue } if rawErr[0] == '{' { err := json.Unmarshal(rawErr, &objectError) if err != nil { return bodyCopy, "", err } errors = append(errors, objectError.Message) } else if rawErr[0] == '"' { var stringError string err := json.Unmarshal(rawErr, &stringError) if err != nil { return bodyCopy, "", err } errors = append(errors, stringError) } } if len(errors) > 0 { return bodyCopy, strings.Join(errors, "\n"), nil } return bodyCopy, "", nil } func previewNamesToMIMETypes(names []string) string { types := []string{fmt.Sprintf("application/vnd.github.%s-preview+json", names[0])} for _, p := range names[1:] { types = append(types, fmt.Sprintf("application/vnd.github.%s-preview", p)) } return strings.Join(types, ", ") }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/api/api_test.go
pkg/cmd/api/api_test.go
package api import ( "bytes" "encoding/json" "fmt" "io" "net/http" "net/http/httptest" "os" "runtime" "strings" "testing" "time" "github.com/MakeNowJust/heredoc" "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/ghrepo" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/go-gh/v2/pkg/template" "github.com/google/shlex" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func Test_NewCmdApi(t *testing.T) { f := &cmdutil.Factory{} tests := []struct { name string cli string wants ApiOptions wantsErr bool }{ { name: "no flags", cli: "graphql", wants: ApiOptions{ Hostname: "", RequestMethod: "GET", RequestMethodPassed: false, RequestPath: "graphql", RequestInputFile: "", RawFields: []string(nil), MagicFields: []string(nil), RequestHeaders: []string(nil), ShowResponseHeaders: false, Paginate: false, Silent: false, CacheTTL: 0, Template: "", FilterOutput: "", Verbose: false, }, wantsErr: false, }, { name: "override method", cli: "repos/octocat/Spoon-Knife -XDELETE", wants: ApiOptions{ Hostname: "", RequestMethod: "DELETE", RequestMethodPassed: true, RequestPath: "repos/octocat/Spoon-Knife", RequestInputFile: "", RawFields: []string(nil), MagicFields: []string(nil), RequestHeaders: []string(nil), ShowResponseHeaders: false, Paginate: false, Silent: false, CacheTTL: 0, Template: "", FilterOutput: "", Verbose: false, }, wantsErr: false, }, { name: "with fields", cli: "graphql -f query=QUERY -F body=@file.txt", wants: ApiOptions{ Hostname: "", RequestMethod: "GET", RequestMethodPassed: false, RequestPath: "graphql", RequestInputFile: "", RawFields: []string{"query=QUERY"}, MagicFields: []string{"body=@file.txt"}, RequestHeaders: []string(nil), ShowResponseHeaders: false, Paginate: false, Silent: false, CacheTTL: 0, Template: "", FilterOutput: "", Verbose: false, }, wantsErr: false, }, { name: "with headers", cli: "user -H 'accept: text/plain' -i", wants: ApiOptions{ Hostname: "", RequestMethod: "GET", RequestMethodPassed: false, RequestPath: "user", RequestInputFile: "", RawFields: []string(nil), MagicFields: []string(nil), RequestHeaders: []string{"accept: text/plain"}, ShowResponseHeaders: true, Paginate: false, Silent: false, CacheTTL: 0, Template: "", FilterOutput: "", Verbose: false, }, wantsErr: false, }, { name: "with pagination", cli: "repos/OWNER/REPO/issues --paginate", wants: ApiOptions{ Hostname: "", RequestMethod: "GET", RequestMethodPassed: false, RequestPath: "repos/OWNER/REPO/issues", RequestInputFile: "", RawFields: []string(nil), MagicFields: []string(nil), RequestHeaders: []string(nil), ShowResponseHeaders: false, Paginate: true, Silent: false, CacheTTL: 0, Template: "", FilterOutput: "", Verbose: false, }, wantsErr: false, }, { name: "with silenced output", cli: "repos/OWNER/REPO/issues --silent", wants: ApiOptions{ Hostname: "", RequestMethod: "GET", RequestMethodPassed: false, RequestPath: "repos/OWNER/REPO/issues", RequestInputFile: "", RawFields: []string(nil), MagicFields: []string(nil), RequestHeaders: []string(nil), ShowResponseHeaders: false, Paginate: false, Silent: true, CacheTTL: 0, Template: "", FilterOutput: "", Verbose: false, }, wantsErr: false, }, { name: "POST pagination", cli: "-XPOST repos/OWNER/REPO/issues --paginate", wantsErr: true, }, { name: "GraphQL pagination", cli: "-XPOST graphql --paginate", wants: ApiOptions{ Hostname: "", RequestMethod: "POST", RequestMethodPassed: true, RequestPath: "graphql", RequestInputFile: "", RawFields: []string(nil), MagicFields: []string(nil), RequestHeaders: []string(nil), ShowResponseHeaders: false, Paginate: true, Silent: false, CacheTTL: 0, Template: "", FilterOutput: "", Verbose: false, }, wantsErr: false, }, { name: "input pagination", cli: "--input repos/OWNER/REPO/issues --paginate", wantsErr: true, }, { name: "with request body from file", cli: "user --input myfile", wants: ApiOptions{ Hostname: "", RequestMethod: "GET", RequestMethodPassed: false, RequestPath: "user", RequestInputFile: "myfile", RawFields: []string(nil), MagicFields: []string(nil), RequestHeaders: []string(nil), ShowResponseHeaders: false, Paginate: false, Silent: false, CacheTTL: 0, Template: "", FilterOutput: "", Verbose: false, }, wantsErr: false, }, { name: "no arguments", cli: "", wantsErr: true, }, { name: "with hostname", cli: "graphql --hostname tom.petty", wants: ApiOptions{ Hostname: "tom.petty", RequestMethod: "GET", RequestMethodPassed: false, RequestPath: "graphql", RequestInputFile: "", RawFields: []string(nil), MagicFields: []string(nil), RequestHeaders: []string(nil), ShowResponseHeaders: false, Paginate: false, Silent: false, CacheTTL: 0, Template: "", FilterOutput: "", Verbose: false, }, wantsErr: false, }, { name: "with cache", cli: "user --cache 5m", wants: ApiOptions{ Hostname: "", RequestMethod: "GET", RequestMethodPassed: false, RequestPath: "user", RequestInputFile: "", RawFields: []string(nil), MagicFields: []string(nil), RequestHeaders: []string(nil), ShowResponseHeaders: false, Paginate: false, Silent: false, CacheTTL: time.Minute * 5, Template: "", FilterOutput: "", Verbose: false, }, wantsErr: false, }, { name: "with template", cli: "user -t 'hello {{.name}}'", wants: ApiOptions{ Hostname: "", RequestMethod: "GET", RequestMethodPassed: false, RequestPath: "user", RequestInputFile: "", RawFields: []string(nil), MagicFields: []string(nil), RequestHeaders: []string(nil), ShowResponseHeaders: false, Paginate: false, Silent: false, CacheTTL: 0, Template: "hello {{.name}}", FilterOutput: "", Verbose: false, }, wantsErr: false, }, { name: "with jq filter", cli: "user -q .name", wants: ApiOptions{ Hostname: "", RequestMethod: "GET", RequestMethodPassed: false, RequestPath: "user", RequestInputFile: "", RawFields: []string(nil), MagicFields: []string(nil), RequestHeaders: []string(nil), ShowResponseHeaders: false, Paginate: false, Silent: false, CacheTTL: 0, Template: "", FilterOutput: ".name", Verbose: false, }, wantsErr: false, }, { name: "--silent with --jq", cli: "user --silent -q .foo", wantsErr: true, }, { name: "--silent with --template", cli: "user --silent -t '{{.foo}}'", wantsErr: true, }, { name: "--jq with --template", cli: "user --jq .foo -t '{{.foo}}'", wantsErr: true, }, { name: "--slurp without --paginate", cli: "user --slurp", wantsErr: true, }, { name: "slurp with --jq", cli: "user --paginate --slurp --jq .foo", wantsErr: true, }, { name: "slurp with --template", cli: "user --paginate --slurp --template '{{.foo}}'", wantsErr: true, }, { name: "with verbose", cli: "user --verbose", wants: ApiOptions{ Hostname: "", RequestMethod: "GET", RequestMethodPassed: false, RequestPath: "user", RequestInputFile: "", RawFields: []string(nil), MagicFields: []string(nil), RequestHeaders: []string(nil), ShowResponseHeaders: false, Paginate: false, Silent: false, CacheTTL: 0, Template: "", FilterOutput: "", Verbose: true, }, wantsErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { var opts *ApiOptions cmd := NewCmdApi(f, func(o *ApiOptions) error { opts = o return nil }) argv, err := shlex.Split(tt.cli) assert.NoError(t, err) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) return } assert.NoError(t, err) assert.Equal(t, tt.wants.Hostname, opts.Hostname) assert.Equal(t, tt.wants.RequestMethod, opts.RequestMethod) assert.Equal(t, tt.wants.RequestMethodPassed, opts.RequestMethodPassed) assert.Equal(t, tt.wants.RequestPath, opts.RequestPath) assert.Equal(t, tt.wants.RequestInputFile, opts.RequestInputFile) assert.Equal(t, tt.wants.RawFields, opts.RawFields) assert.Equal(t, tt.wants.MagicFields, opts.MagicFields) assert.Equal(t, tt.wants.RequestHeaders, opts.RequestHeaders) assert.Equal(t, tt.wants.ShowResponseHeaders, opts.ShowResponseHeaders) assert.Equal(t, tt.wants.Paginate, opts.Paginate) assert.Equal(t, tt.wants.Silent, opts.Silent) assert.Equal(t, tt.wants.CacheTTL, opts.CacheTTL) assert.Equal(t, tt.wants.Template, opts.Template) assert.Equal(t, tt.wants.FilterOutput, opts.FilterOutput) assert.Equal(t, tt.wants.Verbose, opts.Verbose) }) } } func Test_NewCmdApi_WindowsAbsPath(t *testing.T) { if runtime.GOOS != "windows" { t.SkipNow() } cmd := NewCmdApi(&cmdutil.Factory{}, func(opts *ApiOptions) error { return nil }) cmd.SetArgs([]string{`C:\users\repos`}) _, err := cmd.ExecuteC() assert.EqualError(t, err, `invalid API endpoint: "C:\users\repos". Your shell might be rewriting URL paths as filesystem paths. To avoid this, omit the leading slash from the endpoint argument`) } func Test_apiRun(t *testing.T) { tests := []struct { name string options ApiOptions httpResponse *http.Response err error stdout string stderr string isatty bool }{ { name: "success", httpResponse: &http.Response{ StatusCode: 200, Body: io.NopCloser(bytes.NewBufferString(`bam!`)), }, err: nil, stdout: `bam!`, stderr: ``, isatty: false, }, { name: "show response headers", options: ApiOptions{ ShowResponseHeaders: true, }, httpResponse: &http.Response{ Proto: "HTTP/1.1", Status: "200 Okey-dokey", StatusCode: 200, Body: io.NopCloser(bytes.NewBufferString(`body`)), Header: http.Header{"Content-Type": []string{"text/plain"}}, }, err: nil, stdout: "HTTP/1.1 200 Okey-dokey\nContent-Type: text/plain\r\n\r\nbody", stderr: ``, isatty: false, }, { name: "success 204", httpResponse: &http.Response{ StatusCode: 204, Body: nil, }, err: nil, stdout: ``, stderr: ``, isatty: false, }, { name: "REST error", httpResponse: &http.Response{ StatusCode: 400, Body: io.NopCloser(bytes.NewBufferString(`{"message": "THIS IS FINE"}`)), Header: http.Header{"Content-Type": []string{"application/json; charset=utf-8"}}, }, err: cmdutil.SilentError, stdout: `{"message": "THIS IS FINE"}`, stderr: "gh: THIS IS FINE (HTTP 400)\n", isatty: false, }, { name: "REST string errors", httpResponse: &http.Response{ StatusCode: 400, Body: io.NopCloser(bytes.NewBufferString(`{"errors": ["ALSO", "FINE"]}`)), Header: http.Header{"Content-Type": []string{"application/json; charset=utf-8"}}, }, err: cmdutil.SilentError, stdout: `{"errors": ["ALSO", "FINE"]}`, stderr: "gh: ALSO\nFINE\n", isatty: false, }, { name: "GraphQL error", options: ApiOptions{ RequestPath: "graphql", }, httpResponse: &http.Response{ StatusCode: 200, Body: io.NopCloser(bytes.NewBufferString(`{"errors": [{"message":"AGAIN"}, {"message":"FINE"}]}`)), Header: http.Header{"Content-Type": []string{"application/json; charset=utf-8"}}, }, err: cmdutil.SilentError, stdout: `{"errors": [{"message":"AGAIN"}, {"message":"FINE"}]}`, stderr: "gh: AGAIN\nFINE\n", isatty: false, }, { name: "failure", httpResponse: &http.Response{ StatusCode: 502, Body: io.NopCloser(bytes.NewBufferString(`gateway timeout`)), }, err: cmdutil.SilentError, stdout: `gateway timeout`, stderr: "gh: HTTP 502\n", isatty: false, }, { name: "silent", options: ApiOptions{ Silent: true, }, httpResponse: &http.Response{ StatusCode: 200, Body: io.NopCloser(bytes.NewBufferString(`body`)), }, err: nil, stdout: ``, stderr: ``, isatty: false, }, { name: "show response headers even when silent", options: ApiOptions{ ShowResponseHeaders: true, Silent: true, }, httpResponse: &http.Response{ Proto: "HTTP/1.1", Status: "200 Okey-dokey", StatusCode: 200, Body: io.NopCloser(bytes.NewBufferString(`body`)), Header: http.Header{"Content-Type": []string{"text/plain"}}, }, err: nil, stdout: "HTTP/1.1 200 Okey-dokey\nContent-Type: text/plain\r\n\r\n", stderr: ``, isatty: false, }, { name: "output template", options: ApiOptions{ Template: `{{.status}}`, }, httpResponse: &http.Response{ StatusCode: 200, Body: io.NopCloser(bytes.NewBufferString(`{"status":"not a cat"}`)), Header: http.Header{"Content-Type": []string{"application/json"}}, }, err: nil, stdout: "not a cat", stderr: ``, isatty: false, }, { name: "output template with range", options: ApiOptions{ Template: `{{range .}}{{.title}} ({{.labels | pluck "name" | join ", " }}){{"\n"}}{{end}}`, }, httpResponse: &http.Response{ StatusCode: 200, Body: io.NopCloser(bytes.NewBufferString(`[ { "title": "First title", "labels": [{"name":"bug"}, {"name":"help wanted"}] }, { "title": "Second but not last" }, { "title": "Alas, tis' the end", "labels": [{}, {"name":"feature"}] } ]`)), Header: http.Header{"Content-Type": []string{"application/json"}}, }, stdout: heredoc.Doc(` First title (bug, help wanted) Second but not last () Alas, tis' the end (, feature) `), }, { name: "output template when REST error", options: ApiOptions{ Template: `{{.status}}`, }, httpResponse: &http.Response{ StatusCode: 400, Body: io.NopCloser(bytes.NewBufferString(`{"message": "THIS IS FINE"}`)), Header: http.Header{"Content-Type": []string{"application/json; charset=utf-8"}}, }, err: cmdutil.SilentError, stdout: `{"message": "THIS IS FINE"}`, stderr: "gh: THIS IS FINE (HTTP 400)\n", isatty: false, }, { name: "jq filter", options: ApiOptions{ FilterOutput: `.[].name`, }, httpResponse: &http.Response{ StatusCode: 200, Body: io.NopCloser(bytes.NewBufferString(`[{"name":"Mona"},{"name":"Hubot"}]`)), Header: http.Header{"Content-Type": []string{"application/json"}}, }, err: nil, stdout: "Mona\nHubot\n", stderr: ``, isatty: false, }, { name: "jq filter when REST error", options: ApiOptions{ FilterOutput: `.[].name`, }, httpResponse: &http.Response{ StatusCode: 400, Body: io.NopCloser(bytes.NewBufferString(`{"message": "THIS IS FINE"}`)), Header: http.Header{"Content-Type": []string{"application/json; charset=utf-8"}}, }, err: cmdutil.SilentError, stdout: `{"message": "THIS IS FINE"}`, stderr: "gh: THIS IS FINE (HTTP 400)\n", isatty: false, }, { name: "jq filter outputting JSON to a TTY", options: ApiOptions{ FilterOutput: `.`, }, httpResponse: &http.Response{ StatusCode: 200, Body: io.NopCloser(bytes.NewBufferString(`[{"name":"Mona"},{"name":"Hubot"}]`)), Header: http.Header{"Content-Type": []string{"application/json"}}, }, err: nil, stdout: "[\n {\n \"name\": \"Mona\"\n },\n {\n \"name\": \"Hubot\"\n }\n]\n", stderr: ``, isatty: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, stdout, stderr := iostreams.Test() ios.SetStdoutTTY(tt.isatty) tt.options.IO = ios tt.options.Config = func() (gh.Config, error) { return config.NewBlankConfig(), nil } tt.options.HttpClient = func() (*http.Client, error) { var tr roundTripper = func(req *http.Request) (*http.Response, error) { resp := tt.httpResponse resp.Request = req return resp, nil } return &http.Client{Transport: tr}, nil } err := apiRun(&tt.options) if err != tt.err { t.Errorf("expected error %v, got %v", tt.err, err) } if stdout.String() != tt.stdout { t.Errorf("expected output %q, got %q", tt.stdout, stdout.String()) } if stderr.String() != tt.stderr { t.Errorf("expected error output %q, got %q", tt.stderr, stderr.String()) } }) } } func Test_apiRun_paginationREST(t *testing.T) { ios, _, stdout, stderr := iostreams.Test() requestCount := 0 responses := []*http.Response{ { Proto: "HTTP/1.1", Status: "200 OK", StatusCode: 200, Body: io.NopCloser(bytes.NewBufferString(`{"page":1}`)), Header: http.Header{ "Content-Type": []string{"application/json"}, "Link": []string{`<https://api.github.com/repositories/1227/issues?page=2>; rel="next", <https://api.github.com/repositories/1227/issues?page=3>; rel="last"`}, "X-Github-Request-Id": []string{"1"}, }, }, { Proto: "HTTP/1.1", Status: "200 OK", StatusCode: 200, Body: io.NopCloser(bytes.NewBufferString(`{"page":2}`)), Header: http.Header{ "Content-Type": []string{"application/json"}, "Link": []string{`<https://api.github.com/repositories/1227/issues?page=3>; rel="next", <https://api.github.com/repositories/1227/issues?page=3>; rel="last"`}, "X-Github-Request-Id": []string{"2"}, }, }, { Proto: "HTTP/1.1", Status: "200 OK", StatusCode: 200, Body: io.NopCloser(bytes.NewBufferString(`{"page":3}`)), Header: http.Header{ "Content-Type": []string{"application/json"}, "X-Github-Request-Id": []string{"3"}, }, }, } options := ApiOptions{ IO: ios, HttpClient: func() (*http.Client, error) { var tr roundTripper = func(req *http.Request) (*http.Response, error) { resp := responses[requestCount] resp.Request = req requestCount++ return resp, nil } return &http.Client{Transport: tr}, nil }, Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, RequestMethod: "GET", RequestMethodPassed: true, RequestPath: "issues", Paginate: true, RawFields: []string{"per_page=50", "page=1"}, } err := apiRun(&options) assert.NoError(t, err) assert.Equal(t, `{"page":1}{"page":2}{"page":3}`, stdout.String(), "stdout") assert.Equal(t, "", stderr.String(), "stderr") assert.Equal(t, "https://api.github.com/issues?page=1&per_page=50", responses[0].Request.URL.String()) assert.Equal(t, "https://api.github.com/repositories/1227/issues?page=2", responses[1].Request.URL.String()) assert.Equal(t, "https://api.github.com/repositories/1227/issues?page=3", responses[2].Request.URL.String()) } func Test_apiRun_arrayPaginationREST(t *testing.T) { ios, _, stdout, stderr := iostreams.Test() ios.SetStdoutTTY(false) requestCount := 0 responses := []*http.Response{ { StatusCode: 200, Body: io.NopCloser(bytes.NewBufferString(`[{"item":1},{"item":2}]`)), Header: http.Header{ "Content-Type": []string{"application/json"}, "Link": []string{`<https://api.github.com/repositories/1227/issues?page=2>; rel="next", <https://api.github.com/repositories/1227/issues?page=4>; rel="last"`}, }, }, { StatusCode: 200, Body: io.NopCloser(bytes.NewBufferString(`[{"item":3},{"item":4}]`)), Header: http.Header{ "Content-Type": []string{"application/json"}, "Link": []string{`<https://api.github.com/repositories/1227/issues?page=3>; rel="next", <https://api.github.com/repositories/1227/issues?page=4>; rel="last"`}, }, }, { StatusCode: 200, Body: io.NopCloser(bytes.NewBufferString(`[{"item":5}]`)), Header: http.Header{ "Content-Type": []string{"application/json"}, "Link": []string{`<https://api.github.com/repositories/1227/issues?page=4>; rel="next", <https://api.github.com/repositories/1227/issues?page=4>; rel="last"`}, }, }, { StatusCode: 200, Body: io.NopCloser(bytes.NewBufferString(`[]`)), Header: http.Header{ "Content-Type": []string{"application/json"}, }, }, } options := ApiOptions{ IO: ios, HttpClient: func() (*http.Client, error) { var tr roundTripper = func(req *http.Request) (*http.Response, error) { resp := responses[requestCount] resp.Request = req requestCount++ return resp, nil } return &http.Client{Transport: tr}, nil }, Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, RequestMethod: "GET", RequestMethodPassed: true, RequestPath: "issues", Paginate: true, RawFields: []string{"per_page=50", "page=1"}, } err := apiRun(&options) assert.NoError(t, err) assert.Equal(t, `[{"item":1},{"item":2},{"item":3},{"item":4},{"item":5} ]`, stdout.String(), "stdout") assert.Equal(t, "", stderr.String(), "stderr") assert.Equal(t, "https://api.github.com/issues?page=1&per_page=50", responses[0].Request.URL.String()) assert.Equal(t, "https://api.github.com/repositories/1227/issues?page=2", responses[1].Request.URL.String()) assert.Equal(t, "https://api.github.com/repositories/1227/issues?page=3", responses[2].Request.URL.String()) } func Test_apiRun_arrayPaginationREST_with_headers(t *testing.T) { ios, _, stdout, stderr := iostreams.Test() requestCount := 0 responses := []*http.Response{ { Proto: "HTTP/1.1", Status: "200 OK", StatusCode: 200, Body: io.NopCloser(bytes.NewBufferString(`[{"page":1}]`)), Header: http.Header{ "Content-Type": []string{"application/json"}, "Link": []string{`<https://api.github.com/repositories/1227/issues?page=2>; rel="next", <https://api.github.com/repositories/1227/issues?page=3>; rel="last"`}, "X-Github-Request-Id": []string{"1"}, }, }, { Proto: "HTTP/1.1", Status: "200 OK", StatusCode: 200, Body: io.NopCloser(bytes.NewBufferString(`[{"page":2}]`)), Header: http.Header{ "Content-Type": []string{"application/json"}, "Link": []string{`<https://api.github.com/repositories/1227/issues?page=3>; rel="next", <https://api.github.com/repositories/1227/issues?page=3>; rel="last"`}, "X-Github-Request-Id": []string{"2"}, }, }, { Proto: "HTTP/1.1", Status: "200 OK", StatusCode: 200, Body: io.NopCloser(bytes.NewBufferString(`[{"page":3}]`)), Header: http.Header{ "Content-Type": []string{"application/json"}, "X-Github-Request-Id": []string{"3"}, }, }, } options := ApiOptions{ IO: ios, HttpClient: func() (*http.Client, error) { var tr roundTripper = func(req *http.Request) (*http.Response, error) { resp := responses[requestCount] resp.Request = req requestCount++ return resp, nil } return &http.Client{Transport: tr}, nil }, Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, RequestMethod: "GET", RequestMethodPassed: true, RequestPath: "issues", Paginate: true, RawFields: []string{"per_page=50", "page=1"}, ShowResponseHeaders: true, } err := apiRun(&options) assert.NoError(t, err) assert.Equal(t, "HTTP/1.1 200 OK\nContent-Type: application/json\r\nLink: <https://api.github.com/repositories/1227/issues?page=2>; rel=\"next\", <https://api.github.com/repositories/1227/issues?page=3>; rel=\"last\"\r\nX-Github-Request-Id: 1\r\n\r\n[{\"page\":1}]\nHTTP/1.1 200 OK\nContent-Type: application/json\r\nLink: <https://api.github.com/repositories/1227/issues?page=3>; rel=\"next\", <https://api.github.com/repositories/1227/issues?page=3>; rel=\"last\"\r\nX-Github-Request-Id: 2\r\n\r\n[{\"page\":2}]\nHTTP/1.1 200 OK\nContent-Type: application/json\r\nX-Github-Request-Id: 3\r\n\r\n[{\"page\":3}]", stdout.String(), "stdout") assert.Equal(t, "", stderr.String(), "stderr") assert.Equal(t, "https://api.github.com/issues?page=1&per_page=50", responses[0].Request.URL.String()) assert.Equal(t, "https://api.github.com/repositories/1227/issues?page=2", responses[1].Request.URL.String()) assert.Equal(t, "https://api.github.com/repositories/1227/issues?page=3", responses[2].Request.URL.String()) } func Test_apiRun_paginationGraphQL(t *testing.T) { ios, _, stdout, stderr := iostreams.Test() requestCount := 0 responses := []*http.Response{ { StatusCode: 200, Header: http.Header{"Content-Type": []string{`application/json`}}, Body: io.NopCloser(bytes.NewBufferString(heredoc.Doc(` { "data": { "nodes": ["page one"], "pageInfo": { "endCursor": "PAGE1_END", "hasNextPage": true } } }`))), }, { StatusCode: 200, Header: http.Header{"Content-Type": []string{`application/json`}}, Body: io.NopCloser(bytes.NewBufferString(heredoc.Doc(` { "data": { "nodes": ["page two"], "pageInfo": { "endCursor": "PAGE2_END", "hasNextPage": false } } }`))), }, } options := ApiOptions{ IO: ios, HttpClient: func() (*http.Client, error) { var tr roundTripper = func(req *http.Request) (*http.Response, error) { resp := responses[requestCount] resp.Request = req requestCount++ return resp, nil } return &http.Client{Transport: tr}, nil }, Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, RawFields: []string{"foo=bar"}, RequestMethod: "POST", RequestPath: "graphql", Paginate: true, } err := apiRun(&options) require.NoError(t, err) assert.Equal(t, heredoc.Doc(` { "data": { "nodes": ["page one"], "pageInfo": { "endCursor": "PAGE1_END", "hasNextPage": true } } }{ "data": { "nodes": ["page two"], "pageInfo": { "endCursor": "PAGE2_END", "hasNextPage": false } } }`), stdout.String()) assert.Equal(t, "", stderr.String(), "stderr") var requestData struct { Variables map[string]interface{} } bb, err := io.ReadAll(responses[0].Request.Body) require.NoError(t, err) err = json.Unmarshal(bb, &requestData) require.NoError(t, err) _, hasCursor := requestData.Variables["endCursor"].(string) assert.Equal(t, false, hasCursor) bb, err = io.ReadAll(responses[1].Request.Body) require.NoError(t, err) err = json.Unmarshal(bb, &requestData) require.NoError(t, err) endCursor, hasCursor := requestData.Variables["endCursor"].(string) assert.Equal(t, true, hasCursor) assert.Equal(t, "PAGE1_END", endCursor) } func Test_apiRun_paginationGraphQL_slurp(t *testing.T) { ios, _, stdout, stderr := iostreams.Test() requestCount := 0 responses := []*http.Response{ { StatusCode: 200, Header: http.Header{"Content-Type": []string{`application/json`}}, Body: io.NopCloser(bytes.NewBufferString(heredoc.Doc(` { "data": { "nodes": ["page one"], "pageInfo": { "endCursor": "PAGE1_END", "hasNextPage": true } } }`))), }, { StatusCode: 200, Header: http.Header{"Content-Type": []string{`application/json`}}, Body: io.NopCloser(bytes.NewBufferString(heredoc.Doc(` { "data": { "nodes": ["page two"], "pageInfo": { "endCursor": "PAGE2_END", "hasNextPage": false } } }`))), }, } options := ApiOptions{ IO: ios, HttpClient: func() (*http.Client, error) { var tr roundTripper = func(req *http.Request) (*http.Response, error) { resp := responses[requestCount] resp.Request = req requestCount++ return resp, nil } return &http.Client{Transport: tr}, nil }, Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, RawFields: []string{"foo=bar"}, RequestMethod: "POST", RequestPath: "graphql", Paginate: true, Slurp: true, } err := apiRun(&options) require.NoError(t, err) assert.JSONEq(t, stdout.String(), `[ { "data": { "nodes": ["page one"], "pageInfo": { "endCursor": "PAGE1_END", "hasNextPage": true } } }, { "data": { "nodes": ["page two"], "pageInfo": { "endCursor": "PAGE2_END", "hasNextPage": false } } } ]`) assert.Equal(t, "", stderr.String(), "stderr") var requestData struct { Variables map[string]interface{} } bb, err := io.ReadAll(responses[0].Request.Body) require.NoError(t, err) err = json.Unmarshal(bb, &requestData) require.NoError(t, err) _, hasCursor := requestData.Variables["endCursor"].(string) assert.Equal(t, false, hasCursor) bb, err = io.ReadAll(responses[1].Request.Body) require.NoError(t, err) err = json.Unmarshal(bb, &requestData) require.NoError(t, err) endCursor, hasCursor := requestData.Variables["endCursor"].(string) assert.Equal(t, true, hasCursor) assert.Equal(t, "PAGE1_END", endCursor) } func Test_apiRun_paginated_template(t *testing.T) { ios, _, stdout, stderr := iostreams.Test() ios.SetStdoutTTY(true) requestCount := 0 responses := []*http.Response{ { StatusCode: 200, Header: http.Header{"Content-Type": []string{`application/json`}}, Body: io.NopCloser(bytes.NewBufferString(`{ "data": { "nodes": [ { "page": 1, "caption": "page one" } ], "pageInfo": { "endCursor": "PAGE1_END", "hasNextPage": true } } }`)), }, { StatusCode: 200, Header: http.Header{"Content-Type": []string{`application/json`}}, Body: io.NopCloser(bytes.NewBufferString(`{ "data": { "nodes": [ { "page": 20, "caption": "page twenty" } ], "pageInfo": { "endCursor": "PAGE20_END", "hasNextPage": false } } }`)), }, } options := ApiOptions{ IO: ios, HttpClient: func() (*http.Client, error) { var tr roundTripper = func(req *http.Request) (*http.Response, error) { resp := responses[requestCount] resp.Request = req requestCount++ return resp, nil } return &http.Client{Transport: tr}, nil }, Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, RequestMethod: "POST",
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
true
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/api/pagination_test.go
pkg/cmd/api/pagination_test.go
package api import ( "bytes" "io" "net/http" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func Test_findNextPage(t *testing.T) { tests := []struct { name string resp *http.Response want string want1 bool }{ { name: "no Link header", resp: &http.Response{}, want: "", want1: false, }, { name: "no next page in Link", resp: &http.Response{ Header: http.Header{ "Link": []string{`<https://api.github.com/issues?page=3>; rel="last"`}, }, }, want: "", want1: false, }, { name: "has next page", resp: &http.Response{ Header: http.Header{ "Link": []string{`<https://api.github.com/issues?page=2>; rel="next", <https://api.github.com/issues?page=3>; rel="last"`}, }, }, want: "https://api.github.com/issues?page=2", want1: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, got1 := findNextPage(tt.resp) if got != tt.want { t.Errorf("findNextPage() got = %v, want %v", got, tt.want) } if got1 != tt.want1 { t.Errorf("findNextPage() got1 = %v, want %v", got1, tt.want1) } }) } } func Test_findEndCursor(t *testing.T) { tests := []struct { name string json io.Reader want string }{ { name: "blank", json: bytes.NewBufferString(`{}`), want: "", }, { name: "unrelated fields", json: bytes.NewBufferString(`{ "hasNextPage": true, "endCursor": "THE_END" }`), want: "", }, { name: "has next page", json: bytes.NewBufferString(`{ "pageInfo": { "hasNextPage": true, "endCursor": "THE_END" } }`), want: "THE_END", }, { name: "more pageInfo blocks", json: bytes.NewBufferString(`{ "pageInfo": { "hasNextPage": true, "endCursor": "THE_END" }, "pageInfo": { "hasNextPage": true, "endCursor": "NOT_THIS" } }`), want: "THE_END", }, { name: "no next page", json: bytes.NewBufferString(`{ "pageInfo": { "hasNextPage": false, "endCursor": "THE_END" } }`), want: "", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := findEndCursor(tt.json); got != tt.want { t.Errorf("findEndCursor() = %v, want %v", got, tt.want) } }) } } func Test_addPerPage(t *testing.T) { type args struct { p string perPage int params map[string]interface{} } tests := []struct { name string args args want string }{ { name: "adds per_page", args: args{ p: "items", perPage: 13, params: nil, }, want: "items?per_page=13", }, { name: "avoids adding per_page if already in params", args: args{ p: "items", perPage: 13, params: map[string]interface{}{ "state": "open", "per_page": 99, }, }, want: "items", }, { name: "avoids adding per_page if already in query", args: args{ p: "items?per_page=6&state=open", perPage: 13, params: nil, }, want: "items?per_page=6&state=open", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := addPerPage(tt.args.p, tt.args.perPage, tt.args.params); got != tt.want { t.Errorf("addPerPage() = %v, want %v", got, tt.want) } }) } } func TestJsonArrayWriter(t *testing.T) { tests := []struct { name string pages []string want string }{ { name: "empty", pages: nil, want: "[]", }, { name: "single array", pages: []string{`[1,2]`}, want: `[[1,2]]`, }, { name: "multiple arrays", pages: []string{`[1,2]`, `[3]`}, want: `[[1,2],[3]]`, }, { name: "single object", pages: []string{`{"foo":1,"bar":"a"}`}, want: `[{"foo":1,"bar":"a"}]`, }, { name: "multiple pages", pages: []string{`{"foo":1,"bar":"a"}`, `{"foo":2,"bar":"b"}`}, want: `[{"foo":1,"bar":"a"},{"foo":2,"bar":"b"}]`, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { buf := &bytes.Buffer{} w := &jsonArrayWriter{ Writer: buf, } for _, page := range tt.pages { require.NoError(t, startPage(w)) n, err := w.Write([]byte(page)) require.NoError(t, err) assert.Equal(t, len(page), n) } require.NoError(t, w.Close()) assert.Equal(t, tt.want, buf.String()) }) } } func TestJsonArrayWriter_Copy(t *testing.T) { tests := []struct { name string limit int }{ { name: "unlimited", }, { name: "limited", limit: 2, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { buf := &bytes.Buffer{} w := &jsonArrayWriter{ Writer: buf, } r := &noWriteToReader{ Reader: bytes.NewBufferString(`[1,2]`), limit: tt.limit, } require.NoError(t, startPage(w)) n, err := io.Copy(w, r) require.NoError(t, err) assert.Equal(t, int64(5), n) require.NoError(t, w.Close()) assert.Equal(t, `[[1,2]]`, buf.String()) }) } } type noWriteToReader struct { io.Reader limit int } func (r *noWriteToReader) Read(p []byte) (int, error) { if r.limit > 0 { p = p[:r.limit] } return r.Reader.Read(p) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/api/fields_test.go
pkg/cmd/api/fields_test.go
package api import ( "encoding/json" "fmt" "os" "strings" "testing" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/iostreams" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func Test_parseFields(t *testing.T) { ios, stdin, _, _ := iostreams.Test() fmt.Fprint(stdin, "pasted contents") opts := ApiOptions{ IO: ios, RawFields: []string{ "robot=Hubot", "destroyer=false", "helper=true", "location=@work", }, MagicFields: []string{ "input=@-", "enabled=true", "victories=123", }, } params, err := parseFields(&opts) if err != nil { t.Fatalf("parseFields error: %v", err) } expect := map[string]interface{}{ "robot": "Hubot", "destroyer": "false", "helper": "true", "location": "@work", "input": "pasted contents", "enabled": true, "victories": 123, } assert.Equal(t, expect, params) } func Test_parseFields_nested(t *testing.T) { ios, stdin, _, _ := iostreams.Test() fmt.Fprint(stdin, "pasted contents") opts := ApiOptions{ IO: ios, RawFields: []string{ "branch[name]=patch-1", "robots[]=Hubot", "robots[]=Dependabot", "labels[][name]=bug", "labels[][color]=red", "labels[][colorOptions][]=red", "labels[][colorOptions][]=blue", "labels[][name]=feature", "labels[][color]=green", "labels[][colorOptions][]=red", "labels[][colorOptions][]=green", "labels[][colorOptions][]=yellow", "nested[][key1][key2][key3]=value", "empty[]", }, MagicFields: []string{ "branch[protections]=true", "ids[]=123", "ids[]=456", }, } params, err := parseFields(&opts) if err != nil { t.Fatalf("parseFields error: %v", err) } jsonData, err := json.MarshalIndent(params, "", "\t") if err != nil { t.Fatal(err) } assert.Equal(t, strings.TrimSuffix(heredoc.Doc(` { "branch": { "name": "patch-1", "protections": true }, "empty": [], "ids": [ 123, 456 ], "labels": [ { "color": "red", "colorOptions": [ "red", "blue" ], "name": "bug" }, { "color": "green", "colorOptions": [ "red", "green", "yellow" ], "name": "feature" } ], "nested": [ { "key1": { "key2": { "key3": "value" } } } ], "robots": [ "Hubot", "Dependabot" ] } `), "\n"), string(jsonData)) } func Test_parseFields_errors(t *testing.T) { ios, stdin, _, _ := iostreams.Test() fmt.Fprint(stdin, "pasted contents") tests := []struct { name string opts *ApiOptions expected string }{ { name: "cannot overwrite string to array", opts: &ApiOptions{ IO: ios, RawFields: []string{ "object[field]=A", "object[field][]=this should be an error", }, }, expected: `expected array type under "field", got string`, }, { name: "cannot overwrite string to object", opts: &ApiOptions{ IO: ios, RawFields: []string{ "object[field]=B", "object[field][field2]=this should be an error", }, }, expected: `expected map type under "field", got string`, }, { name: "cannot overwrite object to string", opts: &ApiOptions{ IO: ios, RawFields: []string{ "object[field][field2]=C", "object[field]=this should be an error", }, }, expected: `unexpected override existing field under "field"`, }, { name: "cannot overwrite object to array", opts: &ApiOptions{ IO: ios, RawFields: []string{ "object[field][field2]=D", "object[field][]=this should be an error", }, }, expected: `expected array type under "field", got map[string]interface {}`, }, { name: "cannot overwrite array to string", opts: &ApiOptions{ IO: ios, RawFields: []string{ "object[field][]=E", "object[field]=this should be an error", }, }, expected: `unexpected override existing field under "field"`, }, { name: "cannot overwrite array to object", opts: &ApiOptions{ IO: ios, RawFields: []string{ "object[field][]=F", "object[field][field2]=this should be an error", }, }, expected: `expected map type under "field", got []interface {}`, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { _, err := parseFields(tt.opts) require.EqualError(t, err, tt.expected) }) } } func Test_magicFieldValue(t *testing.T) { f, err := os.CreateTemp(t.TempDir(), "gh-test") if err != nil { t.Fatal(err) } defer f.Close() fmt.Fprint(f, "file contents") ios, _, _, _ := iostreams.Test() type args struct { v string opts *ApiOptions } tests := []struct { name string args args want interface{} wantErr bool }{ { name: "string", args: args{v: "hello"}, want: "hello", wantErr: false, }, { name: "bool true", args: args{v: "true"}, want: true, wantErr: false, }, { name: "bool false", args: args{v: "false"}, want: false, wantErr: false, }, { name: "null", args: args{v: "null"}, want: nil, wantErr: false, }, { name: "placeholder colon", args: args{ v: ":owner", opts: &ApiOptions{ IO: ios, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("hubot", "robot-uprising"), nil }, }, }, want: "hubot", wantErr: false, }, { name: "placeholder braces", args: args{ v: "{owner}", opts: &ApiOptions{ IO: ios, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("hubot", "robot-uprising"), nil }, }, }, want: "hubot", wantErr: false, }, { name: "file", args: args{ v: "@" + f.Name(), opts: &ApiOptions{IO: ios}, }, want: "file contents", wantErr: false, }, { name: "file error", args: args{ v: "@", opts: &ApiOptions{IO: ios}, }, want: nil, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := magicFieldValue(tt.args.v, tt.args.opts) if (err != nil) != tt.wantErr { t.Errorf("magicFieldValue() error = %v, wantErr %v", err, tt.wantErr) return } if tt.wantErr { return } assert.Equal(t, tt.want, got) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/api/pagination.go
pkg/cmd/api/pagination.go
package api import ( "encoding/json" "fmt" "io" "net/http" "net/url" "regexp" "strings" "github.com/cli/cli/v2/pkg/jsoncolor" ) var linkRE = regexp.MustCompile(`<([^>]+)>;\s*rel="([^"]+)"`) func findNextPage(resp *http.Response) (string, bool) { for _, m := range linkRE.FindAllStringSubmatch(resp.Header.Get("Link"), -1) { if len(m) > 2 && m[2] == "next" { return m[1], true } } return "", false } func findEndCursor(r io.Reader) string { dec := json.NewDecoder(r) var idx int var stack []json.Delim var lastKey string var contextKey string var endCursor string var hasNextPage bool var foundEndCursor bool var foundNextPage bool loop: for { t, err := dec.Token() if err == io.EOF { break } if err != nil { return "" } switch tt := t.(type) { case json.Delim: switch tt { case '{', '[': stack = append(stack, tt) contextKey = lastKey idx = 0 case '}', ']': stack = stack[:len(stack)-1] contextKey = "" idx = 0 } default: isKey := len(stack) > 0 && stack[len(stack)-1] == '{' && idx%2 == 0 idx++ switch tt := t.(type) { case string: if isKey { lastKey = tt } else if contextKey == "pageInfo" && lastKey == "endCursor" { endCursor = tt foundEndCursor = true if foundNextPage { break loop } } case bool: if contextKey == "pageInfo" && lastKey == "hasNextPage" { hasNextPage = tt foundNextPage = true if foundEndCursor { break loop } } } } } if hasNextPage { return endCursor } return "" } func addPerPage(p string, perPage int, params map[string]interface{}) string { if _, hasPerPage := params["per_page"]; hasPerPage { return p } idx := strings.IndexRune(p, '?') sep := "?" if idx >= 0 { if qp, err := url.ParseQuery(p[idx+1:]); err == nil && qp.Get("per_page") != "" { return p } sep = "&" } return fmt.Sprintf("%s%sper_page=%d", p, sep, perPage) } // paginatedArrayReader wraps a Reader to omit the opening and/or the closing square bracket of a // JSON array in order to apply pagination context between multiple API requests. type paginatedArrayReader struct { io.Reader isFirstPage bool isLastPage bool isSubsequentRead bool cachedByte byte } func (r *paginatedArrayReader) Read(p []byte) (int, error) { var n int var err error if r.cachedByte != 0 && len(p) > 0 { p[0] = r.cachedByte n, err = r.Reader.Read(p[1:]) n += 1 r.cachedByte = 0 } else { n, err = r.Reader.Read(p) } if !r.isSubsequentRead && !r.isFirstPage && n > 0 && p[0] == '[' { if n > 1 && p[1] == ']' { // empty array case p[0] = ' ' } else { // avoid starting a new array and continue with a comma instead p[0] = ',' } } if !r.isLastPage && n > 0 && p[n-1] == ']' { // avoid closing off an array in case we determine we are at EOF r.cachedByte = p[n-1] n -= 1 } r.isSubsequentRead = true return n, err } // jsonArrayWriter wraps a Writer which writes multiple pages of both JSON arrays // and objects. Call Close to write the end of the array. type jsonArrayWriter struct { io.Writer started bool color bool } func (w *jsonArrayWriter) Preface() []json.Delim { if w.started { return []json.Delim{'['} } return nil } // ReadFrom implements io.ReaderFrom to write more data than read, // which otherwise results in an error from io.Copy(). func (w *jsonArrayWriter) ReadFrom(r io.Reader) (int64, error) { var written int64 buf := make([]byte, 4069) for { n, err := r.Read(buf) if n > 0 { n, err := w.Write(buf[:n]) written += int64(n) if err != nil { return written, err } } if err == io.EOF { break } if err != nil { return written, err } } return written, nil } func (w *jsonArrayWriter) Close() error { var delims string if w.started { delims = "]" } else { delims = "[]" } w.started = false if w.color { return jsoncolor.WriteDelims(w, delims, ttyIndent) } _, err := w.Writer.Write([]byte(delims)) return err } func startPage(w io.Writer) error { if jaw, ok := w.(*jsonArrayWriter); ok { var delims string var indent bool if !jaw.started { delims = "[" jaw.started = true } else { delims = "," indent = true } if jaw.color { if indent { _, err := jaw.Write([]byte(ttyIndent)) if err != nil { return err } } return jsoncolor.WriteDelims(w, delims, ttyIndent) } _, err := jaw.Write([]byte(delims)) 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/api/http_test.go
pkg/cmd/api/http_test.go
package api import ( "bytes" "io" "net/http" "testing" "github.com/stretchr/testify/assert" ) func Test_groupGraphQLVariables(t *testing.T) { tests := []struct { name string args map[string]interface{} want map[string]interface{} }{ { name: "empty", args: map[string]interface{}{}, want: map[string]interface{}{}, }, { name: "query only", args: map[string]interface{}{ "query": "QUERY", }, want: map[string]interface{}{ "query": "QUERY", }, }, { name: "variables only", args: map[string]interface{}{ "name": "hubot", }, want: map[string]interface{}{ "variables": map[string]interface{}{ "name": "hubot", }, }, }, { name: "query + variables", args: map[string]interface{}{ "query": "QUERY", "name": "hubot", "power": 9001, }, want: map[string]interface{}{ "query": "QUERY", "variables": map[string]interface{}{ "name": "hubot", "power": 9001, }, }, }, { name: "query + operationName + variables", args: map[string]interface{}{ "query": "query Q1{} query Q2{}", "operationName": "Q1", "power": 9001, }, want: map[string]interface{}{ "query": "query Q1{} query Q2{}", "operationName": "Q1", "variables": map[string]interface{}{ "power": 9001, }, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := groupGraphQLVariables(tt.args) assert.Equal(t, tt.want, got) }) } } type roundTripper func(*http.Request) (*http.Response, error) func (f roundTripper) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) } func Test_httpRequest(t *testing.T) { var tr roundTripper = func(req *http.Request) (*http.Response, error) { return &http.Response{Request: req}, nil } httpClient := http.Client{Transport: tr} type args struct { client *http.Client host string method string p string params interface{} headers []string } type expects struct { method string u string body string headers string } tests := []struct { name string args args want expects wantErr bool }{ { name: "simple GET", args: args{ client: &httpClient, host: "github.com", method: "GET", p: "repos/octocat/spoon-knife", params: nil, headers: []string{}, }, wantErr: false, want: expects{ method: "GET", u: "https://api.github.com/repos/octocat/spoon-knife", body: "", headers: "Accept: */*\r\n", }, }, { name: "GET with accept header", args: args{ client: &httpClient, host: "github.com", method: "GET", p: "repos/octocat/spoon-knife", params: nil, headers: []string{"Accept: testing"}, }, wantErr: false, want: expects{ method: "GET", u: "https://api.github.com/repos/octocat/spoon-knife", body: "", headers: "Accept: testing\r\n", }, }, { name: "lowercase HTTP method", args: args{ client: &httpClient, host: "github.com", method: "get", p: "repos/octocat/spoon-knife", params: nil, headers: []string{}, }, wantErr: false, want: expects{ method: "GET", u: "https://api.github.com/repos/octocat/spoon-knife", body: "", headers: "Accept: */*\r\n", }, }, { name: "GET with leading slash", args: args{ client: &httpClient, host: "github.com", method: "GET", p: "/repos/octocat/spoon-knife", params: nil, headers: []string{}, }, wantErr: false, want: expects{ method: "GET", u: "https://api.github.com/repos/octocat/spoon-knife", body: "", headers: "Accept: */*\r\n", }, }, { name: "Enterprise REST", args: args{ client: &httpClient, host: "example.org", method: "GET", p: "repos/octocat/spoon-knife", params: nil, headers: []string{}, }, wantErr: false, want: expects{ method: "GET", u: "https://example.org/api/v3/repos/octocat/spoon-knife", body: "", headers: "Accept: */*\r\n", }, }, { name: "GET with params", args: args{ client: &httpClient, host: "github.com", method: "GET", p: "repos/octocat/spoon-knife", params: map[string]interface{}{ "a": "b", }, headers: []string{}, }, wantErr: false, want: expects{ method: "GET", u: "https://api.github.com/repos/octocat/spoon-knife?a=b", body: "", headers: "Accept: */*\r\n", }, }, { name: "POST with params", args: args{ client: &httpClient, host: "github.com", method: "POST", p: "repos", params: map[string]interface{}{ "a": "b", }, headers: []string{}, }, wantErr: false, want: expects{ method: "POST", u: "https://api.github.com/repos", body: `{"a":"b"}`, headers: "Accept: */*\r\nContent-Type: application/json; charset=utf-8\r\n", }, }, { name: "POST GraphQL", args: args{ client: &httpClient, host: "github.com", method: "POST", p: "graphql", params: map[string]interface{}{ "a": "b", }, headers: []string{}, }, wantErr: false, want: expects{ method: "POST", u: "https://api.github.com/graphql", body: `{"variables":{"a":"b"}}`, headers: "Accept: */*\r\nContent-Type: application/json; charset=utf-8\r\n", }, }, { name: "Enterprise GraphQL", args: args{ client: &httpClient, host: "example.org", method: "POST", p: "graphql", params: map[string]interface{}{}, headers: []string{}, }, wantErr: false, want: expects{ method: "POST", u: "https://example.org/api/graphql", body: `{}`, headers: "Accept: */*\r\nContent-Type: application/json; charset=utf-8\r\n", }, }, { name: "POST with body and type", args: args{ client: &httpClient, host: "github.com", method: "POST", p: "repos", params: bytes.NewBufferString("CUSTOM"), headers: []string{ "content-type: text/plain", "accept: application/json", }, }, wantErr: false, want: expects{ method: "POST", u: "https://api.github.com/repos", body: `CUSTOM`, headers: "Accept: application/json\r\nContent-Type: text/plain\r\n", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := httpRequest(tt.args.client, tt.args.host, tt.args.method, tt.args.p, tt.args.params, tt.args.headers) if (err != nil) != tt.wantErr { t.Errorf("httpRequest() error = %v, wantErr %v", err, tt.wantErr) return } req := got.Request if req.Method != tt.want.method { t.Errorf("Request.Method = %q, want %q", req.Method, tt.want.method) } if req.URL.String() != tt.want.u { t.Errorf("Request.URL = %q, want %q", req.URL.String(), tt.want.u) } if tt.want.body != "" { bb, err := io.ReadAll(req.Body) if err != nil { t.Errorf("Request.Body ReadAll error = %v", err) return } if string(bb) != tt.want.body { t.Errorf("Request.Body = %q, want %q", string(bb), tt.want.body) } } h := bytes.Buffer{} err = req.Header.WriteSubset(&h, map[string]bool{}) if err != nil { t.Errorf("Request.Header WriteSubset error = %v", err) return } if h.String() != tt.want.headers { t.Errorf("Request.Header = %q, want %q", h.String(), tt.want.headers) } }) } } func Test_addQuery(t *testing.T) { type args struct { path string params map[string]interface{} } tests := []struct { name string args args want string }{ { name: "string", args: args{ path: "", params: map[string]interface{}{"a": "hello"}, }, want: "?a=hello", }, { name: "array", args: args{ path: "", params: map[string]interface{}{"a": []interface{}{"hello", "world"}}, }, want: "?a%5B%5D=hello&a%5B%5D=world", }, { name: "append", args: args{ path: "path", params: map[string]interface{}{"a": "b"}, }, want: "path?a=b", }, { name: "append query", args: args{ path: "path?foo=bar", params: map[string]interface{}{"a": "b"}, }, want: "path?foo=bar&a=b", }, { name: "[]byte", args: args{ path: "", params: map[string]interface{}{"a": []byte("hello")}, }, want: "?a=hello", }, { name: "int", args: args{ path: "", params: map[string]interface{}{"a": 123}, }, want: "?a=123", }, { name: "nil", args: args{ path: "", params: map[string]interface{}{"a": nil}, }, want: "?a=", }, { name: "bool", args: args{ path: "", params: map[string]interface{}{"a": true, "b": false}, }, want: "?a=true&b=false", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := addQuery(tt.args.path, tt.args.params); got != tt.want { t.Errorf("addQuery() = %v, want %v", got, tt.want) } }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/api/http.go
pkg/cmd/api/http.go
package api import ( "bytes" "encoding/json" "fmt" "io" "net/http" "net/url" "strconv" "strings" "github.com/cli/cli/v2/internal/ghinstance" ) func httpRequest(client *http.Client, hostname string, method string, p string, params interface{}, headers []string) (*http.Response, error) { isGraphQL := p == "graphql" var requestURL string if strings.Contains(p, "://") { requestURL = p } else if isGraphQL { requestURL = ghinstance.GraphQLEndpoint(hostname) } else { requestURL = ghinstance.RESTPrefix(hostname) + strings.TrimPrefix(p, "/") } var body io.Reader var bodyIsJSON bool switch pp := params.(type) { case map[string]interface{}: if strings.EqualFold(method, "GET") { requestURL = addQuery(requestURL, pp) } else { if isGraphQL { pp = groupGraphQLVariables(pp) } b, err := json.Marshal(pp) if err != nil { return nil, fmt.Errorf("error serializing parameters: %w", err) } body = bytes.NewBuffer(b) bodyIsJSON = true } case io.Reader: body = pp case nil: body = nil default: return nil, fmt.Errorf("unrecognized parameters type: %v", params) } req, err := http.NewRequest(strings.ToUpper(method), requestURL, body) if err != nil { return nil, err } for _, h := range headers { idx := strings.IndexRune(h, ':') if idx == -1 { return nil, fmt.Errorf("header %q requires a value separated by ':'", h) } name, value := h[0:idx], strings.TrimSpace(h[idx+1:]) if strings.EqualFold(name, "Content-Length") { length, err := strconv.ParseInt(value, 10, 0) if err != nil { return nil, err } req.ContentLength = length } else { req.Header.Add(name, value) } } if bodyIsJSON && req.Header.Get("Content-Type") == "" { req.Header.Set("Content-Type", "application/json; charset=utf-8") } if req.Header.Get("Accept") == "" { req.Header.Set("Accept", "*/*") } return client.Do(req) } func groupGraphQLVariables(params map[string]interface{}) map[string]interface{} { topLevel := make(map[string]interface{}) variables := make(map[string]interface{}) for key, val := range params { switch key { case "query", "operationName": topLevel[key] = val default: variables[key] = val } } if len(variables) > 0 { topLevel["variables"] = variables } return topLevel } func addQuery(path string, params map[string]interface{}) string { if len(params) == 0 { return path } query := url.Values{} if err := addQueryParam(query, "", params); err != nil { panic(err) } sep := "?" if strings.ContainsRune(path, '?') { sep = "&" } return path + sep + query.Encode() } func addQueryParam(query url.Values, key string, value interface{}) error { switch v := value.(type) { case string: query.Add(key, v) case []byte: query.Add(key, string(v)) case nil: query.Add(key, "") case int: query.Add(key, fmt.Sprintf("%d", v)) case bool: query.Add(key, fmt.Sprintf("%v", v)) case map[string]interface{}: for subkey, value := range v { // support for nested subkeys can be added here if that is ever necessary if err := addQueryParam(query, subkey, value); err != nil { return err } } case []interface{}: for _, entry := range v { if err := addQueryParam(query, key+"[]", entry); err != nil { return err } } default: return fmt.Errorf("unknown type %v", v) } return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/api/fields.go
pkg/cmd/api/fields.go
package api import ( "fmt" "reflect" "strconv" "strings" ) const ( keyStart = '[' keyEnd = ']' keySeparator = '=' ) func parseFields(opts *ApiOptions) (map[string]interface{}, error) { params := make(map[string]interface{}) parseField := func(f string, isMagic bool) error { var valueIndex int var keystack []string keyStartAt := 0 parseLoop: for i, r := range f { switch r { case keyStart: if keyStartAt == 0 { keystack = append(keystack, f[0:i]) } keyStartAt = i + 1 case keyEnd: keystack = append(keystack, f[keyStartAt:i]) case keySeparator: if keyStartAt == 0 { keystack = append(keystack, f[0:i]) } valueIndex = i + 1 break parseLoop } } if len(keystack) == 0 { return fmt.Errorf("invalid key: %q", f) } key := f var value interface{} = nil if valueIndex == 0 { if keystack[len(keystack)-1] != "" { return fmt.Errorf("field %q requires a value separated by an '=' sign", key) } } else { key = f[0 : valueIndex-1] value = f[valueIndex:] } if isMagic && value != nil { var err error value, err = magicFieldValue(value.(string), opts) if err != nil { return fmt.Errorf("error parsing %q value: %w", key, err) } } destMap := params isArray := false var subkey string for _, k := range keystack { if k == "" { isArray = true continue } if subkey != "" { var err error if isArray { destMap, err = addParamsSlice(destMap, subkey, k) isArray = false } else { destMap, err = addParamsMap(destMap, subkey) } if err != nil { return err } } subkey = k } if isArray { if value == nil { destMap[subkey] = []interface{}{} } else { if v, exists := destMap[subkey]; exists { if existSlice, ok := v.([]interface{}); ok { destMap[subkey] = append(existSlice, value) } else { return fmt.Errorf("expected array type under %q, got %T", subkey, v) } } else { destMap[subkey] = []interface{}{value} } } } else { if _, exists := destMap[subkey]; exists { return fmt.Errorf("unexpected override existing field under %q", subkey) } destMap[subkey] = value } return nil } for _, f := range opts.RawFields { if err := parseField(f, false); err != nil { return params, err } } for _, f := range opts.MagicFields { if err := parseField(f, true); err != nil { return params, err } } return params, nil } func addParamsMap(m map[string]interface{}, key string) (map[string]interface{}, error) { if v, exists := m[key]; exists { if existMap, ok := v.(map[string]interface{}); ok { return existMap, nil } else { return nil, fmt.Errorf("expected map type under %q, got %T", key, v) } } newMap := make(map[string]interface{}) m[key] = newMap return newMap, nil } func addParamsSlice(m map[string]interface{}, prevkey, newkey string) (map[string]interface{}, error) { if v, exists := m[prevkey]; exists { if existSlice, ok := v.([]interface{}); ok { if len(existSlice) > 0 { lastItem := existSlice[len(existSlice)-1] if lastMap, ok := lastItem.(map[string]interface{}); ok { if _, keyExists := lastMap[newkey]; !keyExists { return lastMap, nil } else if reflect.TypeOf(lastMap[newkey]).Kind() == reflect.Slice { return lastMap, nil } } } newMap := make(map[string]interface{}) m[prevkey] = append(existSlice, newMap) return newMap, nil } else { return nil, fmt.Errorf("expected array type under %q, got %T", prevkey, v) } } newMap := make(map[string]interface{}) m[prevkey] = []interface{}{newMap} return newMap, nil } func magicFieldValue(v string, opts *ApiOptions) (interface{}, error) { if strings.HasPrefix(v, "@") { b, err := opts.IO.ReadUserFile(v[1:]) if err != nil { return "", err } return string(b), nil } if n, err := strconv.Atoi(v); err == nil { return n, nil } switch v { case "true": return true, nil case "false": return false, nil case "null": return nil, nil default: return fillPlaceholders(v, opts) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/alias/alias.go
pkg/cmd/alias/alias.go
package alias import ( "github.com/MakeNowJust/heredoc" deleteCmd "github.com/cli/cli/v2/pkg/cmd/alias/delete" importCmd "github.com/cli/cli/v2/pkg/cmd/alias/imports" listCmd "github.com/cli/cli/v2/pkg/cmd/alias/list" setCmd "github.com/cli/cli/v2/pkg/cmd/alias/set" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/spf13/cobra" ) func NewCmdAlias(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "alias <command>", Short: "Create command shortcuts", Long: heredoc.Docf(` Aliases can be used to make shortcuts for gh commands or to compose multiple commands. Run %[1]sgh help alias set%[1]s to learn more. `, "`"), } cmdutil.DisableAuthCheck(cmd) cmd.AddCommand(deleteCmd.NewCmdDelete(f, nil)) cmd.AddCommand(importCmd.NewCmdImport(f, nil)) cmd.AddCommand(listCmd.NewCmdList(f, nil)) cmd.AddCommand(setCmd.NewCmdSet(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/alias/delete/delete.go
pkg/cmd/alias/delete/delete.go
package delete import ( "fmt" "sort" "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 DeleteOptions struct { Config func() (gh.Config, error) IO *iostreams.IOStreams Name string All bool } func NewCmdDelete(f *cmdutil.Factory, runF func(*DeleteOptions) error) *cobra.Command { opts := &DeleteOptions{ IO: f.IOStreams, Config: f.Config, } cmd := &cobra.Command{ Use: "delete {<alias> | --all}", Short: "Delete set aliases", Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { if len(args) == 0 && !opts.All { return cmdutil.FlagErrorf("specify an alias to delete or `--all`") } if len(args) > 0 && opts.All { return cmdutil.FlagErrorf("cannot use `--all` with alias name") } if len(args) > 0 { opts.Name = args[0] } if runF != nil { return runF(opts) } return deleteRun(opts) }, } cmd.Flags().BoolVar(&opts.All, "all", false, "Delete all aliases") return cmd } func deleteRun(opts *DeleteOptions) error { cfg, err := opts.Config() if err != nil { return err } aliasCfg := cfg.Aliases() aliases := make(map[string]string) if opts.All { aliases = aliasCfg.All() if len(aliases) == 0 { return cmdutil.NewNoResultsError("no aliases configured") } } else { expansion, err := aliasCfg.Get(opts.Name) if err != nil { return fmt.Errorf("no such alias %s", opts.Name) } aliases[opts.Name] = expansion } for name := range aliases { if err := aliasCfg.Delete(name); err != nil { return fmt.Errorf("failed to delete alias %s: %w", name, err) } } if err := cfg.Write(); err != nil { return err } if opts.IO.IsStdoutTTY() { cs := opts.IO.ColorScheme() keys := make([]string, 0, len(aliases)) for k := range aliases { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { fmt.Fprintf(opts.IO.ErrOut, "%s Deleted alias %s; was %s\n", cs.SuccessIconWithColor(cs.Red), k, aliases[k]) } } return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/alias/delete/delete_test.go
pkg/cmd/alias/delete/delete_test.go
package delete import ( "bytes" "io" "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" ) func TestNewCmdDelete(t *testing.T) { tests := []struct { name string input string output DeleteOptions wantErr bool errMsg string }{ { name: "no arguments", input: "", wantErr: true, errMsg: "specify an alias to delete or `--all`", }, { name: "specified alias", input: "co", output: DeleteOptions{ Name: "co", }, }, { name: "all flag", input: "--all", output: DeleteOptions{ All: true, }, }, { name: "specified alias and all flag", input: "co --all", wantErr: true, errMsg: "cannot use `--all` with alias name", }, { name: "too many arguments", input: "il co", wantErr: true, errMsg: "accepts at most 1 arg(s), received 2", }, } 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 *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.wantErr { assert.EqualError(t, err, tt.errMsg) return } assert.NoError(t, err) assert.Equal(t, tt.output.Name, gotOpts.Name) assert.Equal(t, tt.output.All, gotOpts.All) }) } } func TestDeleteRun(t *testing.T) { tests := []struct { name string config string isTTY bool opts *DeleteOptions wantAliases map[string]string wantStdout string wantStderr string wantErrMsg string }{ { name: "delete alias", config: heredoc.Doc(` aliases: il: issue list co: pr checkout `), isTTY: true, opts: &DeleteOptions{ Name: "co", All: false, }, wantAliases: map[string]string{ "il": "issue list", }, wantStderr: "✓ Deleted alias co; was pr checkout\n", }, { name: "delete all aliases", config: heredoc.Doc(` aliases: il: issue list co: pr checkout `), isTTY: true, opts: &DeleteOptions{ All: true, }, wantAliases: map[string]string{}, wantStderr: "✓ Deleted alias co; was pr checkout\n✓ Deleted alias il; was issue list\n", }, { name: "delete alias that does not exist", config: heredoc.Doc(` aliases: il: issue list co: pr checkout `), isTTY: true, opts: &DeleteOptions{ Name: "unknown", }, wantAliases: map[string]string{ "il": "issue list", "co": "pr checkout", }, wantErrMsg: "no such alias unknown", }, { name: "delete all aliases when none exist", isTTY: true, opts: &DeleteOptions{ All: true, }, wantAliases: map[string]string{}, wantErrMsg: "no aliases configured", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, stdout, stderr := iostreams.Test() ios.SetStdinTTY(tt.isTTY) ios.SetStdoutTTY(tt.isTTY) ios.SetStderrTTY(tt.isTTY) tt.opts.IO = ios cfg := config.NewFromString(tt.config) cfg.WriteFunc = func() error { return nil } tt.opts.Config = func() (gh.Config, error) { return cfg, nil } err := deleteRun(tt.opts) if tt.wantErrMsg != "" { assert.EqualError(t, err, tt.wantErrMsg) writeCalls := cfg.WriteCalls() assert.Equal(t, 0, len(writeCalls)) } else { assert.NoError(t, err) writeCalls := cfg.WriteCalls() assert.Equal(t, 1, len(writeCalls)) } assert.Equal(t, tt.wantStdout, stdout.String()) assert.Equal(t, tt.wantStderr, stderr.String()) assert.Equal(t, tt.wantAliases, cfg.Aliases().All()) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/alias/list/list_test.go
pkg/cmd/alias/list/list_test.go
package list import ( "bytes" "io" "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/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestAliasList(t *testing.T) { tests := []struct { name string config string isTTY bool wantErr bool wantStdout string wantStderr string }{ { name: "empty", config: "", isTTY: true, wantErr: true, wantStdout: "", wantStderr: "", }, { name: "some", config: heredoc.Doc(` aliases: co: pr checkout gc: "!gh gist create \"$@\" | pbcopy" `), isTTY: true, wantStdout: "co: pr checkout\ngc: '!gh gist create \"$@\" | pbcopy'\n", wantStderr: "", }, { name: "multiline", config: heredoc.Doc(` aliases: one: "foo\nbar\n" two: |- !chicken coop `), isTTY: true, wantStdout: "one: |\n foo\n bar\ntwo: |-\n !chicken\n coop\n", wantStderr: "", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { cfg := config.NewFromString(tt.config) ios, _, stdout, stderr := iostreams.Test() ios.SetStdoutTTY(tt.isTTY) ios.SetStdinTTY(tt.isTTY) ios.SetStderrTTY(tt.isTTY) factory := &cmdutil.Factory{ IOStreams: ios, Config: func() (gh.Config, error) { return cfg, nil }, } cmd := NewCmdList(factory, nil) cmd.SetArgs([]string{}) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(io.Discard) cmd.SetErr(io.Discard) _, err := cmd.ExecuteC() if tt.wantErr { require.Error(t, err) } else { require.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/alias/list/list.go
pkg/cmd/alias/list/list.go
package list import ( "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" "gopkg.in/yaml.v3" ) type ListOptions struct { Config func() (gh.Config, error) IO *iostreams.IOStreams } func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Command { opts := &ListOptions{ IO: f.IOStreams, Config: f.Config, } cmd := &cobra.Command{ Use: "list", Short: "List your aliases", Aliases: []string{"ls"}, Long: heredoc.Doc(` This command prints out all of the aliases gh is configured to use. `), Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { if runF != nil { return runF(opts) } return listRun(opts) }, } return cmd } func listRun(opts *ListOptions) error { cfg, err := opts.Config() if err != nil { return err } aliasCfg := cfg.Aliases() aliasMap := aliasCfg.All() if len(aliasMap) == 0 { return cmdutil.NewNoResultsError("no aliases configured") } enc := yaml.NewEncoder(opts.IO.Out) return enc.Encode(aliasMap) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/alias/shared/validations.go
pkg/cmd/alias/shared/validations.go
package shared import ( "strings" "github.com/google/shlex" "github.com/spf13/cobra" ) // ValidAliasNameFunc returns a function that will check if the given string // is a valid alias name. A name is valid if: // - it does not shadow an existing command, // - it is not nested under a command that is runnable, // - it is not nested under a command that does not exist. func ValidAliasNameFunc(cmd *cobra.Command) func(string) bool { return func(args string) bool { split, err := shlex.Split(args) if err != nil || len(split) == 0 { return false } rootCmd := cmd.Root() foundCmd, foundArgs, _ := rootCmd.Find(split) if foundCmd != nil && !foundCmd.Runnable() && len(foundArgs) == 1 { return true } return false } } // ValidAliasExpansionFunc returns a function that will check if the given string // is a valid alias expansion. An expansion is valid if: // - it is a shell expansion, // - it is a non-shell expansion that corresponds to an existing command, extension, or alias. func ValidAliasExpansionFunc(cmd *cobra.Command) func(string) bool { return func(expansion string) bool { if strings.HasPrefix(expansion, "!") { return true } split, err := shlex.Split(expansion) if err != nil || len(split) == 0 { return false } rootCmd := cmd.Root() cmd, _, _ = rootCmd.Find(split) return cmd != rootCmd } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/alias/shared/validations_test.go
pkg/cmd/alias/shared/validations_test.go
package shared import ( "testing" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" ) func TestValidAliasNameFunc(t *testing.T) { // Create fake command structure for testing. issueCmd := &cobra.Command{Use: "issue"} prCmd := &cobra.Command{Use: "pr"} prCmd.AddCommand(&cobra.Command{Use: "checkout"}) cmd := &cobra.Command{} cmd.AddCommand(prCmd) cmd.AddCommand(issueCmd) f := ValidAliasNameFunc(cmd) assert.False(t, f("pr")) assert.False(t, f("pr checkout")) assert.False(t, f("issue")) assert.False(t, f("repo list")) assert.True(t, f("ps")) assert.True(t, f("checkout")) assert.True(t, f("issue erase")) assert.True(t, f("pr erase")) assert.True(t, f("pr checkout branch")) } func TestValidAliasExpansionFunc(t *testing.T) { // Create fake command structure for testing. issueCmd := &cobra.Command{Use: "issue"} prCmd := &cobra.Command{Use: "pr"} prCmd.AddCommand(&cobra.Command{Use: "checkout"}) cmd := &cobra.Command{} cmd.AddCommand(prCmd) cmd.AddCommand(issueCmd) f := ValidAliasExpansionFunc(cmd) assert.False(t, f("ps")) assert.False(t, f("checkout")) assert.False(t, f("repo list")) assert.True(t, f("!git branch --show-current")) assert.True(t, f("pr")) assert.True(t, f("pr checkout")) assert.True(t, f("issue")) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/alias/imports/import_test.go
pkg/cmd/alias/imports/import_test.go
package imports import ( "bytes" "fmt" "io" "os" "path/filepath" "strings" "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/cmd/alias/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNewCmdImport(t *testing.T) { tests := []struct { name string cli string tty bool wants ImportOptions wantsError string }{ { name: "no filename and stdin tty", cli: "", tty: true, wants: ImportOptions{ Filename: "", OverwriteExisting: false, }, wantsError: "no filename passed and nothing on STDIN", }, { name: "no filename and stdin is not tty", cli: "", tty: false, wants: ImportOptions{ Filename: "-", OverwriteExisting: false, }, }, { name: "stdin arg", cli: "-", wants: ImportOptions{ Filename: "-", OverwriteExisting: false, }, }, { name: "multiple filenames", cli: "aliases1 aliases2", wants: ImportOptions{ Filename: "aliases1 aliases2", OverwriteExisting: false, }, wantsError: "too many arguments", }, { name: "clobber flag", cli: "aliases --clobber", wants: ImportOptions{ Filename: "aliases", OverwriteExisting: true, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() ios.SetStdinTTY(tt.tty) f := &cmdutil.Factory{IOStreams: ios} argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts *ImportOptions cmd := NewCmdImport(f, func(opts *ImportOptions) 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.wantsError != "" { assert.EqualError(t, err, tt.wantsError) return } assert.NoError(t, err) assert.Equal(t, tt.wants.Filename, gotOpts.Filename) assert.Equal(t, tt.wants.OverwriteExisting, gotOpts.OverwriteExisting) }) } } func TestImportRun(t *testing.T) { tmpFile := filepath.Join(t.TempDir(), "aliases.yml") importFileMsg := fmt.Sprintf(`- Importing aliases from file %q`, tmpFile) importStdinMsg := "- Importing aliases from standard input" tests := []struct { name string opts *ImportOptions stdin string fileContents string initConfig string aliasCommands []*cobra.Command wantConfig string wantStderr string }{ { name: "with no existing aliases", opts: &ImportOptions{ Filename: tmpFile, OverwriteExisting: false, }, fileContents: heredoc.Doc(` co: pr checkout igrep: '!gh issue list --label="$1" | grep "$2"' `), wantConfig: heredoc.Doc(` aliases: co: pr checkout igrep: '!gh issue list --label="$1" | grep "$2"' `), wantStderr: importFileMsg + "\n✓ Added alias co\n✓ Added alias igrep\n\n", }, { name: "with existing aliases", opts: &ImportOptions{ Filename: tmpFile, OverwriteExisting: false, }, fileContents: heredoc.Doc(` users: |- api graphql -F name="$1" -f query=' query ($name: String!) { user(login: $name) { name } }' co: pr checkout `), initConfig: heredoc.Doc(` aliases: igrep: '!gh issue list --label="$1" | grep "$2"' editor: vim `), aliasCommands: []*cobra.Command{ {Use: "igrep"}, }, wantConfig: heredoc.Doc(` aliases: igrep: '!gh issue list --label="$1" | grep "$2"' co: pr checkout users: |- api graphql -F name="$1" -f query=' query ($name: String!) { user(login: $name) { name } }' editor: vim `), wantStderr: importFileMsg + "\n✓ Added alias co\n✓ Added alias users\n\n", }, { name: "from stdin", opts: &ImportOptions{ Filename: "-", OverwriteExisting: false, }, stdin: heredoc.Doc(` co: pr checkout features: |- issue list --label=enhancement igrep: '!gh issue list --label="$1" | grep "$2"' `), wantConfig: heredoc.Doc(` aliases: co: pr checkout features: |- issue list --label=enhancement igrep: '!gh issue list --label="$1" | grep "$2"' `), wantStderr: importStdinMsg + "\n✓ Added alias co\n✓ Added alias features\n✓ Added alias igrep\n\n", }, { name: "already taken aliases", opts: &ImportOptions{ Filename: tmpFile, OverwriteExisting: false, }, fileContents: heredoc.Doc(` co: pr checkout -R cool/repo igrep: '!gh issue list --label="$1" | grep "$2"' `), initConfig: heredoc.Doc(` aliases: co: pr checkout editor: vim `), aliasCommands: []*cobra.Command{ {Use: "co"}, }, wantConfig: heredoc.Doc(` aliases: co: pr checkout igrep: '!gh issue list --label="$1" | grep "$2"' editor: vim `), wantStderr: importFileMsg + "\nX Could not import alias co: name already taken\n✓ Added alias igrep\n\n", }, { name: "override aliases", opts: &ImportOptions{ Filename: tmpFile, OverwriteExisting: true, }, fileContents: heredoc.Doc(` co: pr checkout -R cool/repo igrep: '!gh issue list --label="$1" | grep "$2"' `), initConfig: heredoc.Doc(` aliases: co: pr checkout editor: vim `), aliasCommands: []*cobra.Command{ {Use: "co"}, }, wantConfig: heredoc.Doc(` aliases: co: pr checkout -R cool/repo igrep: '!gh issue list --label="$1" | grep "$2"' editor: vim `), wantStderr: importFileMsg + "\n! Changed alias co\n✓ Added alias igrep\n\n", }, { name: "alias is a gh command", opts: &ImportOptions{ Filename: tmpFile, OverwriteExisting: false, }, fileContents: heredoc.Doc(` pr: pr checkout issue: issue list api: api graphql `), wantStderr: strings.Join( []string{ importFileMsg, "X Could not import alias api: already a gh command or extension", "X Could not import alias issue: already a gh command or extension", "X Could not import alias pr: already a gh command or extension\n\n", }, "\n", ), }, { name: "invalid expansion", opts: &ImportOptions{ Filename: tmpFile, OverwriteExisting: false, }, fileContents: heredoc.Doc(` alias1: alias2: ps checkout `), wantStderr: strings.Join( []string{ importFileMsg, "X Could not import alias alias1: expansion does not correspond to a gh command, extension, or alias", "X Could not import alias alias2: expansion does not correspond to a gh command, extension, or alias\n\n", }, "\n", ), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if tt.fileContents != "" { err := os.WriteFile(tmpFile, []byte(tt.fileContents), 0600) require.NoError(t, err) } ios, stdin, _, stderr := iostreams.Test() ios.SetStdinTTY(true) ios.SetStdoutTTY(true) ios.SetStderrTTY(true) tt.opts.IO = ios readConfigs := config.StubWriteConfig(t) cfg := config.NewFromString(tt.initConfig) tt.opts.Config = func() (gh.Config, error) { return cfg, nil } // Create fake command structure for testing. rootCmd := &cobra.Command{} prCmd := &cobra.Command{Use: "pr"} prCmd.AddCommand(&cobra.Command{Use: "checkout"}) prCmd.AddCommand(&cobra.Command{Use: "status"}) rootCmd.AddCommand(prCmd) issueCmd := &cobra.Command{Use: "issue"} issueCmd.AddCommand(&cobra.Command{Use: "list"}) rootCmd.AddCommand(issueCmd) apiCmd := &cobra.Command{Use: "api"} apiCmd.AddCommand(&cobra.Command{Use: "graphql"}) rootCmd.AddCommand(apiCmd) for _, cmd := range tt.aliasCommands { rootCmd.AddCommand(cmd) } tt.opts.validAliasName = shared.ValidAliasNameFunc(rootCmd) tt.opts.validAliasExpansion = shared.ValidAliasExpansionFunc(rootCmd) if tt.stdin != "" { stdin.WriteString(tt.stdin) } err := importRun(tt.opts) require.NoError(t, err) configOut := bytes.Buffer{} readConfigs(&configOut, io.Discard) assert.Equal(t, tt.wantStderr, stderr.String()) assert.Equal(t, tt.wantConfig, configOut.String()) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/alias/imports/import.go
pkg/cmd/alias/imports/import.go
package imports import ( "fmt" "sort" "strings" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/pkg/cmd/alias/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" "gopkg.in/yaml.v3" ) type ImportOptions struct { Config func() (gh.Config, error) IO *iostreams.IOStreams Filename string OverwriteExisting bool validAliasName func(string) bool validAliasExpansion func(string) bool } func NewCmdImport(f *cmdutil.Factory, runF func(*ImportOptions) error) *cobra.Command { opts := &ImportOptions{ IO: f.IOStreams, Config: f.Config, } cmd := &cobra.Command{ Use: "import [<filename> | -]", Short: "Import aliases from a YAML file", Long: heredoc.Docf(` Import aliases from the contents of a YAML file. Aliases should be defined as a map in YAML, where the keys represent aliases and the values represent the corresponding expansions. An example file should look like the following: bugs: issue list --label=bug igrep: '!gh issue list --label="$1" | grep "$2"' features: |- issue list --label=enhancement Use %[1]s-%[1]s to read aliases (in YAML format) from standard input. The output from %[1]sgh alias list%[1]s can be used to produce a YAML file containing your aliases, which you can use to import them from one machine to another. Run %[1]sgh help alias list%[1]s to learn more. `, "`"), Example: heredoc.Doc(` # Import aliases from a file $ gh alias import aliases.yml # Import aliases from standard input $ gh alias import - `), Args: func(cmd *cobra.Command, args []string) error { if len(args) > 1 { return cmdutil.FlagErrorf("too many arguments") } if len(args) == 0 && opts.IO.IsStdinTTY() { return cmdutil.FlagErrorf("no filename passed and nothing on STDIN") } return nil }, RunE: func(cmd *cobra.Command, args []string) error { opts.Filename = "-" if len(args) > 0 { opts.Filename = args[0] } opts.validAliasName = shared.ValidAliasNameFunc(cmd) opts.validAliasExpansion = shared.ValidAliasExpansionFunc(cmd) if runF != nil { return runF(opts) } return importRun(opts) }, } cmd.Flags().BoolVar(&opts.OverwriteExisting, "clobber", false, "Overwrite existing aliases of the same name") return cmd } func importRun(opts *ImportOptions) error { cs := opts.IO.ColorScheme() cfg, err := opts.Config() if err != nil { return err } aliasCfg := cfg.Aliases() b, err := cmdutil.ReadFile(opts.Filename, opts.IO.In) if err != nil { return err } aliasMap := map[string]string{} if err = yaml.Unmarshal(b, &aliasMap); err != nil { return err } isTerminal := opts.IO.IsStdoutTTY() if isTerminal { if opts.Filename == "-" { fmt.Fprintf(opts.IO.ErrOut, "- Importing aliases from standard input\n") } else { fmt.Fprintf(opts.IO.ErrOut, "- Importing aliases from file %q\n", opts.Filename) } } var msg strings.Builder for _, alias := range getSortedKeys(aliasMap) { var existingAlias bool if _, err := aliasCfg.Get(alias); err == nil { existingAlias = true } if !opts.validAliasName(alias) { if !existingAlias { msg.WriteString( fmt.Sprintf("%s Could not import alias %s: already a gh command or extension\n", cs.FailureIcon(), cs.Bold(alias), ), ) continue } if existingAlias && !opts.OverwriteExisting { msg.WriteString( fmt.Sprintf("%s Could not import alias %s: name already taken\n", cs.FailureIcon(), cs.Bold(alias), ), ) continue } } expansion := aliasMap[alias] if !opts.validAliasExpansion(expansion) { msg.WriteString( fmt.Sprintf("%s Could not import alias %s: expansion does not correspond to a gh command, extension, or alias\n", cs.FailureIcon(), cs.Bold(alias), ), ) continue } aliasCfg.Add(alias, expansion) if existingAlias && opts.OverwriteExisting { msg.WriteString( fmt.Sprintf("%s Changed alias %s\n", cs.WarningIcon(), cs.Bold(alias), ), ) } else { msg.WriteString( fmt.Sprintf("%s Added alias %s\n", cs.SuccessIcon(), cs.Bold(alias), ), ) } } if err := cfg.Write(); err != nil { return err } if isTerminal { fmt.Fprintln(opts.IO.ErrOut, msg.String()) } return nil } func getSortedKeys(m map[string]string) []string { keys := []string{} for key := range m { keys = append(keys, key) } sort.Strings(keys) return keys }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/alias/set/set_test.go
pkg/cmd/alias/set/set_test.go
package set import ( "bytes" "fmt" "testing" "github.com/cli/cli/v2/internal/config" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/pkg/cmd/alias/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" ) func TestNewCmdSet(t *testing.T) { tests := []struct { name string input string output SetOptions wantErr bool errMsg string }{ { name: "no arguments", input: "", wantErr: true, errMsg: "accepts 2 arg(s), received 0", }, { name: "only one argument", input: "name", wantErr: true, errMsg: "accepts 2 arg(s), received 1", }, { name: "name and expansion", input: "alias-name alias-expansion", output: SetOptions{ Name: "alias-name", Expansion: "alias-expansion", }, }, { name: "shell flag", input: "alias-name alias-expansion --shell", output: SetOptions{ Name: "alias-name", Expansion: "alias-expansion", IsShell: true, }, }, { name: "clobber flag", input: "alias-name alias-expansion --clobber", output: SetOptions{ Name: "alias-name", Expansion: "alias-expansion", OverwriteExisting: 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 *SetOptions cmd := NewCmdSet(f, func(opts *SetOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err = cmd.ExecuteC() if tt.wantErr { assert.EqualError(t, err, tt.errMsg) return } assert.NoError(t, err) assert.Equal(t, tt.output.Name, gotOpts.Name) assert.Equal(t, tt.output.Expansion, gotOpts.Expansion) assert.Equal(t, tt.output.IsShell, gotOpts.IsShell) assert.Equal(t, tt.output.OverwriteExisting, gotOpts.OverwriteExisting) }) } } func TestSetRun(t *testing.T) { tests := []struct { name string tty bool opts *SetOptions stdin string wantExpansion string wantStdout string wantStderr string wantErrMsg string }{ { name: "creates alias tty", tty: true, opts: &SetOptions{ Name: "foo", Expansion: "bar", }, wantExpansion: "bar", wantStderr: "- Creating alias for foo: bar\n✓ Added alias foo\n", }, { name: "creates alias", opts: &SetOptions{ Name: "foo", Expansion: "bar", }, wantExpansion: "bar", }, { name: "creates shell alias tty", tty: true, opts: &SetOptions{ Name: "igrep", Expansion: "!gh issue list | grep", }, wantExpansion: "!gh issue list | grep", wantStderr: "- Creating alias for igrep: !gh issue list | grep\n✓ Added alias igrep\n", }, { name: "creates shell alias", opts: &SetOptions{ Name: "igrep", Expansion: "!gh issue list | grep", }, wantExpansion: "!gh issue list | grep", }, { name: "creates shell alias using flag tty", tty: true, opts: &SetOptions{ Name: "igrep", Expansion: "gh issue list | grep", IsShell: true, }, wantExpansion: "!gh issue list | grep", wantStderr: "- Creating alias for igrep: !gh issue list | grep\n✓ Added alias igrep\n", }, { name: "creates shell alias using flag", opts: &SetOptions{ Name: "igrep", Expansion: "gh issue list | grep", IsShell: true, }, wantExpansion: "!gh issue list | grep", }, { name: "creates alias where expansion has args tty", tty: true, opts: &SetOptions{ Name: "foo", Expansion: "bar baz --author='$1' --label='$2'", }, wantExpansion: "bar baz --author='$1' --label='$2'", wantStderr: "- Creating alias for foo: bar baz --author='$1' --label='$2'\n✓ Added alias foo\n", }, { name: "creates alias where expansion has args", opts: &SetOptions{ Name: "foo", Expansion: "bar baz --author='$1' --label='$2'", }, wantExpansion: "bar baz --author='$1' --label='$2'", }, { name: "creates alias from stdin tty", tty: true, opts: &SetOptions{ Name: "foo", Expansion: "-", }, stdin: `bar baz --author="$1" --label="$2"`, wantExpansion: `bar baz --author="$1" --label="$2"`, wantStderr: "- Creating alias for foo: bar baz --author=\"$1\" --label=\"$2\"\n✓ Added alias foo\n", }, { name: "creates alias from stdin", opts: &SetOptions{ Name: "foo", Expansion: "-", }, stdin: `bar baz --author="$1" --label="$2"`, wantExpansion: `bar baz --author="$1" --label="$2"`, }, { name: "overwrites existing alias tty", tty: true, opts: &SetOptions{ Name: "co", Expansion: "bar", OverwriteExisting: true, }, wantExpansion: "bar", wantStderr: "- Creating alias for co: bar\n! Changed alias co\n", }, { name: "overwrites existing alias", opts: &SetOptions{ Name: "co", Expansion: "bar", OverwriteExisting: true, }, wantExpansion: "bar", }, { name: "fails when alias name is an existing alias tty", tty: true, opts: &SetOptions{ Name: "co", Expansion: "bar", }, wantExpansion: "pr checkout", wantErrMsg: "X Could not create alias co: name already taken, use the --clobber flag to overwrite it", wantStderr: "- Creating alias for co: bar\n", }, { name: "fails when alias name is an existing alias", opts: &SetOptions{ Name: "co", Expansion: "bar", }, wantExpansion: "pr checkout", wantErrMsg: "X Could not create alias co: name already taken, use the --clobber flag to overwrite it", }, { name: "fails when alias expansion is not an existing command tty", tty: true, opts: &SetOptions{ Name: "foo", Expansion: "baz", }, wantErrMsg: "X Could not create alias foo: expansion does not correspond to a gh command, extension, or alias", wantStderr: "- Creating alias for foo: baz\n", }, { name: "fails when alias expansion is not an existing command", opts: &SetOptions{ Name: "foo", Expansion: "baz", }, wantErrMsg: "X Could not create alias foo: expansion does not correspond to a gh command, extension, or alias", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { rootCmd := &cobra.Command{} barCmd := &cobra.Command{Use: "bar"} barCmd.AddCommand(&cobra.Command{Use: "baz"}) rootCmd.AddCommand(barCmd) coCmd := &cobra.Command{Use: "co"} rootCmd.AddCommand(coCmd) tt.opts.validAliasName = shared.ValidAliasNameFunc(rootCmd) tt.opts.validAliasExpansion = shared.ValidAliasExpansionFunc(rootCmd) ios, stdin, stdout, stderr := iostreams.Test() ios.SetStdinTTY(tt.tty) ios.SetStdoutTTY(tt.tty) ios.SetStderrTTY(tt.tty) tt.opts.IO = ios if tt.stdin != "" { fmt.Fprint(stdin, tt.stdin) } cfg := config.NewBlankConfig() cfg.WriteFunc = func() error { return nil } tt.opts.Config = func() (gh.Config, error) { return cfg, nil } err := setRun(tt.opts) if tt.wantErrMsg != "" { assert.EqualError(t, err, tt.wantErrMsg) writeCalls := cfg.WriteCalls() assert.Equal(t, 0, len(writeCalls)) } else { assert.NoError(t, err) writeCalls := cfg.WriteCalls() assert.Equal(t, 1, len(writeCalls)) } ac := cfg.Aliases() expansion, _ := ac.Get(tt.opts.Name) assert.Equal(t, tt.wantExpansion, expansion) assert.Equal(t, tt.wantStdout, stdout.String()) assert.Equal(t, tt.wantStderr, stderr.String()) }) } } func TestGetExpansion(t *testing.T) { tests := []struct { name string want string expansionArg string stdin string }{ { name: "co", want: "pr checkout", expansionArg: "pr checkout", }, { name: "co", want: "pr checkout", expansionArg: "pr checkout", stdin: "api graphql -F name=\"$1\"", }, { name: "stdin", expansionArg: "-", want: "api graphql -F name=\"$1\"", stdin: "api graphql -F name=\"$1\"", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, stdin, _, _ := iostreams.Test() ios.SetStdinTTY(false) _, err := stdin.WriteString(tt.stdin) assert.NoError(t, err) expansion, err := getExpansion(&SetOptions{ Expansion: tt.expansionArg, IO: ios, }) assert.NoError(t, err) assert.Equal(t, expansion, tt.want) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/alias/set/set.go
pkg/cmd/alias/set/set.go
package set import ( "fmt" "io" "strings" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/pkg/cmd/alias/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type SetOptions struct { Config func() (gh.Config, error) IO *iostreams.IOStreams Name string Expansion string IsShell bool OverwriteExisting bool validAliasName func(string) bool validAliasExpansion func(string) bool } func NewCmdSet(f *cmdutil.Factory, runF func(*SetOptions) error) *cobra.Command { opts := &SetOptions{ IO: f.IOStreams, Config: f.Config, } cmd := &cobra.Command{ Use: "set <alias> <expansion>", Short: "Create a shortcut for a gh command", Long: heredoc.Docf(` Define a word that will expand to a full gh command when invoked. The expansion may specify additional arguments and flags. If the expansion includes positional placeholders such as %[1]s$1%[1]s, extra arguments that follow the alias will be inserted appropriately. Otherwise, extra arguments will be appended to the expanded command. Use %[1]s-%[1]s as expansion argument to read the expansion string from standard input. This is useful to avoid quoting issues when defining expansions. If the expansion starts with %[1]s!%[1]s or if %[1]s--shell%[1]s was given, the expansion is a shell expression that will be evaluated through the %[1]ssh%[1]s interpreter when the alias is invoked. This allows for chaining multiple commands via piping and redirection. `, "`"), Example: heredoc.Doc(` # Note: Command Prompt on Windows requires using double quotes for arguments $ gh alias set pv 'pr view' $ gh pv -w 123 #=> gh pr view -w 123 $ gh alias set bugs 'issue list --label=bugs' $ gh bugs $ gh alias set homework 'issue list --assignee @me' $ gh homework $ gh alias set 'issue mine' 'issue list --mention @me' $ gh issue mine $ gh alias set epicsBy 'issue list --author="$1" --label="epic"' $ gh epicsBy vilmibm #=> gh issue list --author="vilmibm" --label="epic" $ gh alias set --shell igrep 'gh issue list --label="$1" | grep "$2"' $ gh igrep epic foo #=> gh issue list --label="epic" | grep "foo" `), Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { opts.Name = args[0] opts.Expansion = args[1] opts.validAliasName = shared.ValidAliasNameFunc(cmd) opts.validAliasExpansion = shared.ValidAliasExpansionFunc(cmd) if runF != nil { return runF(opts) } return setRun(opts) }, } cmd.Flags().BoolVarP(&opts.IsShell, "shell", "s", false, "Declare an alias to be passed through a shell interpreter") cmd.Flags().BoolVar(&opts.OverwriteExisting, "clobber", false, "Overwrite existing aliases of the same name") return cmd } func setRun(opts *SetOptions) error { cs := opts.IO.ColorScheme() cfg, err := opts.Config() if err != nil { return err } aliasCfg := cfg.Aliases() expansion, err := getExpansion(opts) if err != nil { return fmt.Errorf("did not understand expansion: %w", err) } if opts.IsShell && !strings.HasPrefix(expansion, "!") { expansion = "!" + expansion } isTerminal := opts.IO.IsStdoutTTY() if isTerminal { fmt.Fprintf(opts.IO.ErrOut, "- Creating alias for %s: %s\n", cs.Bold(opts.Name), cs.Bold(expansion)) } var existingAlias bool if _, err := aliasCfg.Get(opts.Name); err == nil { existingAlias = true } if !opts.validAliasName(opts.Name) { if !existingAlias { return fmt.Errorf("%s Could not create alias %s: already a gh command or extension", cs.FailureIcon(), cs.Bold(opts.Name)) } if existingAlias && !opts.OverwriteExisting { return fmt.Errorf("%s Could not create alias %s: name already taken, use the --clobber flag to overwrite it", cs.FailureIcon(), cs.Bold(opts.Name), ) } } if !opts.validAliasExpansion(expansion) { return fmt.Errorf("%s Could not create alias %s: expansion does not correspond to a gh command, extension, or alias", cs.FailureIcon(), cs.Bold(opts.Name)) } aliasCfg.Add(opts.Name, expansion) err = cfg.Write() if err != nil { return err } successMsg := fmt.Sprintf("%s Added alias %s", cs.SuccessIcon(), cs.Bold(opts.Name)) if existingAlias && opts.OverwriteExisting { successMsg = fmt.Sprintf("%s Changed alias %s", cs.WarningIcon(), cs.Bold(opts.Name)) } if isTerminal { fmt.Fprintln(opts.IO.ErrOut, successMsg) } return nil } func getExpansion(opts *SetOptions) (string, error) { if opts.Expansion == "-" { stdin, err := io.ReadAll(opts.IO.In) if err != nil { return "", fmt.Errorf("failed to read from STDIN: %w", err) } return string(stdin), nil } return opts.Expansion, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/repo.go
pkg/cmd/repo/repo.go
package repo import ( "github.com/MakeNowJust/heredoc" repoArchiveCmd "github.com/cli/cli/v2/pkg/cmd/repo/archive" repoAutolinkCmd "github.com/cli/cli/v2/pkg/cmd/repo/autolink" repoCloneCmd "github.com/cli/cli/v2/pkg/cmd/repo/clone" repoCreateCmd "github.com/cli/cli/v2/pkg/cmd/repo/create" creditsCmd "github.com/cli/cli/v2/pkg/cmd/repo/credits" repoDeleteCmd "github.com/cli/cli/v2/pkg/cmd/repo/delete" deployKeyCmd "github.com/cli/cli/v2/pkg/cmd/repo/deploy-key" repoEditCmd "github.com/cli/cli/v2/pkg/cmd/repo/edit" repoForkCmd "github.com/cli/cli/v2/pkg/cmd/repo/fork" gardenCmd "github.com/cli/cli/v2/pkg/cmd/repo/garden" gitIgnoreCmd "github.com/cli/cli/v2/pkg/cmd/repo/gitignore" licenseCmd "github.com/cli/cli/v2/pkg/cmd/repo/license" repoListCmd "github.com/cli/cli/v2/pkg/cmd/repo/list" repoRenameCmd "github.com/cli/cli/v2/pkg/cmd/repo/rename" repoDefaultCmd "github.com/cli/cli/v2/pkg/cmd/repo/setdefault" repoSyncCmd "github.com/cli/cli/v2/pkg/cmd/repo/sync" repoUnarchiveCmd "github.com/cli/cli/v2/pkg/cmd/repo/unarchive" repoViewCmd "github.com/cli/cli/v2/pkg/cmd/repo/view" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/spf13/cobra" ) func NewCmdRepo(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "repo <command>", Short: "Manage repositories", Long: `Work with GitHub repositories.`, Example: heredoc.Doc(` $ gh repo create $ gh repo clone cli/cli $ gh repo view --web `), Annotations: map[string]string{ "help:arguments": heredoc.Doc(` A repository can be supplied as an argument in any of the following formats: - "OWNER/REPO" - by URL, e.g. "https://github.com/OWNER/REPO" `), }, GroupID: "core", } cmdutil.AddGroup(cmd, "General commands", repoListCmd.NewCmdList(f, nil), repoCreateCmd.NewCmdCreate(f, nil), ) cmdutil.AddGroup(cmd, "Targeted commands", repoViewCmd.NewCmdView(f, nil), repoCloneCmd.NewCmdClone(f, nil), repoForkCmd.NewCmdFork(f, nil), repoDefaultCmd.NewCmdSetDefault(f, nil), repoSyncCmd.NewCmdSync(f, nil), repoEditCmd.NewCmdEdit(f, nil), deployKeyCmd.NewCmdDeployKey(f), licenseCmd.NewCmdLicense(f), gitIgnoreCmd.NewCmdGitIgnore(f), repoRenameCmd.NewCmdRename(f, nil), repoArchiveCmd.NewCmdArchive(f, nil), repoUnarchiveCmd.NewCmdUnarchive(f, nil), repoDeleteCmd.NewCmdDelete(f, nil), creditsCmd.NewCmdRepoCredits(f, nil), gardenCmd.NewCmdGarden(f, nil), repoAutolinkCmd.NewCmdAutolink(f), ) return cmd }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/credits/credits.go
pkg/cmd/repo/credits/credits.go
package credits import ( "bytes" "fmt" "math" "math/rand" "net/http" "os" "os/exec" "runtime" "strings" "time" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/utils" "github.com/spf13/cobra" ) type CreditsOptions struct { HttpClient func() (*http.Client, error) BaseRepo func() (ghrepo.Interface, error) IO *iostreams.IOStreams Repository string Static bool } func NewCmdCredits(f *cmdutil.Factory, runF func(*CreditsOptions) error) *cobra.Command { opts := &CreditsOptions{ HttpClient: f.HttpClient, IO: f.IOStreams, BaseRepo: f.BaseRepo, Repository: "cli/cli", } cmd := &cobra.Command{ Use: "credits", Short: "View credits for this tool", Long: `View animated credits for gh, the tool you are currently using :)`, Example: heredoc.Doc(` # See a credits animation for this project $ gh credits # Display a non-animated thank you $ gh credits -s # Just print the contributors, one per line $ gh credits | cat `), Args: cobra.ExactArgs(0), RunE: func(cmd *cobra.Command, args []string) error { if runF != nil { return runF(opts) } return creditsRun(opts) }, Hidden: true, } cmd.Flags().BoolVarP(&opts.Static, "static", "s", false, "Print a static version of the credits") return cmd } func NewCmdRepoCredits(f *cmdutil.Factory, runF func(*CreditsOptions) error) *cobra.Command { opts := &CreditsOptions{ HttpClient: f.HttpClient, BaseRepo: f.BaseRepo, IO: f.IOStreams, } cmd := &cobra.Command{ Use: "credits [<repository>]", Short: "View credits for a repository", Example: heredoc.Doc(` # View credits for the current repository $ gh repo credits # View credits for a specific repository $ gh repo credits cool/repo # Print a non-animated thank you $ gh repo credits -s # Pipe to just print the contributors, one per line $ gh repo credits | cat `), Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { if len(args) > 0 { opts.Repository = args[0] } if runF != nil { return runF(opts) } return creditsRun(opts) }, Hidden: true, } cmd.Flags().BoolVarP(&opts.Static, "static", "s", false, "Print a static version of the credits") return cmd } func creditsRun(opts *CreditsOptions) error { isWindows := runtime.GOOS == "windows" httpClient, err := opts.HttpClient() if err != nil { return err } client := api.NewClientFromHTTP(httpClient) var baseRepo ghrepo.Interface if opts.Repository == "" { baseRepo, err = opts.BaseRepo() if err != nil { return err } } else { baseRepo, err = ghrepo.FromFullName(opts.Repository) if err != nil { return err } } type Contributor struct { Login string Type string } type Result []Contributor result := Result{} body := bytes.NewBufferString("") path := fmt.Sprintf("repos/%s/%s/contributors", baseRepo.RepoOwner(), baseRepo.RepoName()) err = client.REST(baseRepo.RepoHost(), "GET", path, body, &result) if err != nil { return err } isTTY := opts.IO.IsStdoutTTY() static := opts.Static || isWindows out := opts.IO.Out cs := opts.IO.ColorScheme() if isTTY && static { fmt.Fprintln(out, "THANK YOU CONTRIBUTORS!!! <3") fmt.Fprintln(out, "") } logins := []string{} for x, c := range result { if c.Type != "User" { continue } if isTTY && !static { logins = append(logins, cs.ColorFromString(getColor(x))(c.Login)) } else { fmt.Fprintf(out, "%s\n", c.Login) } } if !isTTY || static { return nil } r := rand.New(rand.NewSource(time.Now().UnixNano())) lines := []string{} thankLines := strings.Split(thankYou, "\n") for x, tl := range thankLines { lines = append(lines, cs.ColorFromString(getColor(x))(tl)) } lines = append(lines, "") lines = append(lines, logins...) lines = append(lines, "( <3 press ctrl-c to quit <3 )") termWidth, termHeight, err := utils.TerminalSize(out) if err != nil { return err } margin := termWidth / 3 starLinesLeft := []string{} for x := 0; x < len(lines); x++ { starLinesLeft = append(starLinesLeft, starLine(r, margin)) } starLinesRight := []string{} for x := 0; x < len(lines); x++ { lineWidth := termWidth - (margin + len(lines[x])) starLinesRight = append(starLinesRight, starLine(r, lineWidth)) } loop := true startx := termHeight - 1 li := 0 for loop { clear() for x := 0; x < termHeight; x++ { if x == startx || startx < 0 { starty := 0 if startx < 0 { starty = int(math.Abs(float64(startx))) } for y := starty; y < li+1; y++ { if y >= len(lines) { continue } starLineLeft := starLinesLeft[y] starLinesLeft[y] = twinkle(starLineLeft) starLineRight := starLinesRight[y] starLinesRight[y] = twinkle(starLineRight) fmt.Fprintf(out, "%s %s %s\n", starLineLeft, lines[y], starLineRight) } li += 1 x += li } else { fmt.Fprintf(out, "\n") } } if li < len(lines) { startx -= 1 } time.Sleep(300 * time.Millisecond) } return nil } func starLine(r *rand.Rand, width int) string { line := "" starChance := 0.1 for y := 0; y < width; y++ { chance := r.Float64() if chance <= starChance { charRoll := r.Float64() switch { case charRoll < 0.3: line += "." case charRoll > 0.3 && charRoll < 0.6: line += "+" default: line += "*" } } else { line += " " } } return line } func twinkle(starLine string) string { starLine = strings.ReplaceAll(starLine, ".", "P") starLine = strings.ReplaceAll(starLine, "+", "A") starLine = strings.ReplaceAll(starLine, "*", ".") starLine = strings.ReplaceAll(starLine, "P", "+") starLine = strings.ReplaceAll(starLine, "A", "*") return starLine } func getColor(x int) string { rainbow := []string{ "magenta", "red", "yellow", "green", "cyan", "blue", } ix := x % len(rainbow) return rainbow[ix] } func clear() { // on windows we'd do cmd := exec.Command("cmd", "/c", "cls"); unfortunately the draw speed is so // slow that the animation is very jerky, flashy, and painful to look at. cmd := exec.Command("clear") cmd.Stdout = os.Stdout _ = cmd.Run() } var thankYou = ` _ _ | | | | _|_ | | __, _ _ | | __ | |/ \ / | / |/ | |/_) | | / \_| | |_/| |_/\_/|_/ | |_/| \_/ \_/|/\__/ \_/|_/ /| \| _ o | | | __ __ _ _ _|_ ,_ | | _|_ __ ,_ , | / / \_/ |/ | | / | | |/ \_| | | / \_/ | / \_| \___/\__/ | |_/|_/ |_/|_/\_/ \_/|_/|_/\__/ |_/ \/ o `
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/autolink/autolink.go
pkg/cmd/repo/autolink/autolink.go
package autolink import ( "github.com/MakeNowJust/heredoc" cmdCreate "github.com/cli/cli/v2/pkg/cmd/repo/autolink/create" cmdDelete "github.com/cli/cli/v2/pkg/cmd/repo/autolink/delete" cmdList "github.com/cli/cli/v2/pkg/cmd/repo/autolink/list" cmdView "github.com/cli/cli/v2/pkg/cmd/repo/autolink/view" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/spf13/cobra" ) func NewCmdAutolink(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "autolink <command>", Short: "Manage autolink references", Long: heredoc.Docf(` Autolinks link issues, pull requests, commit messages, and release descriptions to external third-party services. Autolinks require %[1]sadmin%[1]s role to view or manage. For more information, see <https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/managing-repository-settings/configuring-autolinks-to-reference-external-resources> `, "`"), } cmdutil.EnableRepoOverride(cmd, f) cmd.AddCommand(cmdList.NewCmdList(f, nil)) cmd.AddCommand(cmdCreate.NewCmdCreate(f, nil)) cmd.AddCommand(cmdView.NewCmdView(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/repo/autolink/delete/delete.go
pkg/cmd/repo/autolink/delete/delete.go
package delete import ( "fmt" "github.com/cli/cli/v2/internal/browser" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/pkg/cmd/repo/autolink/view" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type deleteOptions struct { BaseRepo func() (ghrepo.Interface, error) Browser browser.Browser AutolinkDeleteClient AutolinkDeleteClient AutolinkViewClient view.AutolinkViewClient IO *iostreams.IOStreams ID string Confirmed bool Prompter prompter.Prompter } type AutolinkDeleteClient interface { Delete(repo ghrepo.Interface, id string) error } func NewCmdDelete(f *cmdutil.Factory, runF func(*deleteOptions) error) *cobra.Command { opts := &deleteOptions{ Browser: f.Browser, IO: f.IOStreams, Prompter: f.Prompter, } cmd := &cobra.Command{ Use: "delete <id>", Short: "Delete an autolink reference", Long: "Delete an autolink reference for a repository.", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.BaseRepo = f.BaseRepo httpClient, err := f.HttpClient() if err != nil { return err } opts.AutolinkDeleteClient = &AutolinkDeleter{HTTPClient: httpClient} opts.AutolinkViewClient = &view.AutolinkViewer{HTTPClient: httpClient} opts.ID = 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, "yes", false, "Confirm deletion without prompting") return cmd } func deleteRun(opts *deleteOptions) error { repo, err := opts.BaseRepo() if err != nil { return err } out := opts.IO.Out cs := opts.IO.ColorScheme() autolink, err := opts.AutolinkViewClient.View(repo, opts.ID) if err != nil { return fmt.Errorf("%s %w", cs.Red("error deleting autolink:"), err) } if opts.IO.CanPrompt() && !opts.Confirmed { fmt.Fprintf(out, "Autolink %s has key prefix %s.\n", cs.Cyan(opts.ID), autolink.KeyPrefix) err := opts.Prompter.ConfirmDeletion(autolink.KeyPrefix) if err != nil { return err } } err = opts.AutolinkDeleteClient.Delete(repo, opts.ID) if err != nil { return err } if opts.IO.IsStdoutTTY() { fmt.Fprintf(out, "%s Autolink %s deleted from %s\n", cs.SuccessIcon(), cs.Cyan(opts.ID), cs.Bold(ghrepo.FullName(repo))) } return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/autolink/delete/delete_test.go
pkg/cmd/repo/autolink/delete/delete_test.go
package delete import ( "bytes" "errors" "net/http" "testing" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/browser" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/pkg/cmd/repo/autolink/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 TestNewCmdDelete(t *testing.T) { tests := []struct { name string input string output deleteOptions isTTY bool wantErr bool errMsg string }{ { name: "no argument", input: "", isTTY: true, wantErr: true, errMsg: "accepts 1 arg(s), received 0", }, { name: "id provided", input: "123", isTTY: true, output: deleteOptions{ID: "123"}, }, { name: "yes flag", input: "123 --yes", isTTY: true, output: deleteOptions{ID: "123", Confirmed: true}, }, { name: "non-TTY", input: "123 --yes", isTTY: false, output: deleteOptions{ID: "123", Confirmed: true}, }, { name: "non-TTY missing yes flag", input: "123", isTTY: false, wantErr: true, errMsg: "--yes required when not running interactively", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() ios.SetStdinTTY(tt.isTTY) ios.SetStdoutTTY(tt.isTTY) ios.SetStderrTTY(tt.isTTY) f := &cmdutil.Factory{ IOStreams: ios, } f.HttpClient = func() (*http.Client, error) { return &http.Client{}, nil } argv, err := shlex.Split(tt.input) require.NoError(t, err) var gotOpts *deleteOptions cmd := NewCmdDelete(f, func(opts *deleteOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err = cmd.ExecuteC() if tt.wantErr { require.EqualError(t, err, tt.errMsg) } else { require.NoError(t, err) assert.Equal(t, tt.output.ID, gotOpts.ID) assert.Equal(t, tt.output.Confirmed, gotOpts.Confirmed) } }) } } type stubAutolinkDeleter struct { err error } func (d *stubAutolinkDeleter) Delete(repo ghrepo.Interface, id string) error { return d.err } type stubAutolinkViewer struct { autolink *shared.Autolink err error } func (g stubAutolinkViewer) View(repo ghrepo.Interface, id string) (*shared.Autolink, error) { return g.autolink, g.err } var errTestPrompt = errors.New("prompt error") var errTestAutolinkClientView = errors.New("autolink client view error") var errTestAutolinkClientDelete = errors.New("autolink client delete error") func TestDeleteRun(t *testing.T) { tests := []struct { name string opts *deleteOptions isTTY bool stubDeleter stubAutolinkDeleter stubViewer stubAutolinkViewer prompterStubs func(*prompter.PrompterMock) wantStdout string expectedErr error expectedErrMsg string }{ { name: "delete", opts: &deleteOptions{ ID: "123", }, isTTY: true, stubViewer: stubAutolinkViewer{ autolink: &shared.Autolink{ ID: 123, KeyPrefix: "TICKET-", URLTemplate: "https://example.com/TICKET?query=<num>", IsAlphanumeric: true, }, }, stubDeleter: stubAutolinkDeleter{ err: nil, }, prompterStubs: func(pm *prompter.PrompterMock) { pm.ConfirmDeletionFunc = func(_ string) error { return nil } }, wantStdout: heredoc.Doc(` Autolink 123 has key prefix TICKET-. ✓ Autolink 123 deleted from OWNER/REPO `), }, { name: "delete with confirm flag", opts: &deleteOptions{ ID: "123", Confirmed: true, }, isTTY: true, stubViewer: stubAutolinkViewer{ autolink: &shared.Autolink{ ID: 123, KeyPrefix: "TICKET-", URLTemplate: "https://example.com/TICKET?query=<num>", IsAlphanumeric: true, }, }, stubDeleter: stubAutolinkDeleter{}, wantStdout: "✓ Autolink 123 deleted from OWNER/REPO\n", }, { name: "confirmation fails", opts: &deleteOptions{ ID: "123", }, isTTY: true, stubViewer: stubAutolinkViewer{ autolink: &shared.Autolink{ ID: 123, KeyPrefix: "TICKET-", URLTemplate: "https://example.com/TICKET?query=<num>", IsAlphanumeric: true, }, }, stubDeleter: stubAutolinkDeleter{}, prompterStubs: func(pm *prompter.PrompterMock) { pm.ConfirmDeletionFunc = func(_ string) error { return errTestPrompt } }, expectedErr: errTestPrompt, expectedErrMsg: errTestPrompt.Error(), wantStdout: "Autolink 123 has key prefix TICKET-.\n", }, { name: "view error", opts: &deleteOptions{ ID: "123", }, isTTY: true, stubViewer: stubAutolinkViewer{ err: errTestAutolinkClientView, }, stubDeleter: stubAutolinkDeleter{}, expectedErr: errTestAutolinkClientView, expectedErrMsg: "error deleting autolink: autolink client view error", }, { name: "delete error", opts: &deleteOptions{ ID: "123", }, isTTY: true, stubViewer: stubAutolinkViewer{ autolink: &shared.Autolink{ ID: 123, KeyPrefix: "TICKET-", URLTemplate: "https://example.com/TICKET?query=<num>", IsAlphanumeric: true, }, }, stubDeleter: stubAutolinkDeleter{ err: errTestAutolinkClientDelete, }, prompterStubs: func(pm *prompter.PrompterMock) { pm.ConfirmDeletionFunc = func(_ string) error { return nil } }, expectedErr: errTestAutolinkClientDelete, expectedErrMsg: errTestAutolinkClientDelete.Error(), wantStdout: "Autolink 123 has key prefix TICKET-.\n", }, { name: "no TTY", opts: &deleteOptions{ ID: "123", Confirmed: true, }, isTTY: false, stubViewer: stubAutolinkViewer{ autolink: &shared.Autolink{ ID: 123, KeyPrefix: "TICKET-", URLTemplate: "https://example.com/TICKET?query=<num>", IsAlphanumeric: true, }}, stubDeleter: stubAutolinkDeleter{}, wantStdout: "", }, { name: "no TTY view error", opts: &deleteOptions{ ID: "123", }, isTTY: false, stubViewer: stubAutolinkViewer{ err: errTestAutolinkClientView, }, stubDeleter: stubAutolinkDeleter{}, expectedErr: errTestAutolinkClientView, expectedErrMsg: "error deleting autolink: autolink client view error", }, { name: "no TTY delete error", opts: &deleteOptions{ ID: "123", Confirmed: true, }, isTTY: false, stubViewer: stubAutolinkViewer{ autolink: &shared.Autolink{ ID: 123, KeyPrefix: "TICKET-", URLTemplate: "https://example.com/TICKET?query=<num>", IsAlphanumeric: true, }, }, stubDeleter: stubAutolinkDeleter{ err: errTestAutolinkClientDelete, }, expectedErr: errTestAutolinkClientDelete, expectedErrMsg: errTestAutolinkClientDelete.Error(), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, stdout, _ := iostreams.Test() ios.SetStdinTTY(tt.isTTY) ios.SetStdoutTTY(tt.isTTY) opts := tt.opts opts.IO = ios opts.Browser = &browser.Stub{} opts.IO = ios opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil } opts.AutolinkDeleteClient = &tt.stubDeleter opts.AutolinkViewClient = &tt.stubViewer pm := &prompter.PrompterMock{} if tt.prompterStubs != nil { tt.prompterStubs(pm) } tt.opts.Prompter = pm err := deleteRun(opts) if tt.expectedErr != nil { require.Error(t, err, "expected error but got none") assert.ErrorIs(t, err, tt.expectedErr, "unexpected error") assert.Equal(t, tt.expectedErrMsg, err.Error(), "unexpected error message") } else { require.NoError(t, err) } assert.Equal(t, tt.wantStdout, stdout.String(), "unexpected stdout") }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/autolink/delete/http_test.go
pkg/cmd/repo/autolink/delete/http_test.go
package delete import ( "fmt" "net/http" "testing" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/go-gh/v2/pkg/api" "github.com/stretchr/testify/require" ) func TestAutolinkDeleter_Delete(t *testing.T) { repo := ghrepo.New("OWNER", "REPO") tests := []struct { name string id string stubStatus int stubResp any expectErr bool expectedErrMsg string }{ { name: "204 successful delete", id: "123", stubStatus: http.StatusNoContent, }, { name: "404 repo or autolink not found", id: "123", stubStatus: http.StatusNotFound, expectErr: true, expectedErrMsg: "error deleting autolink: HTTP 404: Perhaps you are missing admin rights to the repository? (https://api.github.com/repos/OWNER/REPO/autolinks/123)", }, { name: "500 unexpected error", id: "123", stubResp: api.HTTPError{ Message: "arbitrary error", }, stubStatus: http.StatusInternalServerError, expectErr: true, expectedErrMsg: "HTTP 500: arbitrary error (https://api.github.com/repos/OWNER/REPO/autolinks/123)", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { reg := &httpmock.Registry{} reg.Register( httpmock.REST( http.MethodDelete, fmt.Sprintf("repos/%s/%s/autolinks/%s", repo.RepoOwner(), repo.RepoName(), tt.id), ), httpmock.StatusJSONResponse(tt.stubStatus, tt.stubResp), ) defer reg.Verify(t) autolinkDeleter := &AutolinkDeleter{ HTTPClient: &http.Client{Transport: reg}, } err := autolinkDeleter.Delete(repo, tt.id) if tt.expectErr { require.EqualError(t, err, tt.expectedErrMsg) } else { 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/repo/autolink/delete/http.go
pkg/cmd/repo/autolink/delete/http.go
package delete import ( "fmt" "net/http" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghinstance" "github.com/cli/cli/v2/internal/ghrepo" ) type AutolinkDeleter struct { HTTPClient *http.Client } func (a *AutolinkDeleter) Delete(repo ghrepo.Interface, id string) error { path := fmt.Sprintf("repos/%s/%s/autolinks/%s", repo.RepoOwner(), repo.RepoName(), id) url := ghinstance.RESTPrefix(repo.RepoHost()) + path req, err := http.NewRequest(http.MethodDelete, url, nil) if err != nil { return err } resp, err := a.HTTPClient.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode == http.StatusNotFound { return fmt.Errorf("error deleting autolink: HTTP 404: Perhaps you are missing admin rights to the repository? (https://api.github.com/%s)", path) } else if resp.StatusCode > 299 { return api.HandleHTTPError(resp) } return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/autolink/list/list_test.go
pkg/cmd/repo/autolink/list/list_test.go
package list import ( "bytes" "net/http" "testing" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/browser" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/repo/autolink/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/pkg/jsonfieldstest" "github.com/google/shlex" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestJSONFields(t *testing.T) { jsonfieldstest.ExpectCommandToSupportJSONFields(t, NewCmdList, []string{ "id", "isAlphanumeric", "keyPrefix", "urlTemplate", }) } func TestNewCmdList(t *testing.T) { tests := []struct { name string input string output listOptions wantErr bool wantExporter bool errMsg string }{ { name: "no argument", input: "", output: listOptions{}, }, { name: "web flag", input: "--web", output: listOptions{WebMode: true}, }, { name: "json flag", input: "--json id", output: listOptions{}, wantExporter: true, }, { name: "invalid json flag", input: "--json invalid", output: listOptions{}, wantErr: true, errMsg: "Unknown JSON field: \"invalid\"\nAvailable fields:\n id\n isAlphanumeric\n keyPrefix\n urlTemplate", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() f := &cmdutil.Factory{ IOStreams: ios, } f.HttpClient = func() (*http.Client, error) { return &http.Client{}, nil } argv, err := shlex.Split(tt.input) require.NoError(t, err) var gotOpts *listOptions cmd := NewCmdList(f, func(opts *listOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err = cmd.ExecuteC() if tt.wantErr { require.EqualError(t, err, tt.errMsg) } else { require.NoError(t, err) assert.Equal(t, tt.output.WebMode, gotOpts.WebMode) assert.Equal(t, tt.wantExporter, gotOpts.Exporter != nil) } }) } } type stubAutolinkLister struct { autolinks []shared.Autolink err error } func (g stubAutolinkLister) List(repo ghrepo.Interface) ([]shared.Autolink, error) { return g.autolinks, g.err } type testAutolinkClientListError struct{} func (e testAutolinkClientListError) Error() string { return "autolink client list error" } func TestListRun(t *testing.T) { tests := []struct { name string opts *listOptions isTTY bool stubLister stubAutolinkLister expectedErr error wantStdout string wantStderr string }{ { name: "list tty", opts: &listOptions{}, isTTY: true, stubLister: stubAutolinkLister{ autolinks: []shared.Autolink{ { ID: 1, KeyPrefix: "TICKET-", URLTemplate: "https://example.com/TICKET?query=<num>", IsAlphanumeric: true, }, { ID: 2, KeyPrefix: "STORY-", URLTemplate: "https://example.com/STORY?id=<num>", IsAlphanumeric: false, }, }, }, wantStdout: heredoc.Doc(` Showing 2 autolink references in OWNER/REPO ID KEY PREFIX URL TEMPLATE ALPHANUMERIC 1 TICKET- https://example.com/TICKET?query=<num> true 2 STORY- https://example.com/STORY?id=<num> false `), wantStderr: "", }, { name: "list json", opts: &listOptions{ Exporter: func() cmdutil.Exporter { exporter := cmdutil.NewJSONExporter() exporter.SetFields([]string{"id"}) return exporter }(), }, isTTY: true, stubLister: stubAutolinkLister{ autolinks: []shared.Autolink{ { ID: 1, KeyPrefix: "TICKET-", URLTemplate: "https://example.com/TICKET?query=<num>", IsAlphanumeric: true, }, { ID: 2, KeyPrefix: "STORY-", URLTemplate: "https://example.com/STORY?id=<num>", IsAlphanumeric: false, }, }, }, wantStdout: "[{\"id\":1},{\"id\":2}]\n", wantStderr: "", }, { name: "list non-tty", opts: &listOptions{}, isTTY: false, stubLister: stubAutolinkLister{ autolinks: []shared.Autolink{ { ID: 1, KeyPrefix: "TICKET-", URLTemplate: "https://example.com/TICKET?query=<num>", IsAlphanumeric: true, }, { ID: 2, KeyPrefix: "STORY-", URLTemplate: "https://example.com/STORY?id=<num>", IsAlphanumeric: false, }, }, }, wantStdout: heredoc.Doc(` 1 TICKET- https://example.com/TICKET?query=<num> true 2 STORY- https://example.com/STORY?id=<num> false `), wantStderr: "", }, { name: "no results", opts: &listOptions{}, isTTY: true, stubLister: stubAutolinkLister{ autolinks: []shared.Autolink{}, }, expectedErr: cmdutil.NewNoResultsError("no autolinks found in OWNER/REPO"), wantStderr: "", }, { name: "client error", opts: &listOptions{}, isTTY: true, stubLister: stubAutolinkLister{ autolinks: []shared.Autolink{}, err: testAutolinkClientListError{}, }, expectedErr: testAutolinkClientListError{}, wantStderr: "", }, { name: "web mode", isTTY: true, opts: &listOptions{WebMode: true}, wantStderr: "Opening https://github.com/OWNER/REPO/settings/key_links in your browser.\n", }, } 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.Browser = &browser.Stub{} opts.IO = ios opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil } opts.AutolinkClient = &tt.stubLister err := listRun(opts) if tt.expectedErr != nil { require.Error(t, err) require.ErrorIs(t, err, tt.expectedErr) } else { require.NoError(t, err) assert.Equal(t, tt.wantStdout, stdout.String()) } if tt.wantStderr != "" { 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/autolink/list/list.go
pkg/cmd/repo/autolink/list/list.go
package list import ( "fmt" "strconv" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/browser" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/tableprinter" "github.com/cli/cli/v2/internal/text" "github.com/cli/cli/v2/pkg/cmd/repo/autolink/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type listOptions struct { BaseRepo func() (ghrepo.Interface, error) Browser browser.Browser AutolinkClient AutolinkListClient IO *iostreams.IOStreams Exporter cmdutil.Exporter WebMode bool } type AutolinkListClient interface { List(repo ghrepo.Interface) ([]shared.Autolink, error) } func NewCmdList(f *cmdutil.Factory, runF func(*listOptions) error) *cobra.Command { opts := &listOptions{ Browser: f.Browser, IO: f.IOStreams, } cmd := &cobra.Command{ Use: "list", Short: "List autolink references for a GitHub repository", Long: heredoc.Doc(` Gets all autolink references that are configured for a repository. Information about autolinks is only available to repository administrators. `), Aliases: []string{"ls"}, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { opts.BaseRepo = f.BaseRepo httpClient, err := f.HttpClient() if err != nil { return err } opts.AutolinkClient = &AutolinkLister{HTTPClient: httpClient} if runF != nil { return runF(opts) } return listRun(opts) }, } cmd.Flags().BoolVarP(&opts.WebMode, "web", "w", false, "List autolink references in the web browser") cmdutil.AddJSONFlags(cmd, &opts.Exporter, shared.AutolinkFields) return cmd } func listRun(opts *listOptions) error { repo, err := opts.BaseRepo() if err != nil { return err } if opts.WebMode { autolinksListURL := ghrepo.GenerateRepoURL(repo, "settings/key_links") if opts.IO.IsStdoutTTY() { fmt.Fprintf(opts.IO.ErrOut, "Opening %s in your browser.\n", text.DisplayURL(autolinksListURL)) } return opts.Browser.Browse(autolinksListURL) } autolinks, err := opts.AutolinkClient.List(repo) if err != nil { return err } cs := opts.IO.ColorScheme() if len(autolinks) == 0 { return cmdutil.NewNoResultsError( fmt.Sprintf( "no autolinks found in %s", cs.Bold(ghrepo.FullName(repo))), ) } if opts.Exporter != nil { return opts.Exporter.Write(opts.IO, autolinks) } if opts.IO.IsStdoutTTY() { title := fmt.Sprintf( "Showing %s in %s", text.Pluralize(len(autolinks), "autolink reference"), cs.Bold(ghrepo.FullName(repo)), ) fmt.Fprintf(opts.IO.Out, "\n%s\n\n", title) } tp := tableprinter.New(opts.IO, tableprinter.WithHeader("ID", "KEY PREFIX", "URL TEMPLATE", "ALPHANUMERIC")) for _, autolink := range autolinks { tp.AddField(cs.Cyanf("%d", autolink.ID)) tp.AddField(autolink.KeyPrefix) tp.AddField(autolink.URLTemplate) tp.AddField(strconv.FormatBool(autolink.IsAlphanumeric)) tp.EndRow() } return tp.Render() }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/autolink/list/http_test.go
pkg/cmd/repo/autolink/list/http_test.go
package list import ( "fmt" "net/http" "testing" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/repo/autolink/shared" "github.com/cli/cli/v2/pkg/httpmock" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestAutolinkLister_List(t *testing.T) { tests := []struct { name string repo ghrepo.Interface resp []shared.Autolink status int }{ { name: "no autolinks", repo: ghrepo.New("OWNER", "REPO"), resp: []shared.Autolink{}, status: http.StatusOK, }, { name: "two autolinks", repo: ghrepo.New("OWNER", "REPO"), resp: []shared.Autolink{ { ID: 1, IsAlphanumeric: true, KeyPrefix: "key", URLTemplate: "https://example.com", }, { ID: 2, IsAlphanumeric: false, KeyPrefix: "key2", URLTemplate: "https://example2.com", }, }, status: http.StatusOK, }, { name: "http error", repo: ghrepo.New("OWNER", "REPO"), status: http.StatusNotFound, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { reg := &httpmock.Registry{} reg.Register( httpmock.REST(http.MethodGet, fmt.Sprintf("repos/%s/%s/autolinks", tt.repo.RepoOwner(), tt.repo.RepoName())), httpmock.StatusJSONResponse(tt.status, tt.resp), ) defer reg.Verify(t) autolinkLister := &AutolinkLister{ HTTPClient: &http.Client{Transport: reg}, } autolinks, err := autolinkLister.List(tt.repo) if tt.status == http.StatusNotFound { require.Error(t, err) assert.Equal(t, "error getting autolinks: HTTP 404: Perhaps you are missing admin rights to the repository? (https://api.github.com/repos/OWNER/REPO/autolinks)", err.Error()) } else { require.NoError(t, err) assert.Equal(t, tt.resp, autolinks) } }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/autolink/list/http.go
pkg/cmd/repo/autolink/list/http.go
package list import ( "encoding/json" "fmt" "net/http" "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/repo/autolink/shared" ) type AutolinkLister struct { HTTPClient *http.Client } func (a *AutolinkLister) List(repo ghrepo.Interface) ([]shared.Autolink, error) { path := fmt.Sprintf("repos/%s/%s/autolinks", repo.RepoOwner(), repo.RepoName()) url := ghinstance.RESTPrefix(repo.RepoHost()) + path req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return nil, err } resp, err := a.HTTPClient.Do(req) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode == http.StatusNotFound { return nil, fmt.Errorf("error getting autolinks: HTTP 404: Perhaps you are missing admin rights to the repository? (https://api.github.com/%s)", path) } else if resp.StatusCode > 299 { return nil, api.HandleHTTPError(resp) } var autolinks []shared.Autolink err = json.NewDecoder(resp.Body).Decode(&autolinks) if err != nil { return nil, err } return autolinks, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/autolink/view/view.go
pkg/cmd/repo/autolink/view/view.go
package view import ( "fmt" "github.com/cli/cli/v2/internal/browser" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/repo/autolink/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type viewOptions struct { BaseRepo func() (ghrepo.Interface, error) Browser browser.Browser AutolinkClient AutolinkViewClient IO *iostreams.IOStreams Exporter cmdutil.Exporter ID string } type AutolinkViewClient interface { View(repo ghrepo.Interface, id string) (*shared.Autolink, error) } func NewCmdView(f *cmdutil.Factory, runF func(*viewOptions) error) *cobra.Command { opts := &viewOptions{ Browser: f.Browser, IO: f.IOStreams, } cmd := &cobra.Command{ Use: "view <id>", Short: "View an autolink reference", Long: "View an autolink reference for a repository.", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { httpClient, err := f.HttpClient() if err != nil { return err } opts.BaseRepo = f.BaseRepo opts.ID = args[0] opts.AutolinkClient = &AutolinkViewer{HTTPClient: httpClient} if runF != nil { return runF(opts) } return viewRun(opts) }, } cmdutil.AddJSONFlags(cmd, &opts.Exporter, shared.AutolinkFields) return cmd } func viewRun(opts *viewOptions) error { repo, err := opts.BaseRepo() if err != nil { return err } out := opts.IO.Out cs := opts.IO.ColorScheme() autolink, err := opts.AutolinkClient.View(repo, opts.ID) if err != nil { return fmt.Errorf("%s %w", cs.Red("error viewing autolink:"), err) } if opts.Exporter != nil { return opts.Exporter.Write(opts.IO, autolink) } fmt.Fprintf(out, "Autolink in %s\n\n", cs.Bold(ghrepo.FullName(repo))) fmt.Fprint(out, cs.Bold("ID: ")) fmt.Fprintln(out, cs.Cyanf("%d", autolink.ID)) fmt.Fprint(out, cs.Bold("Key Prefix: ")) fmt.Fprintln(out, autolink.KeyPrefix) fmt.Fprint(out, cs.Bold("URL Template: ")) fmt.Fprintln(out, autolink.URLTemplate) fmt.Fprint(out, cs.Bold("Alphanumeric: ")) fmt.Fprintln(out, autolink.IsAlphanumeric) return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/autolink/view/http_test.go
pkg/cmd/repo/autolink/view/http_test.go
package view import ( "fmt" "net/http" "testing" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/repo/autolink/shared" "github.com/cli/cli/v2/pkg/httpmock" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestAutolinkViewer_View(t *testing.T) { repo := ghrepo.New("OWNER", "REPO") tests := []struct { name string id string stubStatus int stubRespJSON string expectedAutolink *shared.Autolink expectErr bool expectedErrMsg string }{ { name: "200 successful alphanumeric view", id: "123", stubStatus: http.StatusOK, stubRespJSON: `{ "id": 123, "key_prefix": "TICKET-", "url_template": "https://example.com/TICKET?query=<num>", "is_alphanumeric": true }`, expectedAutolink: &shared.Autolink{ ID: 123, KeyPrefix: "TICKET-", URLTemplate: "https://example.com/TICKET?query=<num>", IsAlphanumeric: true, }, }, { name: "200 successful numeric view", id: "123", stubStatus: http.StatusOK, stubRespJSON: `{ "id": 123, "key_prefix": "TICKET-", "url_template": "https://example.com/TICKET?query=<num>", "is_alphanumeric": false }`, expectedAutolink: &shared.Autolink{ ID: 123, KeyPrefix: "TICKET-", URLTemplate: "https://example.com/TICKET?query=<num>", IsAlphanumeric: false, }, }, { name: "404 repo or autolink not found", id: "123", stubStatus: http.StatusNotFound, stubRespJSON: `{ "message": "Not Found", "documentation_url": "https://docs.github.com/rest/repos/autolinks#get-an-autolink-reference-of-a-repository", "status": "404" }`, expectErr: true, expectedErrMsg: "HTTP 404: Perhaps you are missing admin rights to the repository? (https://api.github.com/repos/OWNER/REPO/autolinks/123)", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { reg := &httpmock.Registry{} reg.Register( httpmock.REST( http.MethodGet, fmt.Sprintf("repos/%s/%s/autolinks/%s", repo.RepoOwner(), repo.RepoName(), tt.id), ), httpmock.StatusStringResponse(tt.stubStatus, tt.stubRespJSON), ) defer reg.Verify(t) autolinkViewer := &AutolinkViewer{ HTTPClient: &http.Client{Transport: reg}, } autolink, err := autolinkViewer.View(repo, tt.id) if tt.expectErr { require.EqualError(t, err, tt.expectedErrMsg) } else { require.NoError(t, err) assert.Equal(t, tt.expectedAutolink, autolink) } }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/autolink/view/http.go
pkg/cmd/repo/autolink/view/http.go
package view import ( "encoding/json" "fmt" "net/http" "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/repo/autolink/shared" ) type AutolinkViewer struct { HTTPClient *http.Client } func (a *AutolinkViewer) View(repo ghrepo.Interface, id string) (*shared.Autolink, error) { path := fmt.Sprintf("repos/%s/%s/autolinks/%s", repo.RepoOwner(), repo.RepoName(), id) url := ghinstance.RESTPrefix(repo.RepoHost()) + path req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return nil, err } resp, err := a.HTTPClient.Do(req) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode == http.StatusNotFound { return nil, fmt.Errorf("HTTP 404: Perhaps you are missing admin rights to the repository? (https://api.github.com/%s)", path) } else if resp.StatusCode > 299 { return nil, api.HandleHTTPError(resp) } var autolink shared.Autolink err = json.NewDecoder(resp.Body).Decode(&autolink) if err != nil { return nil, err } return &autolink, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/autolink/view/view_test.go
pkg/cmd/repo/autolink/view/view_test.go
package view import ( "bytes" "net/http" "testing" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/browser" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/repo/autolink/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/pkg/jsonfieldstest" "github.com/google/shlex" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestJSONFields(t *testing.T) { jsonfieldstest.ExpectCommandToSupportJSONFields(t, NewCmdView, []string{ "id", "isAlphanumeric", "keyPrefix", "urlTemplate", }) } func TestNewCmdView(t *testing.T) { tests := []struct { name string input string output viewOptions wantErr bool wantExporter bool errMsg string }{ { name: "no argument", input: "", wantErr: true, errMsg: "accepts 1 arg(s), received 0", }, { name: "id provided", input: "123", output: viewOptions{ID: "123"}, }, { name: "json flag", input: "123 --json id", output: viewOptions{ID: "123"}, wantExporter: true, }, { name: "invalid json flag", input: "123 --json invalid", wantErr: true, errMsg: "Unknown JSON field: \"invalid\"\nAvailable fields:\n id\n isAlphanumeric\n keyPrefix\n urlTemplate", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() f := &cmdutil.Factory{ IOStreams: ios, } f.HttpClient = func() (*http.Client, error) { return &http.Client{}, nil } argv, err := shlex.Split(tt.input) require.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.wantErr { require.EqualError(t, err, tt.errMsg) } else { require.NoError(t, err) assert.Equal(t, tt.wantExporter, gotOpts.Exporter != nil) assert.Equal(t, tt.output.ID, gotOpts.ID) } }) } } type stubAutolinkViewer struct { autolink *shared.Autolink err error } func (g stubAutolinkViewer) View(repo ghrepo.Interface, id string) (*shared.Autolink, error) { return g.autolink, g.err } type testAutolinkClientViewError struct{} func (e testAutolinkClientViewError) Error() string { return "autolink client view error" } func TestViewRun(t *testing.T) { tests := []struct { name string opts *viewOptions stubViewer stubAutolinkViewer expectedErr error wantStdout string }{ { name: "view", opts: &viewOptions{ ID: "1", }, stubViewer: stubAutolinkViewer{ autolink: &shared.Autolink{ ID: 1, KeyPrefix: "TICKET-", URLTemplate: "https://example.com/TICKET?query=<num>", IsAlphanumeric: true, }, }, wantStdout: heredoc.Doc(` Autolink in OWNER/REPO ID: 1 Key Prefix: TICKET- URL Template: https://example.com/TICKET?query=<num> Alphanumeric: true `), }, { name: "view json", opts: &viewOptions{ Exporter: func() cmdutil.Exporter { exporter := cmdutil.NewJSONExporter() exporter.SetFields([]string{"id"}) return exporter }(), }, stubViewer: stubAutolinkViewer{ autolink: &shared.Autolink{ ID: 1, KeyPrefix: "TICKET-", URLTemplate: "https://example.com/TICKET?query=<num>", IsAlphanumeric: true, }, }, wantStdout: "{\"id\":1}\n", }, { name: "client error", opts: &viewOptions{}, stubViewer: stubAutolinkViewer{ autolink: nil, err: testAutolinkClientViewError{}, }, expectedErr: testAutolinkClientViewError{}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, stdout, _ := iostreams.Test() opts := tt.opts opts.IO = ios opts.Browser = &browser.Stub{} opts.IO = ios opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil } opts.AutolinkClient = &tt.stubViewer err := viewRun(opts) if tt.expectedErr != nil { require.Error(t, err) assert.ErrorIs(t, err, tt.expectedErr) } else { require.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/repo/autolink/create/create.go
pkg/cmd/repo/autolink/create/create.go
package create import ( "fmt" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/browser" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/repo/autolink/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type createOptions struct { BaseRepo func() (ghrepo.Interface, error) Browser browser.Browser AutolinkClient AutolinkCreateClient IO *iostreams.IOStreams Exporter cmdutil.Exporter KeyPrefix string URLTemplate string Numeric bool } type AutolinkCreateClient interface { Create(repo ghrepo.Interface, request AutolinkCreateRequest) (*shared.Autolink, error) } func NewCmdCreate(f *cmdutil.Factory, runF func(*createOptions) error) *cobra.Command { opts := &createOptions{ Browser: f.Browser, IO: f.IOStreams, } cmd := &cobra.Command{ Use: "create <keyPrefix> <urlTemplate>", Short: "Create a new autolink reference", Long: heredoc.Docf(` Create a new autolink reference for a repository. The %[1]skeyPrefix%[1]s argument specifies the prefix that will generate a link when it is appended by certain characters. The %[1]surlTemplate%[1]s argument specifies the target URL that will be generated when the keyPrefix is found, which must contain %[1]s<num>%[1]s variable for the reference number. By default, autolinks are alphanumeric with %[1]s--numeric%[1]s flag used to create a numeric autolink. The %[1]s<num>%[1]s variable behavior differs depending on whether the autolink is alphanumeric or numeric: - alphanumeric: matches %[1]sA-Z%[1]s (case insensitive), %[1]s0-9%[1]s, and %[1]s-%[1]s - numeric: matches %[1]s0-9%[1]s If the template contains multiple instances of %[1]s<num>%[1]s, only the first will be replaced. `, "`"), Example: heredoc.Doc(` # Create an alphanumeric autolink to example.com for the key prefix "TICKET-". # Generates https://example.com/TICKET?query=123abc from "TICKET-123abc". $ gh repo autolink create TICKET- "https://example.com/TICKET?query=<num>" # Create a numeric autolink to example.com for the key prefix "STORY-". # Generates https://example.com/STORY?id=123 from "STORY-123". $ gh repo autolink create STORY- "https://example.com/STORY?id=<num>" --numeric `), Args: cmdutil.ExactArgs(2, "Cannot create autolink: keyPrefix and urlTemplate arguments are both required"), Aliases: []string{"new"}, RunE: func(c *cobra.Command, args []string) error { opts.BaseRepo = f.BaseRepo httpClient, err := f.HttpClient() if err != nil { return err } opts.AutolinkClient = &AutolinkCreator{HTTPClient: httpClient} opts.KeyPrefix = args[0] opts.URLTemplate = args[1] if runF != nil { return runF(opts) } return createRun(opts) }, } cmd.Flags().BoolVarP(&opts.Numeric, "numeric", "n", false, "Mark autolink as numeric") return cmd } func createRun(opts *createOptions) error { repo, err := opts.BaseRepo() if err != nil { return err } request := AutolinkCreateRequest{ KeyPrefix: opts.KeyPrefix, URLTemplate: opts.URLTemplate, IsAlphanumeric: !opts.Numeric, } autolink, err := opts.AutolinkClient.Create(repo, request) if err != nil { return fmt.Errorf("error creating autolink: %w", err) } cs := opts.IO.ColorScheme() fmt.Fprintf(opts.IO.Out, "%s Created repository autolink %s on %s\n", cs.SuccessIconWithColor(cs.Green), cs.Cyanf("%d", autolink.ID), cs.Bold(ghrepo.FullName(repo))) return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/autolink/create/create_test.go
pkg/cmd/repo/autolink/create/create_test.go
package create import ( "bytes" "fmt" "net/http" "testing" "github.com/cli/cli/v2/internal/browser" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/repo/autolink/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNewCmdCreate(t *testing.T) { tests := []struct { name string input string output createOptions wantErr bool errMsg string }{ { name: "no argument", input: "", wantErr: true, errMsg: "Cannot create autolink: keyPrefix and urlTemplate arguments are both required", }, { name: "one argument", input: "TEST-", wantErr: true, errMsg: "Cannot create autolink: keyPrefix and urlTemplate arguments are both required", }, { name: "two argument", input: "TICKET- https://example.com/TICKET?query=<num>", output: createOptions{ KeyPrefix: "TICKET-", URLTemplate: "https://example.com/TICKET?query=<num>", }, }, { name: "numeric flag", input: "TICKET- https://example.com/TICKET?query=<num> --numeric", output: createOptions{ KeyPrefix: "TICKET-", URLTemplate: "https://example.com/TICKET?query=<num>", Numeric: true, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() f := &cmdutil.Factory{ IOStreams: ios, } f.HttpClient = func() (*http.Client, error) { return &http.Client{}, nil } argv, err := shlex.Split(tt.input) require.NoError(t, err) var gotOpts *createOptions cmd := NewCmdCreate(f, func(opts *createOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err = cmd.ExecuteC() if tt.wantErr { require.EqualError(t, err, tt.errMsg) } else { require.NoError(t, err) assert.Equal(t, tt.output.KeyPrefix, gotOpts.KeyPrefix) assert.Equal(t, tt.output.URLTemplate, gotOpts.URLTemplate) assert.Equal(t, tt.output.Numeric, gotOpts.Numeric) } }) } } type stubAutolinkCreator struct { err error } func (g stubAutolinkCreator) Create(repo ghrepo.Interface, request AutolinkCreateRequest) (*shared.Autolink, error) { if g.err != nil { return nil, g.err } return &shared.Autolink{ ID: 1, KeyPrefix: request.KeyPrefix, URLTemplate: request.URLTemplate, IsAlphanumeric: request.IsAlphanumeric, }, nil } type testAutolinkClientCreateError struct{} func (e testAutolinkClientCreateError) Error() string { return "autolink client create error" } func TestCreateRun(t *testing.T) { tests := []struct { name string opts *createOptions stubCreator stubAutolinkCreator expectedErr error errMsg string wantStdout string wantStderr string }{ { name: "success, alphanumeric", opts: &createOptions{ KeyPrefix: "TICKET-", URLTemplate: "https://example.com/TICKET?query=<num>", }, stubCreator: stubAutolinkCreator{}, wantStdout: "✓ Created repository autolink 1 on OWNER/REPO\n", }, { name: "success, numeric", opts: &createOptions{ KeyPrefix: "TICKET-", URLTemplate: "https://example.com/TICKET?query=<num>", Numeric: true, }, stubCreator: stubAutolinkCreator{}, wantStdout: "✓ Created repository autolink 1 on OWNER/REPO\n", }, { name: "client error", opts: &createOptions{ KeyPrefix: "TICKET-", URLTemplate: "https://example.com/TICKET?query=<num>", }, stubCreator: stubAutolinkCreator{err: testAutolinkClientCreateError{}}, expectedErr: testAutolinkClientCreateError{}, errMsg: fmt.Sprint("error creating autolink: ", testAutolinkClientCreateError{}.Error()), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, stdout, stderr := iostreams.Test() opts := tt.opts opts.IO = ios opts.Browser = &browser.Stub{} opts.IO = ios opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil } opts.AutolinkClient = &tt.stubCreator err := createRun(opts) if tt.expectedErr != nil { require.Error(t, err) assert.ErrorIs(t, err, tt.expectedErr) assert.Equal(t, tt.errMsg, err.Error()) } else { require.NoError(t, err) } if tt.wantStdout != "" { assert.Equal(t, tt.wantStdout, stdout.String()) } if tt.wantStderr != "" { 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/autolink/create/http_test.go
pkg/cmd/repo/autolink/create/http_test.go
package create import ( "fmt" "net/http" "testing" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/repo/autolink/shared" "github.com/cli/cli/v2/pkg/httpmock" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestAutolinkCreator_Create(t *testing.T) { repo := ghrepo.New("OWNER", "REPO") tests := []struct { name string req AutolinkCreateRequest stubStatus int stubRespJSON string expectedAutolink *shared.Autolink expectErr bool expectedErrMsg string }{ { name: "201 successful creation", req: AutolinkCreateRequest{ IsAlphanumeric: true, KeyPrefix: "TICKET-", URLTemplate: "https://example.com/TICKET?query=<num>", }, stubStatus: http.StatusCreated, stubRespJSON: `{ "id": 1, "is_alphanumeric": true, "key_prefix": "TICKET-", "url_template": "https://example.com/TICKET?query=<num>" }`, expectedAutolink: &shared.Autolink{ ID: 1, KeyPrefix: "TICKET-", URLTemplate: "https://example.com/TICKET?query=<num>", IsAlphanumeric: true, }, }, { name: "422 URL template not valid URL", req: AutolinkCreateRequest{ IsAlphanumeric: true, KeyPrefix: "TICKET-", URLTemplate: "foo/<num>", }, stubStatus: http.StatusUnprocessableEntity, stubRespJSON: `{ "message": "Validation Failed", "errors": [ { "resource": "KeyLink", "code": "custom", "field": "url_template", "message": "url_template must be an absolute URL" } ], "documentation_url": "https://docs.github.com/rest/repos/autolinks#create-an-autolink-reference-for-a-repository", "status": "422" }`, expectErr: true, expectedErrMsg: heredoc.Doc(` HTTP 422: Validation Failed (https://api.github.com/repos/OWNER/REPO/autolinks) url_template must be an absolute URL`), }, { name: "404 repo not found", req: AutolinkCreateRequest{ IsAlphanumeric: true, KeyPrefix: "TICKET-", URLTemplate: "https://example.com/TICKET?query=<num>", }, stubStatus: http.StatusNotFound, stubRespJSON: `{ "message": "Not Found", "documentation_url": "https://docs.github.com/rest/repos/autolinks#create-an-autolink-reference-for-a-repository", "status": "404" }`, expectErr: true, expectedErrMsg: "HTTP 404: Must have admin rights to Repository. (https://api.github.com/repos/OWNER/REPO/autolinks)", }, { name: "422 URL template missing <num>", req: AutolinkCreateRequest{ IsAlphanumeric: true, KeyPrefix: "TICKET-", URLTemplate: "https://example.com/TICKET", }, stubStatus: http.StatusUnprocessableEntity, stubRespJSON: `{"message":"Validation Failed","errors":[{"resource":"KeyLink","code":"custom","field":"url_template","message":"url_template is missing a <num> token"}],"documentation_url":"https://docs.github.com/rest/repos/autolinks#create-an-autolink-reference-for-a-repository","status":"422"}`, expectErr: true, expectedErrMsg: heredoc.Doc(` HTTP 422: Validation Failed (https://api.github.com/repos/OWNER/REPO/autolinks) url_template is missing a <num> token`), }, { name: "422 already exists", req: AutolinkCreateRequest{ IsAlphanumeric: true, KeyPrefix: "TICKET-", URLTemplate: "https://example.com/TICKET?query=<num>", }, stubStatus: http.StatusUnprocessableEntity, stubRespJSON: `{"message":"Validation Failed","errors":[{"resource":"KeyLink","code":"already_exists","field":"key_prefix"}],"documentation_url":"https://docs.github.com/rest/repos/autolinks#create-an-autolink-reference-for-a-repository","status":"422"}`, expectErr: true, expectedErrMsg: heredoc.Doc(` HTTP 422: Validation Failed (https://api.github.com/repos/OWNER/REPO/autolinks) KeyLink.key_prefix already exists`), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { reg := &httpmock.Registry{} reg.Register( httpmock.REST( http.MethodPost, fmt.Sprintf("repos/%s/%s/autolinks", repo.RepoOwner(), repo.RepoName())), httpmock.RESTPayload(tt.stubStatus, tt.stubRespJSON, func(payload map[string]interface{}) { require.Equal(t, map[string]interface{}{ "is_alphanumeric": tt.req.IsAlphanumeric, "key_prefix": tt.req.KeyPrefix, "url_template": tt.req.URLTemplate, }, payload) }, ), ) defer reg.Verify(t) autolinkCreator := &AutolinkCreator{ HTTPClient: &http.Client{Transport: reg}, } autolink, err := autolinkCreator.Create(repo, tt.req) if tt.expectErr { require.EqualError(t, err, tt.expectedErrMsg) } else { require.NoError(t, err) assert.Equal(t, tt.expectedAutolink, autolink) } }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/autolink/create/http.go
pkg/cmd/repo/autolink/create/http.go
package create import ( "bytes" "encoding/json" "errors" "fmt" "net/http" "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/repo/autolink/shared" ) type AutolinkCreator struct { HTTPClient *http.Client } type AutolinkCreateRequest struct { IsAlphanumeric bool `json:"is_alphanumeric"` KeyPrefix string `json:"key_prefix"` URLTemplate string `json:"url_template"` } func (a *AutolinkCreator) Create(repo ghrepo.Interface, request AutolinkCreateRequest) (*shared.Autolink, error) { path := fmt.Sprintf("repos/%s/%s/autolinks", repo.RepoOwner(), repo.RepoName()) url := ghinstance.RESTPrefix(repo.RepoHost()) + path requestByte, err := json.Marshal(request) if err != nil { return nil, err } requestBody := bytes.NewReader(requestByte) req, err := http.NewRequest(http.MethodPost, url, requestBody) if err != nil { return nil, err } resp, err := a.HTTPClient.Do(req) if err != nil { return nil, err } defer resp.Body.Close() err = handleAutolinkCreateError(resp) if err != nil { return nil, err } var autolink shared.Autolink err = json.NewDecoder(resp.Body).Decode(&autolink) if err != nil { return nil, err } return &autolink, nil } func handleAutolinkCreateError(resp *http.Response) error { switch resp.StatusCode { case http.StatusCreated: return nil case http.StatusNotFound: err := api.HandleHTTPError(resp) var httpErr api.HTTPError if errors.As(err, &httpErr) { httpErr.Message = "Must have admin rights to Repository." return httpErr } return err default: return api.HandleHTTPError(resp) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/autolink/shared/autolink.go
pkg/cmd/repo/autolink/shared/autolink.go
package shared import "github.com/cli/cli/v2/pkg/cmdutil" type Autolink struct { ID int `json:"id"` IsAlphanumeric bool `json:"is_alphanumeric"` KeyPrefix string `json:"key_prefix"` URLTemplate string `json:"url_template"` } var AutolinkFields = []string{ "id", "isAlphanumeric", "keyPrefix", "urlTemplate", } func (a *Autolink) ExportData(fields []string) map[string]interface{} { return cmdutil.StructExportData(a, fields) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/delete/delete.go
pkg/cmd/repo/delete/delete.go
package delete import ( "errors" "fmt" "net/http" "strings" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" ghauth "github.com/cli/go-gh/v2/pkg/auth" "github.com/spf13/cobra" ) type iprompter interface { ConfirmDeletion(string) error } type DeleteOptions struct { HttpClient func() (*http.Client, error) BaseRepo func() (ghrepo.Interface, error) Prompter iprompter IO *iostreams.IOStreams RepoArg string Confirmed bool } func NewCmdDelete(f *cmdutil.Factory, runF func(*DeleteOptions) error) *cobra.Command { opts := &DeleteOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, BaseRepo: f.BaseRepo, Prompter: f.Prompter, } cmd := &cobra.Command{ Use: "delete [<repository>]", Short: "Delete a repository", Long: heredoc.Docf(` Delete a GitHub repository. With no argument, deletes the current repository. Otherwise, deletes the specified repository. For safety, when no repository argument is provided, the %[1]s--yes%[1]s flag is ignored and you will be prompted for confirmation. To delete the current repository non-interactively, specify it explicitly (e.g., %[1]sgh repo delete owner/repo --yes%[1]s). Deletion requires authorization with the %[1]sdelete_repo%[1]s scope. To authorize, run %[1]sgh auth refresh -s delete_repo%[1]s `, "`"), Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { if len(args) > 0 { opts.RepoArg = args[0] } // Ignore --yes when no argument provided to prevent accidental deletion if len(args) == 0 && opts.Confirmed { if !opts.IO.CanPrompt() { return cmdutil.FlagErrorf("cannot non-interactively delete current repository. Please specify a repository or run interactively") } _, _ = fmt.Fprintln(opts.IO.ErrOut, "Warning: `--yes` is ignored since no repository was specified") opts.Confirmed = false } if !opts.IO.CanPrompt() && !opts.Confirmed { return cmdutil.FlagErrorf("--yes required when not running interactively") } if runF != nil { return runF(opts) } return deleteRun(opts) }, } cmd.Flags().BoolVar(&opts.Confirmed, "confirm", false, "Confirm deletion without prompting") _ = cmd.Flags().MarkDeprecated("confirm", "use `--yes` instead") cmd.Flags().BoolVar(&opts.Confirmed, "yes", false, "Confirm deletion without prompting") return cmd } func deleteRun(opts *DeleteOptions) error { httpClient, err := opts.HttpClient() if err != nil { return err } apiClient := api.NewClientFromHTTP(httpClient) var toDelete ghrepo.Interface if opts.RepoArg == "" { toDelete, err = opts.BaseRepo() if err != nil { return err } } else { repoSelector := opts.RepoArg if !strings.Contains(repoSelector, "/") { defaultHost, _ := ghauth.DefaultHost() currentUser, err := api.CurrentLoginName(apiClient, defaultHost) if err != nil { return err } repoSelector = currentUser + "/" + repoSelector } toDelete, err = ghrepo.FromFullName(repoSelector) if err != nil { return fmt.Errorf("argument error: %w", err) } } fullName := ghrepo.FullName(toDelete) if !opts.Confirmed { if err := opts.Prompter.ConfirmDeletion(fullName); err != nil { return err } } err = deleteRepo(httpClient, toDelete) if err != nil { var httpErr api.HTTPError if errors.As(err, &httpErr) { statusCode := httpErr.HTTPError.StatusCode if statusCode == http.StatusMovedPermanently || statusCode == http.StatusTemporaryRedirect || statusCode == http.StatusPermanentRedirect { cs := opts.IO.ColorScheme() fmt.Fprintf(opts.IO.ErrOut, "%s Failed to delete repository: %s has changed name or transferred ownership\n", cs.FailureIcon(), fullName) return cmdutil.SilentError } } return err } if opts.IO.IsStdoutTTY() { cs := opts.IO.ColorScheme() fmt.Fprintf(opts.IO.Out, "%s Deleted 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/delete/delete_test.go
pkg/cmd/repo/delete/delete_test.go
package delete import ( "bytes" "net/http" "testing" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" ) func TestNewCmdDelete(t *testing.T) { tests := []struct { name string input string tty bool output DeleteOptions wantErr bool wantErrMsg string wantStderr string }{ { name: "confirm flag", tty: true, input: "OWNER/REPO --confirm", output: DeleteOptions{RepoArg: "OWNER/REPO", Confirmed: true}, }, { name: "yes flag", tty: true, input: "OWNER/REPO --yes", output: DeleteOptions{RepoArg: "OWNER/REPO", Confirmed: true}, }, { name: "no confirmation notty", input: "OWNER/REPO", output: DeleteOptions{RepoArg: "OWNER/REPO"}, wantErr: true, wantErrMsg: "--yes required when not running interactively", }, { name: "base repo resolution", input: "", tty: true, output: DeleteOptions{}, }, { name: "yes flag ignored when no argument tty", tty: true, input: "--yes", output: DeleteOptions{Confirmed: false}, // --yes should be ignored wantErr: false, wantStderr: "Warning: `--yes` is ignored since no repository was specified\n", }, { name: "yes flag error when no argument notty", input: "--yes", wantErr: true, wantErrMsg: "cannot non-interactively delete current repository. Please specify a repository or run interactively", }, { name: "confirm flag error when no argument notty", input: "--confirm", wantErr: true, wantErrMsg: "cannot non-interactively delete current repository. Please specify a repository or run interactively", }, { name: "confirm flag also ignored when no argument tty", tty: true, input: "--confirm", output: DeleteOptions{Confirmed: false}, // --confirm should also be ignored wantStderr: "Warning: `--yes` is ignored since no repository was specified\n", // Note: This does not confuse the user, as deprecation warnings are shown: "Flag --confirm has been deprecated, use `--yes` instead" }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, stdErr := 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 *DeleteOptions cmd := NewCmdDelete(f, func(opts *DeleteOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(stdErr) _, err = cmd.ExecuteC() if tt.wantErr { assert.Error(t, err) assert.Equal(t, tt.wantErrMsg, err.Error()) return } assert.NoError(t, err) assert.Equal(t, tt.wantStderr, stdErr.String()) assert.Equal(t, tt.output.RepoArg, gotOpts.RepoArg) }) } } func Test_deleteRun(t *testing.T) { tests := []struct { name string tty bool opts *DeleteOptions httpStubs func(*httpmock.Registry) prompterStubs func(*prompter.PrompterMock) wantStdout string wantStderr string wantErr bool errMsg string }{ { name: "prompting confirmation tty", tty: true, opts: &DeleteOptions{RepoArg: "OWNER/REPO"}, wantStdout: "✓ Deleted repository OWNER/REPO\n", prompterStubs: func(p *prompter.PrompterMock) { p.ConfirmDeletionFunc = func(_ string) error { return nil } }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("DELETE", "repos/OWNER/REPO"), httpmock.StatusStringResponse(204, "{}")) }, }, { name: "infer base repo", tty: true, opts: &DeleteOptions{}, wantStdout: "✓ Deleted repository OWNER/REPO\n", prompterStubs: func(p *prompter.PrompterMock) { p.ConfirmDeletionFunc = func(_ string) error { return nil } }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("DELETE", "repos/OWNER/REPO"), httpmock.StatusStringResponse(204, "{}")) }, }, { name: "confirmation no tty", opts: &DeleteOptions{ RepoArg: "OWNER/REPO", Confirmed: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("DELETE", "repos/OWNER/REPO"), httpmock.StatusStringResponse(204, "{}")) }, }, { name: "short repo name", opts: &DeleteOptions{RepoArg: "REPO"}, wantStdout: "✓ Deleted repository OWNER/REPO\n", tty: true, prompterStubs: func(p *prompter.PrompterMock) { p.ConfirmDeletionFunc = func(_ string) error { return nil } }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data":{"viewer":{"login":"OWNER"}}}`)) reg.Register( httpmock.REST("DELETE", "repos/OWNER/REPO"), httpmock.StatusStringResponse(204, "{}")) }, }, { name: "repo transferred ownership", opts: &DeleteOptions{RepoArg: "OWNER/REPO", Confirmed: true}, wantErr: true, errMsg: "SilentError", wantStderr: "X Failed to delete repository: OWNER/REPO has changed name or transferred ownership\n", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("DELETE", "repos/OWNER/REPO"), httpmock.StatusStringResponse(307, "{}")) }, }, } for _, tt := range tests { pm := &prompter.PrompterMock{} if tt.prompterStubs != nil { tt.prompterStubs(pm) } tt.opts.Prompter = pm tt.opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil } 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 t.Run(tt.name, func(t *testing.T) { defer reg.Verify(t) err := deleteRun(tt.opts) if tt.wantErr { assert.Error(t, err) assert.Equal(t, tt.errMsg, err.Error()) return } 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/delete/http.go
pkg/cmd/repo/delete/http.go
package delete import ( "fmt" "net/http" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghinstance" "github.com/cli/cli/v2/internal/ghrepo" ) func deleteRepo(client *http.Client, repo ghrepo.Interface) error { oldClient := *client client = &oldClient client.CheckRedirect = func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse } url := fmt.Sprintf("%srepos/%s", ghinstance.RESTPrefix(repo.RepoHost()), ghrepo.FullName(repo)) request, err := http.NewRequest("DELETE", url, nil) if err != nil { return err } resp, err := client.Do(request) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode > 299 { api.EndpointNeedsScopes(resp, "delete_repo") return api.HandleHTTPError(resp) } return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/setdefault/setdefault_test.go
pkg/cmd/repo/setdefault/setdefault_test.go
package base import ( "bytes" "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/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" ) func TestNewCmdSetDefault(t *testing.T) { tests := []struct { name string gitStubs func(*run.CommandStubber) input string output SetDefaultOptions wantErr bool errMsg string }{ { name: "no argument", gitStubs: func(cs *run.CommandStubber) { cs.Register(`git rev-parse --git-dir`, 0, ".git") }, input: "", output: SetDefaultOptions{}, }, { name: "repo argument", gitStubs: func(cs *run.CommandStubber) { cs.Register(`git rev-parse --git-dir`, 0, ".git") }, input: "cli/cli", output: SetDefaultOptions{Repo: ghrepo.New("cli", "cli")}, }, { name: "invalid repo argument", gitStubs: func(cs *run.CommandStubber) {}, input: "some_invalid_format", wantErr: true, errMsg: `expected the "[HOST/]OWNER/REPO" format, got "some_invalid_format"`, }, { name: "view flag", gitStubs: func(cs *run.CommandStubber) { cs.Register(`git rev-parse --git-dir`, 0, ".git") }, input: "--view", output: SetDefaultOptions{ViewMode: true}, }, { name: "unset flag", gitStubs: func(cs *run.CommandStubber) { cs.Register(`git rev-parse --git-dir`, 0, ".git") }, input: "--unset", output: SetDefaultOptions{UnsetMode: true}, }, { name: "run from non-git directory", gitStubs: func(cs *run.CommandStubber) { cs.Register(`git rev-parse --git-dir`, 128, "") }, input: "", wantErr: true, errMsg: "must be run from inside a git repository", }, } for _, tt := range tests { io, _, _, _ := iostreams.Test() io.SetStdoutTTY(true) io.SetStdinTTY(true) io.SetStderrTTY(true) f := &cmdutil.Factory{ IOStreams: io, GitClient: &git.Client{GitPath: "/fake/path/to/git"}, } var gotOpts *SetDefaultOptions cmd := NewCmdSetDefault(f, func(opts *SetDefaultOptions) error { gotOpts = opts return nil }) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) t.Run(tt.name, func(t *testing.T) { argv, err := shlex.Split(tt.input) assert.NoError(t, err) cmd.SetArgs(argv) cs, teardown := run.Stub() defer teardown(t) tt.gitStubs(cs) _, err = cmd.ExecuteC() if tt.wantErr { assert.EqualError(t, err, tt.errMsg) return } assert.NoError(t, err) assert.Equal(t, tt.output.Repo, gotOpts.Repo) assert.Equal(t, tt.output.ViewMode, gotOpts.ViewMode) }) } } func TestDefaultRun(t *testing.T) { repo1, _ := ghrepo.FromFullName("OWNER/REPO") repo2, _ := ghrepo.FromFullName("OWNER2/REPO2") repo3, _ := ghrepo.FromFullName("OWNER3/REPO3") repo4, _ := ghrepo.FromFullName("OWNER4/REPO4") repo5, _ := ghrepo.FromFullName("OWNER5/REPO5") repo6, _ := ghrepo.FromFullName("OWNER6/REPO6") tests := []struct { name string tty bool opts SetDefaultOptions remotes []*context.Remote httpStubs func(*httpmock.Registry) gitStubs func(*run.CommandStubber) prompterStubs func(*prompter.PrompterMock) wantStdout string wantStderr string wantErr bool errMsg string }{ { name: "unset mode with base resolved current default", tty: true, opts: SetDefaultOptions{UnsetMode: true}, remotes: []*context.Remote{ { Remote: &git.Remote{Name: "origin", Resolved: "base"}, Repo: repo1, }, }, gitStubs: func(cs *run.CommandStubber) { cs.Register(`git config --unset remote.origin.gh-resolved`, 0, "") }, wantStdout: "✓ Unset OWNER/REPO as default repository\n", }, { name: "unset mode no current default", tty: true, opts: SetDefaultOptions{UnsetMode: true}, remotes: []*context.Remote{ { Remote: &git.Remote{Name: "origin"}, Repo: repo1, }, }, wantStdout: "no default repository has been set\n", }, { name: "tty view mode no current default", tty: true, opts: SetDefaultOptions{ViewMode: true}, remotes: []*context.Remote{ { Remote: &git.Remote{Name: "origin"}, Repo: repo1, }, }, wantStderr: "X No default remote repository has been set. To learn more about the default repository, run: gh repo set-default --help\n", }, { name: "view mode no current default", tty: false, opts: SetDefaultOptions{ViewMode: true}, remotes: []*context.Remote{ { Remote: &git.Remote{Name: "origin"}, Repo: repo1, }, }, wantStderr: "X No default remote repository has been set. To learn more about the default repository, run: gh repo set-default --help\n", }, { name: "view mode with base resolved current default", opts: SetDefaultOptions{ViewMode: true}, remotes: []*context.Remote{ { Remote: &git.Remote{Name: "origin", Resolved: "base"}, Repo: repo1, }, }, wantStdout: "OWNER/REPO\n", }, { name: "view mode with non-base resolved current default", opts: SetDefaultOptions{ViewMode: true}, remotes: []*context.Remote{ { Remote: &git.Remote{Name: "origin", Resolved: "PARENT/REPO"}, Repo: repo1, }, }, wantStdout: "PARENT/REPO\n", }, { name: "tty non-interactive mode no current default", tty: true, opts: SetDefaultOptions{Repo: repo2}, remotes: []*context.Remote{ { Remote: &git.Remote{Name: "origin"}, Repo: repo1, }, { Remote: &git.Remote{Name: "upstream"}, Repo: repo2, }, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryNetwork\b`), httpmock.StringResponse(`{"data":{"repo_000":{"name":"REPO2","owner":{"login":"OWNER2"}}}}`), ) }, gitStubs: func(cs *run.CommandStubber) { cs.Register(`git config --add remote.upstream.gh-resolved base`, 0, "") }, wantStdout: "✓ Set OWNER2/REPO2 as the default repository for the current directory\n", }, { name: "tty non-interactive mode set non-base default", tty: true, opts: SetDefaultOptions{Repo: repo2}, remotes: []*context.Remote{ { Remote: &git.Remote{Name: "origin"}, Repo: repo1, }, { Remote: &git.Remote{Name: "upstream"}, Repo: repo3, }, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryNetwork\b`), httpmock.StringResponse(`{"data":{"repo_000":{"name":"REPO","owner":{"login":"OWNER"},"parent":{"name":"REPO2","owner":{"login":"OWNER2"}}}}}`), ) }, gitStubs: func(cs *run.CommandStubber) { cs.Register(`git config --add remote.upstream.gh-resolved OWNER2/REPO2`, 0, "") }, wantStdout: "✓ Set OWNER2/REPO2 as the default repository for the current directory\n", }, { name: "non-tty non-interactive mode no current default", opts: SetDefaultOptions{Repo: repo2}, remotes: []*context.Remote{ { Remote: &git.Remote{Name: "origin"}, Repo: repo1, }, { Remote: &git.Remote{Name: "upstream"}, Repo: repo2, }, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryNetwork\b`), httpmock.StringResponse(`{"data":{"repo_000":{"name":"REPO2","owner":{"login":"OWNER2"}}}}`), ) }, gitStubs: func(cs *run.CommandStubber) { cs.Register(`git config --add remote.upstream.gh-resolved base`, 0, "") }, wantStdout: "", }, { name: "non-interactive mode with current default", tty: true, opts: SetDefaultOptions{Repo: repo2}, remotes: []*context.Remote{ { Remote: &git.Remote{Name: "origin", Resolved: "base"}, Repo: repo1, }, { Remote: &git.Remote{Name: "upstream"}, Repo: repo2, }, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryNetwork\b`), httpmock.StringResponse(`{"data":{"repo_000":{"name":"REPO2","owner":{"login":"OWNER2"}}}}`), ) }, gitStubs: func(cs *run.CommandStubber) { cs.Register(`git config --unset remote.origin.gh-resolved`, 0, "") cs.Register(`git config --add remote.upstream.gh-resolved base`, 0, "") }, wantStdout: "✓ Set OWNER2/REPO2 as the default repository for the current directory\n", }, { name: "non-interactive mode no known hosts", opts: SetDefaultOptions{Repo: repo2}, remotes: []*context.Remote{ { Remote: &git.Remote{Name: "origin"}, Repo: repo1, }, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryNetwork\b`), httpmock.StringResponse(`{"data":{}}`), ) }, wantErr: true, errMsg: "none of the git remotes correspond to a valid remote repository", }, { name: "non-interactive mode no matching remotes", opts: SetDefaultOptions{Repo: repo2}, remotes: []*context.Remote{ { Remote: &git.Remote{Name: "origin"}, Repo: repo1, }, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryNetwork\b`), httpmock.StringResponse(`{"data":{"repo_000":{"name":"REPO","owner":{"login":"OWNER"}}}}`), ) }, wantErr: true, errMsg: "OWNER2/REPO2 does not correspond to any git remotes", }, { name: "interactive mode", tty: true, opts: SetDefaultOptions{}, remotes: []*context.Remote{ { Remote: &git.Remote{Name: "origin"}, Repo: repo1, }, { Remote: &git.Remote{Name: "upstream"}, Repo: repo2, }, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryNetwork\b`), httpmock.StringResponse(`{"data":{"repo_000":{"name":"REPO","owner":{"login":"OWNER"}},"repo_001":{"name":"REPO2","owner":{"login":"OWNER2"}}}}`), ) }, gitStubs: func(cs *run.CommandStubber) { cs.Register(`git config --add remote.upstream.gh-resolved base`, 0, "") }, prompterStubs: func(pm *prompter.PrompterMock) { pm.SelectFunc = func(p, d string, opts []string) (int, error) { switch p { case "Which repository should be the default?": prompter.AssertOptions(t, []string{"OWNER/REPO", "OWNER2/REPO2"}, opts) return prompter.IndexFor(opts, "OWNER2/REPO2") default: return -1, prompter.NoSuchPromptErr(p) } } }, wantStdout: "This command sets the default remote repository to use when querying the\nGitHub API for the locally cloned repository.\n\ngh uses the default repository for things like:\n\n - viewing and creating pull requests\n - viewing and creating issues\n - viewing and creating releases\n - working with GitHub Actions\n\n### NOTE: gh does not use the default repository for managing repository and environment secrets.\n\n✓ Set OWNER2/REPO2 as the default repository for the current directory\n", }, { name: "interactive mode only one known host", tty: true, opts: SetDefaultOptions{}, remotes: []*context.Remote{ { Remote: &git.Remote{Name: "origin"}, Repo: repo1, }, { Remote: &git.Remote{Name: "upstream"}, Repo: repo2, }, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryNetwork\b`), httpmock.StringResponse(`{"data":{"repo_000":{"name":"REPO2","owner":{"login":"OWNER2"}}}}`), ) }, gitStubs: func(cs *run.CommandStubber) { cs.Register(`git config --add remote.upstream.gh-resolved base`, 0, "") }, wantStdout: "Found only one known remote repo, OWNER2/REPO2 on github.com.\n✓ Set OWNER2/REPO2 as the default repository for the current directory\n", }, { name: "interactive mode more than five remotes", tty: true, opts: SetDefaultOptions{}, remotes: []*context.Remote{ {Remote: &git.Remote{Name: "origin"}, Repo: repo1}, {Remote: &git.Remote{Name: "upstream"}, Repo: repo2}, {Remote: &git.Remote{Name: "other1"}, Repo: repo3}, {Remote: &git.Remote{Name: "other2"}, Repo: repo4}, {Remote: &git.Remote{Name: "other3"}, Repo: repo5}, {Remote: &git.Remote{Name: "other4"}, Repo: repo6}, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryNetwork\b`), httpmock.GraphQLQuery(`{"data":{ "repo_000":{"name":"REPO","owner":{"login":"OWNER"}}, "repo_001":{"name":"REPO2","owner":{"login":"OWNER2"}}, "repo_002":{"name":"REPO3","owner":{"login":"OWNER3"}}, "repo_003":{"name":"REPO4","owner":{"login":"OWNER4"}}, "repo_004":{"name":"REPO5","owner":{"login":"OWNER5"}}, "repo_005":{"name":"REPO6","owner":{"login":"OWNER6"}} }}`, func(query string, inputs map[string]interface{}) { assert.Contains(t, query, "repo_000") assert.Contains(t, query, "repo_001") assert.Contains(t, query, "repo_002") assert.Contains(t, query, "repo_003") assert.Contains(t, query, "repo_004") assert.Contains(t, query, "repo_005") }), ) }, gitStubs: func(cs *run.CommandStubber) { cs.Register(`git config --add remote.upstream.gh-resolved base`, 0, "") }, prompterStubs: func(pm *prompter.PrompterMock) { pm.SelectFunc = func(p, d string, opts []string) (int, error) { switch p { case "Which repository should be the default?": prompter.AssertOptions(t, []string{"OWNER/REPO", "OWNER2/REPO2", "OWNER3/REPO3", "OWNER4/REPO4", "OWNER5/REPO5", "OWNER6/REPO6"}, opts) return prompter.IndexFor(opts, "OWNER2/REPO2") default: return -1, prompter.NoSuchPromptErr(p) } } }, wantStdout: "This command sets the default remote repository to use when querying the\nGitHub API for the locally cloned repository.\n\ngh uses the default repository for things like:\n\n - viewing and creating pull requests\n - viewing and creating issues\n - viewing and creating releases\n - working with GitHub Actions\n\n### NOTE: gh does not use the default repository for managing repository and environment secrets.\n\n✓ Set OWNER2/REPO2 as the default repository for the current directory\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 } io, _, stdout, stderr := iostreams.Test() io.SetStdinTTY(tt.tty) io.SetStdoutTTY(tt.tty) io.SetStderrTTY(tt.tty) tt.opts.IO = io tt.opts.Remotes = func() (context.Remotes, error) { return tt.remotes, nil } tt.opts.GitClient = &git.Client{} pm := &prompter.PrompterMock{} if tt.prompterStubs != nil { tt.prompterStubs(pm) } tt.opts.Prompter = pm t.Run(tt.name, func(t *testing.T) { cs, teardown := run.Stub() defer teardown(t) if tt.gitStubs != nil { tt.gitStubs(cs) } defer reg.Verify(t) err := setDefaultRun(&tt.opts) if tt.wantErr { assert.EqualError(t, err, tt.errMsg) return } assert.NoError(t, err) if tt.wantStdout != "" { assert.Equal(t, tt.wantStdout, stdout.String()) } else { 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/setdefault/setdefault.go
pkg/cmd/repo/setdefault/setdefault.go
package base import ( "errors" "fmt" "net/http" "sort" "strings" ctx "context" "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/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) func explainer() string { return heredoc.Doc(` This command sets the default remote repository to use when querying the GitHub API for the locally cloned repository. gh uses the default repository for things like: - viewing and creating pull requests - viewing and creating issues - viewing and creating releases - working with GitHub Actions ### NOTE: gh does not use the default repository for managing repository and environment secrets.`) } type iprompter interface { Select(string, string, []string) (int, error) } type SetDefaultOptions struct { IO *iostreams.IOStreams Remotes func() (context.Remotes, error) HttpClient func() (*http.Client, error) Prompter iprompter GitClient *git.Client Repo ghrepo.Interface ViewMode bool UnsetMode bool } func NewCmdSetDefault(f *cmdutil.Factory, runF func(*SetDefaultOptions) error) *cobra.Command { opts := &SetDefaultOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, Remotes: f.Remotes, Prompter: f.Prompter, GitClient: f.GitClient, } cmd := &cobra.Command{ Use: "set-default [<repository>]", Short: "Configure default repository for this directory", Long: explainer(), Example: heredoc.Doc(` # Interactively select a default repository $ gh repo set-default # Set a repository explicitly $ gh repo set-default owner/repo # View the current default repository $ gh repo set-default --view # Show more repository options in the interactive picker $ git remote add newrepo https://github.com/owner/repo $ gh repo set-default `), Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { if len(args) > 0 { var err error opts.Repo, err = ghrepo.FromFullName(args[0]) if err != nil { return err } } if !opts.ViewMode && !opts.IO.CanPrompt() && opts.Repo == nil { return cmdutil.FlagErrorf("repository required when not running interactively") } if isLocal, err := opts.GitClient.IsLocalGitRepo(cmd.Context()); err != nil { return err } else if !isLocal { return errors.New("must be run from inside a git repository") } if runF != nil { return runF(opts) } return setDefaultRun(opts) }, } cmd.Flags().BoolVarP(&opts.ViewMode, "view", "v", false, "View the current default repository") cmd.Flags().BoolVarP(&opts.UnsetMode, "unset", "u", false, "Unset the current default repository") return cmd } func setDefaultRun(opts *SetDefaultOptions) error { remotes, err := opts.Remotes() if err != nil { return err } currentDefaultRepo, _ := remotes.ResolvedRemote() cs := opts.IO.ColorScheme() if opts.ViewMode { if currentDefaultRepo != nil { fmt.Fprintln(opts.IO.Out, displayRemoteRepoName(currentDefaultRepo)) } else { fmt.Fprintf(opts.IO.ErrOut, "%s No default remote repository has been set. To learn more about the default repository, run: gh repo set-default --help\n", cs.FailureIcon()) } return nil } if opts.UnsetMode { var msg string if currentDefaultRepo != nil { if err := opts.GitClient.UnsetRemoteResolution( ctx.Background(), currentDefaultRepo.Name); err != nil { return err } msg = fmt.Sprintf("%s Unset %s as default repository", cs.SuccessIcon(), ghrepo.FullName(currentDefaultRepo)) } else { msg = "no default repository has been set" } if opts.IO.IsStdoutTTY() { fmt.Fprintln(opts.IO.Out, msg) } return nil } httpClient, err := opts.HttpClient() if err != nil { return err } apiClient := api.NewClientFromHTTP(httpClient) resolvedRemotes, err := context.ResolveRemotesToRepos(remotes, apiClient, "") if err != nil { return err } knownRepos, err := resolvedRemotes.NetworkRepos(0) if err != nil { return err } if len(knownRepos) == 0 { return errors.New("none of the git remotes correspond to a valid remote repository") } var selectedRepo ghrepo.Interface if opts.Repo != nil { for _, knownRepo := range knownRepos { if ghrepo.IsSame(opts.Repo, knownRepo) { selectedRepo = opts.Repo break } } if selectedRepo == nil { return fmt.Errorf("%s does not correspond to any git remotes", ghrepo.FullName(opts.Repo)) } } if selectedRepo == nil { if len(knownRepos) == 1 { selectedRepo = knownRepos[0] fmt.Fprintf(opts.IO.Out, "Found only one known remote repo, %s on %s.\n", cs.Bold(ghrepo.FullName(selectedRepo)), cs.Bold(selectedRepo.RepoHost())) } else { var repoNames []string current := "" if currentDefaultRepo != nil { current = ghrepo.FullName(currentDefaultRepo) } for _, knownRepo := range knownRepos { repoNames = append(repoNames, ghrepo.FullName(knownRepo)) } fmt.Fprintln(opts.IO.Out, explainer()) fmt.Fprintln(opts.IO.Out) selected, err := opts.Prompter.Select("Which repository should be the default?", current, repoNames) if err != nil { return fmt.Errorf("could not prompt: %w", err) } selectedName := repoNames[selected] owner, repo, _ := strings.Cut(selectedName, "/") selectedRepo = ghrepo.New(owner, repo) } } resolution := "base" selectedRemote, _ := resolvedRemotes.RemoteForRepo(selectedRepo) if selectedRemote == nil { sort.Stable(remotes) selectedRemote = remotes[0] resolution = ghrepo.FullName(selectedRepo) } if currentDefaultRepo != nil { if err := opts.GitClient.UnsetRemoteResolution( ctx.Background(), currentDefaultRepo.Name); err != nil { return err } } if err = opts.GitClient.SetRemoteResolution( ctx.Background(), selectedRemote.Name, resolution); err != nil { return err } if opts.IO.IsStdoutTTY() { cs := opts.IO.ColorScheme() fmt.Fprintf(opts.IO.Out, "%s Set %s as the default repository for the current directory\n", cs.SuccessIcon(), ghrepo.FullName(selectedRepo)) } return nil } func displayRemoteRepoName(remote *context.Remote) string { if remote.Resolved == "" || remote.Resolved == "base" { return ghrepo.FullName(remote) } repo, err := ghrepo.FromFullName(remote.Resolved) if err != nil { return ghrepo.FullName(remote) } return ghrepo.FullName(repo) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/fork/fork.go
pkg/cmd/repo/fork/fork.go
package fork import ( "context" "errors" "fmt" "net/http" "net/url" "strings" "time" "github.com/MakeNowJust/heredoc" "github.com/cenkalti/backoff/v4" "github.com/cli/cli/v2/api" ghContext "github.com/cli/cli/v2/context" "github.com/cli/cli/v2/git" "github.com/cli/cli/v2/internal/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" "github.com/spf13/pflag" ) const defaultRemoteName = "origin" type iprompter interface { Confirm(string, bool) (bool, error) } type ForkOptions struct { HttpClient func() (*http.Client, error) GitClient *git.Client Config func() (gh.Config, error) IO *iostreams.IOStreams BaseRepo func() (ghrepo.Interface, error) Remotes func() (ghContext.Remotes, error) Since func(time.Time) time.Duration BackOff backoff.BackOff Prompter iprompter GitArgs []string Repository string Clone bool Remote bool PromptClone bool PromptRemote bool RemoteName string Organization string ForkName string Rename bool DefaultBranchOnly bool } type errWithExitCode interface { ExitCode() int } // TODO warn about useless flags (--remote, --remote-name) when running from outside a repository // TODO output over STDOUT not STDERR // TODO remote-name has no effect on its own; error that or change behavior func NewCmdFork(f *cmdutil.Factory, runF func(*ForkOptions) error) *cobra.Command { opts := &ForkOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, GitClient: f.GitClient, Config: f.Config, BaseRepo: f.BaseRepo, Remotes: f.Remotes, Prompter: f.Prompter, Since: time.Since, } cmd := &cobra.Command{ Use: "fork [<repository>] [-- <gitflags>...]", Args: func(cmd *cobra.Command, args []string) error { if cmd.ArgsLenAtDash() == 0 && len(args[1:]) > 0 { return cmdutil.FlagErrorf("repository argument required when passing git clone flags") } return nil }, Short: "Create a fork of a repository", Long: heredoc.Docf(` Create a fork of a repository. With no argument, creates a fork of the current repository. Otherwise, forks the specified repository. By default, the new fork is set to be your %[1]sorigin%[1]s remote and any existing origin remote is renamed to %[1]supstream%[1]s. To alter this behavior, you can set a name for the new fork's remote with %[1]s--remote-name%[1]s. The %[1]supstream%[1]s remote will be set as the default remote repository. Additional %[1]sgit clone%[1]s flags can be passed after %[1]s--%[1]s. `, "`"), RunE: func(cmd *cobra.Command, args []string) error { promptOk := opts.IO.CanPrompt() if len(args) > 0 { opts.Repository = args[0] opts.GitArgs = args[1:] } if cmd.Flags().Changed("org") && opts.Organization == "" { return cmdutil.FlagErrorf("--org cannot be blank") } if opts.RemoteName == "" { return cmdutil.FlagErrorf("--remote-name cannot be blank") } else if !cmd.Flags().Changed("remote-name") { opts.Rename = true // Any existing 'origin' will be renamed to upstream } if promptOk { // We can prompt for these if they were not specified. opts.PromptClone = !cmd.Flags().Changed("clone") opts.PromptRemote = !cmd.Flags().Changed("remote") } if runF != nil { return runF(opts) } return forkRun(opts) }, } 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) }) cmd.Flags().BoolVar(&opts.Clone, "clone", false, "Clone the fork") cmd.Flags().BoolVar(&opts.Remote, "remote", false, "Add a git remote for the fork") cmd.Flags().StringVar(&opts.RemoteName, "remote-name", defaultRemoteName, "Specify the name for the new remote") cmd.Flags().StringVar(&opts.Organization, "org", "", "Create the fork in an organization") cmd.Flags().StringVar(&opts.ForkName, "fork-name", "", "Rename the forked repository") cmd.Flags().BoolVar(&opts.DefaultBranchOnly, "default-branch-only", false, "Only include the default branch in the fork") return cmd } func forkRun(opts *ForkOptions) error { var repoToFork ghrepo.Interface var err error inParent := false // whether or not we're forking the repo we're currently "in" if opts.Repository == "" { baseRepo, err := opts.BaseRepo() if err != nil { return fmt.Errorf("unable to determine base repository: %w", err) } inParent = true repoToFork = baseRepo } else { repoArg := opts.Repository if isURL(repoArg) { parsedURL, err := url.Parse(repoArg) if err != nil { return fmt.Errorf("did not understand argument: %w", err) } repoToFork, err = ghrepo.FromURL(parsedURL) if err != nil { return fmt.Errorf("did not understand argument: %w", err) } } else if strings.HasPrefix(repoArg, "git@") { parsedURL, err := git.ParseURL(repoArg) if err != nil { return fmt.Errorf("did not understand argument: %w", err) } repoToFork, err = ghrepo.FromURL(parsedURL) if err != nil { return fmt.Errorf("did not understand argument: %w", err) } } else { repoToFork, err = ghrepo.FromFullName(repoArg) if err != nil { return fmt.Errorf("argument error: %w", err) } } } connectedToTerminal := opts.IO.IsStdoutTTY() && opts.IO.IsStderrTTY() && opts.IO.IsStdinTTY() cs := opts.IO.ColorScheme() stderr := opts.IO.ErrOut httpClient, err := opts.HttpClient() if err != nil { return fmt.Errorf("unable to create client: %w", err) } apiClient := api.NewClientFromHTTP(httpClient) opts.IO.StartProgressIndicator() forkedRepo, err := api.ForkRepo(apiClient, repoToFork, opts.Organization, opts.ForkName, opts.DefaultBranchOnly) opts.IO.StopProgressIndicator() if err != nil { return fmt.Errorf("failed to fork: %w", err) } // This is weird. There is not an efficient way to determine via the GitHub API whether or not a // given user has forked a given repo. We noticed, also, that the create fork API endpoint just // returns the fork repo data even if it already exists -- with no change in status code or // anything. We thus check the created time to see if the repo is brand new or not; if it's not, // we assume the fork already existed and report an error. createdAgo := opts.Since(forkedRepo.CreatedAt) if createdAgo > time.Minute { if connectedToTerminal { fmt.Fprintf(stderr, "%s %s %s\n", cs.Yellow("!"), cs.Bold(ghrepo.FullName(forkedRepo)), "already exists") } else { fmt.Fprintf(stderr, "%s already exists\n", ghrepo.FullName(forkedRepo)) } } else { if connectedToTerminal { fmt.Fprintf(stderr, "%s Created fork %s\n", cs.SuccessIconWithColor(cs.Green), cs.Bold(ghrepo.FullName(forkedRepo))) } else { fmt.Fprintln(opts.IO.Out, ghrepo.GenerateRepoURL(forkedRepo, "")) } } // Rename the new repo if necessary if opts.ForkName != "" && !strings.EqualFold(forkedRepo.RepoName(), shared.NormalizeRepoName(opts.ForkName)) { forkedRepo, err = api.RenameRepo(apiClient, forkedRepo, opts.ForkName) if err != nil { return fmt.Errorf("could not rename fork: %w", err) } if connectedToTerminal { fmt.Fprintf(stderr, "%s Renamed fork to %s\n", cs.SuccessIconWithColor(cs.Green), cs.Bold(ghrepo.FullName(forkedRepo))) } } if (inParent && (!opts.Remote && !opts.PromptRemote)) || (!inParent && (!opts.Clone && !opts.PromptClone)) { return nil } cfg, err := opts.Config() if err != nil { return err } protocolConfig := cfg.GitProtocol(repoToFork.RepoHost()) protocolIsConfiguredByUser := protocolConfig.Source == gh.ConfigUserProvided protocol := protocolConfig.Value gitClient := opts.GitClient ctx := context.Background() if inParent { remotes, err := opts.Remotes() if err != nil { return err } if !protocolIsConfiguredByUser { if remote, err := remotes.FindByRepo(repoToFork.RepoOwner(), repoToFork.RepoName()); err == nil { scheme := "" if remote.FetchURL != nil { scheme = remote.FetchURL.Scheme } if remote.PushURL != nil { scheme = remote.PushURL.Scheme } if scheme != "" { protocol = scheme } else { protocol = "https" } } } if remote, err := remotes.FindByRepo(forkedRepo.RepoOwner(), forkedRepo.RepoName()); err == nil { if connectedToTerminal { fmt.Fprintf(stderr, "%s Using existing remote %s\n", cs.SuccessIcon(), cs.Bold(remote.Name)) } return nil } remoteDesired := opts.Remote if opts.PromptRemote { remoteDesired, err = opts.Prompter.Confirm("Would you like to add a remote for the fork?", false) if err != nil { return err } } if remoteDesired { remoteName := opts.RemoteName remotes, err := opts.Remotes() if err != nil { return err } if _, err := remotes.FindByName(remoteName); err == nil { if opts.Rename { renameTarget := "upstream" renameCmd, err := gitClient.Command(ctx, "remote", "rename", remoteName, renameTarget) if err != nil { return err } _, err = renameCmd.Output() if err != nil { return err } if connectedToTerminal { fmt.Fprintf(stderr, "%s Renamed remote %s to %s\n", cs.SuccessIcon(), cs.Bold(remoteName), cs.Bold(renameTarget)) } } else { return fmt.Errorf("a git remote named '%s' already exists", remoteName) } } forkedRepoCloneURL := ghrepo.FormatRemoteURL(forkedRepo, protocol) _, err = gitClient.AddRemote(ctx, remoteName, forkedRepoCloneURL, []string{}) if err != nil { return fmt.Errorf("failed to add remote: %w", err) } if connectedToTerminal { fmt.Fprintf(stderr, "%s Added remote %s\n", cs.SuccessIcon(), cs.Bold(remoteName)) } } } else { cloneDesired := opts.Clone if opts.PromptClone { cloneDesired, err = opts.Prompter.Confirm("Would you like to clone the fork?", false) if err != nil { return err } } if cloneDesired { // Allow injecting alternative BackOff in tests. if opts.BackOff == nil { bo := backoff.NewConstantBackOff(2 * time.Second) opts.BackOff = bo } cloneDir, err := backoff.RetryWithData(func() (string, error) { forkedRepoURL := ghrepo.FormatRemoteURL(forkedRepo, protocol) dir, err := gitClient.Clone(ctx, forkedRepoURL, opts.GitArgs) if err == nil { return dir, nil } var execError errWithExitCode if errors.As(err, &execError) && execError.ExitCode() == 128 { return "", err } return "", backoff.Permanent(err) }, backoff.WithContext(backoff.WithMaxRetries(opts.BackOff, 3), ctx)) if err != nil { return fmt.Errorf("failed to clone fork: %w", err) } gc := gitClient.Copy() gc.RepoDir = cloneDir upstreamURL := ghrepo.FormatRemoteURL(repoToFork, protocol) upstreamRemote := "upstream" if _, err := gc.AddRemote(ctx, upstreamRemote, upstreamURL, []string{}); err != nil { return err } if err := gc.SetRemoteResolution(ctx, upstreamRemote, "base"); err != nil { return err } if err := gc.Fetch(ctx, upstreamRemote, ""); err != nil { return err } if connectedToTerminal { fmt.Fprintf(stderr, "%s Cloned fork\n", cs.SuccessIcon()) fmt.Fprintf(stderr, "%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(repoToFork))) } } } return nil } func isURL(s string) bool { return strings.HasPrefix(s, "http:/") || strings.HasPrefix(s, "https:/") }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/fork/fork_test.go
pkg/cmd/repo/fork/fork_test.go
package fork import ( "bytes" "io" "net/http" "net/url" "strings" "testing" "time" "github.com/cenkalti/backoff/v4" "github.com/cli/cli/v2/context" "github.com/cli/cli/v2/git" "github.com/cli/cli/v2/internal/config" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/internal/run" "github.com/cli/cli/v2/pkg/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 TestNewCmdFork(t *testing.T) { tests := []struct { name string cli string tty bool wants ForkOptions wantErr bool errMsg string }{ { name: "repo with git args", cli: "foo/bar -- --foo=bar", wants: ForkOptions{ Repository: "foo/bar", GitArgs: []string{"--foo=bar"}, RemoteName: "origin", Rename: true, }, }, { name: "git args without repo", cli: "-- --foo bar", wantErr: true, errMsg: "repository argument required when passing git clone flags", }, { name: "repo", cli: "foo/bar", wants: ForkOptions{ Repository: "foo/bar", RemoteName: "origin", Rename: true, GitArgs: []string{}, }, }, { name: "blank remote name", cli: "--remote --remote-name=''", wantErr: true, errMsg: "--remote-name cannot be blank", }, { name: "remote name", cli: "--remote --remote-name=foo", wants: ForkOptions{ RemoteName: "foo", Rename: false, Remote: true, }, }, { name: "blank nontty", cli: "", wants: ForkOptions{ RemoteName: "origin", Rename: true, Organization: "", }, }, { name: "blank tty", cli: "", tty: true, wants: ForkOptions{ RemoteName: "origin", PromptClone: true, PromptRemote: true, Rename: true, Organization: "", }, }, { name: "clone", cli: "--clone", wants: ForkOptions{ RemoteName: "origin", Rename: true, }, }, { name: "remote", cli: "--remote", wants: ForkOptions{ RemoteName: "origin", Remote: true, Rename: true, }, }, { name: "to org", cli: "--org batmanshome", wants: ForkOptions{ RemoteName: "origin", Remote: false, Rename: false, Organization: "batmanshome", }, }, { name: "empty org", cli: " --org=''", wantErr: true, errMsg: "--org cannot be blank", }, { name: "git flags in wrong place", cli: "--depth 1 OWNER/REPO", wantErr: true, errMsg: "unknown flag: --depth\nSeparate git clone flags with `--`.", }, { name: "with fork name", cli: "--fork-name new-fork", wants: ForkOptions{ Remote: false, RemoteName: "origin", ForkName: "new-fork", Rename: false, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() f := &cmdutil.Factory{ IOStreams: ios, } ios.SetStdoutTTY(tt.tty) ios.SetStdinTTY(tt.tty) argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts *ForkOptions cmd := NewCmdFork(f, func(opts *ForkOptions) 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.wants.RemoteName, gotOpts.RemoteName) assert.Equal(t, tt.wants.Remote, gotOpts.Remote) assert.Equal(t, tt.wants.PromptRemote, gotOpts.PromptRemote) assert.Equal(t, tt.wants.PromptClone, gotOpts.PromptClone) assert.Equal(t, tt.wants.Organization, gotOpts.Organization) assert.Equal(t, tt.wants.GitArgs, gotOpts.GitArgs) }) } } func TestRepoFork(t *testing.T) { forkResult := `{ "node_id": "123", "name": "REPO", "clone_url": "https://github.com/someone/repo.git", "created_at": "2011-01-26T19:01:12Z", "owner": { "login": "someone" } }` forkPost := func(reg *httpmock.Registry) { reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/forks"), httpmock.StringResponse(forkResult)) } tests := []struct { name string opts *ForkOptions tty bool httpStubs func(*httpmock.Registry) execStubs func(*run.CommandStubber) promptStubs func(*prompter.MockPrompter) cfgStubs func(*testing.T, gh.Config) remotes []*context.Remote wantOut string wantErrOut string wantErr bool errMsg string }{ { name: "implicit match, configured protocol overrides provided", tty: true, opts: &ForkOptions{ Remote: true, RemoteName: "fork", }, remotes: []*context.Remote{ { Remote: &git.Remote{Name: "origin", PushURL: &url.URL{ Scheme: "ssh", }}, Repo: ghrepo.New("OWNER", "REPO"), }, }, cfgStubs: func(_ *testing.T, c gh.Config) { c.Set("", "git_protocol", "https") }, httpStubs: forkPost, execStubs: func(cs *run.CommandStubber) { cs.Register(`git remote add fork https://github\.com/someone/REPO\.git`, 0, "") }, wantErrOut: "✓ Created fork someone/REPO\n✓ Added remote fork\n", }, { name: "implicit match, no configured protocol", tty: true, opts: &ForkOptions{ Remote: true, RemoteName: "fork", }, remotes: []*context.Remote{ { Remote: &git.Remote{Name: "origin", PushURL: &url.URL{ Scheme: "ssh", }}, Repo: ghrepo.New("OWNER", "REPO"), }, }, httpStubs: forkPost, execStubs: func(cs *run.CommandStubber) { cs.Register(`git remote add fork git@github\.com:someone/REPO\.git`, 0, "") }, wantErrOut: "✓ Created fork someone/REPO\n✓ Added remote fork\n", }, { name: "implicit with negative interactive choices", tty: true, opts: &ForkOptions{ PromptRemote: true, Rename: true, RemoteName: defaultRemoteName, }, httpStubs: forkPost, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterConfirm("Would you like to add a remote for the fork?", func(_ string, _ bool) (bool, error) { return false, nil }) }, wantErrOut: "✓ Created fork someone/REPO\n", }, { name: "implicit with interactive choices", tty: true, opts: &ForkOptions{ PromptRemote: true, Rename: true, RemoteName: defaultRemoteName, }, httpStubs: forkPost, execStubs: func(cs *run.CommandStubber) { cs.Register("git remote rename origin upstream", 0, "") cs.Register(`git remote add origin https://github.com/someone/REPO.git`, 0, "") }, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterConfirm("Would you like to add a remote for the fork?", func(_ string, _ bool) (bool, error) { return true, nil }) }, wantErrOut: "✓ Created fork someone/REPO\n✓ Renamed remote origin to upstream\n✓ Added remote origin\n", }, { name: "implicit tty reuse existing remote", tty: true, opts: &ForkOptions{ Remote: true, RemoteName: defaultRemoteName, }, remotes: []*context.Remote{ { Remote: &git.Remote{Name: "origin", FetchURL: &url.URL{}}, Repo: ghrepo.New("someone", "REPO"), }, { Remote: &git.Remote{Name: "upstream", FetchURL: &url.URL{}}, Repo: ghrepo.New("OWNER", "REPO"), }, }, httpStubs: forkPost, wantErrOut: "✓ Created fork someone/REPO\n✓ Using existing remote origin\n", }, { name: "implicit tty remote exists", // gh repo fork --remote --remote-name origin | cat tty: true, opts: &ForkOptions{ Remote: true, RemoteName: defaultRemoteName, }, httpStubs: forkPost, wantErr: true, errMsg: "a git remote named 'origin' already exists", }, { name: "implicit tty current owner forked", tty: true, opts: &ForkOptions{ Repository: "someone/REPO", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("POST", "repos/someone/REPO/forks"), httpmock.StringResponse(forkResult)) }, wantErr: true, errMsg: "failed to fork: someone/REPO cannot be forked", }, { name: "implicit tty already forked", tty: true, opts: &ForkOptions{ Since: func(t time.Time) time.Duration { return 120 * time.Second }, }, httpStubs: forkPost, wantErrOut: "! someone/REPO already exists\n", }, { name: "implicit tty --remote", tty: true, opts: &ForkOptions{ Remote: true, RemoteName: defaultRemoteName, Rename: true, }, httpStubs: forkPost, execStubs: func(cs *run.CommandStubber) { cs.Register("git remote rename origin upstream", 0, "") cs.Register(`git remote add origin https://github.com/someone/REPO.git`, 0, "") }, wantErrOut: "✓ Created fork someone/REPO\n✓ Renamed remote origin to upstream\n✓ Added remote origin\n", }, { name: "implicit nontty reuse existing remote", opts: &ForkOptions{ Remote: true, RemoteName: defaultRemoteName, Rename: true, }, remotes: []*context.Remote{ { Remote: &git.Remote{Name: "origin", FetchURL: &url.URL{}}, Repo: ghrepo.New("someone", "REPO"), }, { Remote: &git.Remote{Name: "upstream", FetchURL: &url.URL{}}, Repo: ghrepo.New("OWNER", "REPO"), }, }, httpStubs: forkPost, wantOut: "https://github.com/someone/REPO\n", }, { name: "implicit nontty remote exists", // gh repo fork --remote --remote-name origin | cat opts: &ForkOptions{ Remote: true, RemoteName: defaultRemoteName, }, httpStubs: forkPost, wantErr: true, errMsg: "a git remote named 'origin' already exists", }, { name: "implicit nontty already forked", opts: &ForkOptions{ Since: func(t time.Time) time.Duration { return 120 * time.Second }, }, httpStubs: forkPost, wantErrOut: "someone/REPO already exists\n", }, { name: "implicit nontty --remote", opts: &ForkOptions{ Remote: true, RemoteName: defaultRemoteName, Rename: true, }, httpStubs: forkPost, execStubs: func(cs *run.CommandStubber) { cs.Register("git remote rename origin upstream", 0, "") cs.Register(`git remote add origin https://github.com/someone/REPO.git`, 0, "") }, wantOut: "https://github.com/someone/REPO\n", }, { name: "implicit nontty no args", opts: &ForkOptions{}, httpStubs: forkPost, wantOut: "https://github.com/someone/REPO\n", }, { name: "passes git flags", tty: true, opts: &ForkOptions{ Repository: "OWNER/REPO", GitArgs: []string{"--depth", "1"}, Clone: true, }, httpStubs: forkPost, execStubs: func(cs *run.CommandStubber) { cs.Register(`git clone --depth 1 https://github.com/someone/REPO\.git`, 0, "") cs.Register(`git -C REPO remote add upstream https://github\.com/OWNER/REPO\.git`, 0, "") cs.Register(`git -C REPO fetch upstream`, 0, "") cs.Register(`git -C REPO config --add remote.upstream.gh-resolved base`, 0, "") }, wantErrOut: "✓ Created fork someone/REPO\n✓ Cloned fork\n! Repository OWNER/REPO set as the default repository. To learn more about the default repository, run: gh repo set-default --help\n", }, { name: "repo arg fork to org", tty: true, opts: &ForkOptions{ Repository: "OWNER/REPO", Organization: "gamehendge", Clone: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/forks"), func(req *http.Request) (*http.Response, error) { bb, err := io.ReadAll(req.Body) if err != nil { return nil, err } assert.Equal(t, `{"organization":"gamehendge"}`, strings.TrimSpace(string(bb))) return &http.Response{ Request: req, StatusCode: 200, Body: io.NopCloser(bytes.NewBufferString(`{"name":"REPO", "owner":{"login":"gamehendge"}}`)), }, nil }) }, execStubs: func(cs *run.CommandStubber) { cs.Register(`git clone https://github.com/gamehendge/REPO\.git`, 0, "") cs.Register(`git -C REPO remote add upstream https://github\.com/OWNER/REPO\.git`, 0, "") cs.Register(`git -C REPO fetch upstream`, 0, "") cs.Register(`git -C REPO config --add remote.upstream.gh-resolved base`, 0, "") }, wantErrOut: "✓ Created fork gamehendge/REPO\n✓ Cloned fork\n! Repository OWNER/REPO set as the default repository. To learn more about the default repository, run: gh repo set-default --help\n", }, { name: "repo arg url arg", tty: true, opts: &ForkOptions{ Repository: "https://github.com/OWNER/REPO.git", Clone: true, }, httpStubs: forkPost, execStubs: func(cs *run.CommandStubber) { cs.Register(`git clone https://github.com/someone/REPO\.git`, 0, "") cs.Register(`git -C REPO remote add upstream https://github\.com/OWNER/REPO\.git`, 0, "") cs.Register(`git -C REPO fetch upstream`, 0, "") cs.Register(`git -C REPO config --add remote.upstream.gh-resolved base`, 0, "") }, wantErrOut: "✓ Created fork someone/REPO\n✓ Cloned fork\n! Repository OWNER/REPO set as the default repository. To learn more about the default repository, run: gh repo set-default --help\n", }, { name: "repo arg interactive no clone", tty: true, opts: &ForkOptions{ Repository: "OWNER/REPO", PromptClone: true, }, httpStubs: forkPost, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterConfirm("Would you like to clone the fork?", func(_ string, _ bool) (bool, error) { return false, nil }) }, wantErrOut: "✓ Created fork someone/REPO\n", }, { name: "repo arg interactive", tty: true, opts: &ForkOptions{ Repository: "OWNER/REPO", PromptClone: true, }, httpStubs: forkPost, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterConfirm("Would you like to clone the fork?", func(_ string, _ bool) (bool, error) { return true, nil }) }, execStubs: func(cs *run.CommandStubber) { cs.Register(`git clone https://github.com/someone/REPO\.git`, 0, "") cs.Register(`git -C REPO remote add upstream https://github\.com/OWNER/REPO\.git`, 0, "") cs.Register(`git -C REPO fetch upstream`, 0, "") cs.Register(`git -C REPO config --add remote.upstream.gh-resolved base`, 0, "") }, wantErrOut: "✓ Created fork someone/REPO\n✓ Cloned fork\n! Repository OWNER/REPO set as the default repository. To learn more about the default repository, run: gh repo set-default --help\n", }, { name: "repo arg interactive already forked", tty: true, opts: &ForkOptions{ Repository: "OWNER/REPO", PromptClone: true, Since: func(t time.Time) time.Duration { return 120 * time.Second }, }, httpStubs: forkPost, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterConfirm("Would you like to clone the fork?", func(_ string, _ bool) (bool, error) { return true, nil }) }, execStubs: func(cs *run.CommandStubber) { cs.Register(`git clone https://github.com/someone/REPO\.git`, 0, "") cs.Register(`git -C REPO remote add upstream https://github\.com/OWNER/REPO\.git`, 0, "") cs.Register(`git -C REPO fetch upstream`, 0, "") cs.Register(`git -C REPO config --add remote.upstream.gh-resolved base`, 0, "") }, wantErrOut: "! someone/REPO already exists\n✓ Cloned fork\n! Repository OWNER/REPO set as the default repository. To learn more about the default repository, run: gh repo set-default --help\n", }, { name: "repo arg nontty no flags", opts: &ForkOptions{ Repository: "OWNER/REPO", }, httpStubs: forkPost, wantOut: "https://github.com/someone/REPO\n", }, { name: "repo arg nontty repo already exists", opts: &ForkOptions{ Repository: "OWNER/REPO", Since: func(t time.Time) time.Duration { return 120 * time.Second }, }, httpStubs: forkPost, wantErrOut: "someone/REPO already exists\n", }, { name: "repo arg nontty clone arg already exists", opts: &ForkOptions{ Repository: "OWNER/REPO", Clone: true, Since: func(t time.Time) time.Duration { return 120 * time.Second }, }, httpStubs: forkPost, execStubs: func(cs *run.CommandStubber) { cs.Register(`git clone https://github.com/someone/REPO\.git`, 0, "") cs.Register(`git -C REPO remote add upstream https://github\.com/OWNER/REPO\.git`, 0, "") cs.Register(`git -C REPO fetch upstream`, 0, "") cs.Register(`git -C REPO config --add remote.upstream.gh-resolved base`, 0, "") }, wantErrOut: "someone/REPO already exists\n", }, { name: "repo arg nontty clone arg", opts: &ForkOptions{ Repository: "OWNER/REPO", Clone: true, }, httpStubs: forkPost, execStubs: func(cs *run.CommandStubber) { cs.Register(`git clone https://github.com/someone/REPO\.git`, 0, "") cs.Register(`git -C REPO remote add upstream https://github\.com/OWNER/REPO\.git`, 0, "") cs.Register(`git -C REPO fetch upstream`, 0, "") cs.Register(`git -C REPO config --add remote.upstream.gh-resolved base`, 0, "") }, wantOut: "https://github.com/someone/REPO\n", }, { name: "non tty repo arg with fork-name", opts: &ForkOptions{ Repository: "someone/REPO", Clone: false, ForkName: "NEW_REPO", }, tty: false, httpStubs: func(reg *httpmock.Registry) { forkResult := `{ "node_id": "123", "name": "REPO", "clone_url": "https://github.com/OWNER/REPO.git", "created_at": "2011-01-26T19:01:12Z", "owner": { "login": "OWNER" } }` renameResult := `{ "node_id": "1234", "name": "NEW_REPO", "clone_url": "https://github.com/OWNER/NEW_REPO.git", "created_at": "2012-01-26T19:01:12Z", "owner": { "login": "OWNER" } }` reg.Register( httpmock.REST("POST", "repos/someone/REPO/forks"), httpmock.StringResponse(forkResult)) reg.Register( httpmock.REST("PATCH", "repos/OWNER/REPO"), httpmock.StringResponse(renameResult)) }, wantErrOut: "", wantOut: "https://github.com/OWNER/REPO\n", }, { name: "tty repo arg with fork-name", opts: &ForkOptions{ Repository: "someone/REPO", Clone: false, ForkName: "NEW_REPO", }, tty: true, httpStubs: func(reg *httpmock.Registry) { forkResult := `{ "node_id": "123", "name": "REPO", "clone_url": "https://github.com/OWNER/REPO.git", "created_at": "2011-01-26T19:01:12Z", "owner": { "login": "OWNER" } }` renameResult := `{ "node_id": "1234", "name": "NEW_REPO", "clone_url": "https://github.com/OWNER/NEW_REPO.git", "created_at": "2012-01-26T19:01:12Z", "owner": { "login": "OWNER" } }` reg.Register( httpmock.REST("POST", "repos/someone/REPO/forks"), httpmock.StringResponse(forkResult)) reg.Register( httpmock.REST("PATCH", "repos/OWNER/REPO"), httpmock.StringResponse(renameResult)) }, wantErrOut: "✓ Created fork OWNER/REPO\n✓ Renamed fork to OWNER/NEW_REPO\n", }, { name: "retries clone up to four times if necessary", opts: &ForkOptions{ Repository: "OWNER/REPO", Clone: true, BackOff: &backoff.ZeroBackOff{}, }, httpStubs: forkPost, execStubs: func(cs *run.CommandStubber) { cs.Register(`git clone https://github.com/someone/REPO\.git`, 128, "") cs.Register(`git clone https://github.com/someone/REPO\.git`, 128, "") cs.Register(`git clone https://github.com/someone/REPO\.git`, 128, "") cs.Register(`git clone https://github.com/someone/REPO\.git`, 0, "") cs.Register(`git -C REPO remote add upstream https://github\.com/OWNER/REPO\.git`, 0, "") cs.Register(`git -C REPO fetch upstream`, 0, "") cs.Register(`git -C REPO config --add remote.upstream.gh-resolved base`, 0, "") }, wantOut: "https://github.com/someone/REPO\n", }, { name: "does not retry clone if error occurs and exit code is not 128", opts: &ForkOptions{ Repository: "OWNER/REPO", Clone: true, BackOff: &backoff.ZeroBackOff{}, }, httpStubs: forkPost, execStubs: func(cs *run.CommandStubber) { cs.Register(`git clone https://github.com/someone/REPO\.git`, 128, "") cs.Register(`git clone https://github.com/someone/REPO\.git`, 65, "") }, wantErr: true, errMsg: `failed to clone fork: failed to run git: git -c credential.helper= -c credential.helper=!"[^"]+" auth git-credential clone https://github.com/someone/REPO\.git exited with status 65`, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, stdout, stderr := iostreams.Test() ios.SetStdinTTY(tt.tty) ios.SetStdoutTTY(tt.tty) ios.SetStderrTTY(tt.tty) tt.opts.IO = ios tt.opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil } reg := &httpmock.Registry{} if tt.httpStubs != nil { tt.httpStubs(reg) } tt.opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } cfg, _ := config.NewIsolatedTestConfig(t) if tt.cfgStubs != nil { tt.cfgStubs(t, cfg) } tt.opts.Config = func() (gh.Config, error) { return cfg, nil } tt.opts.Remotes = func() (context.Remotes, error) { if tt.remotes == nil { return []*context.Remote{ { Remote: &git.Remote{ Name: "origin", FetchURL: &url.URL{}, }, Repo: ghrepo.New("OWNER", "REPO"), }, }, nil } return tt.remotes, nil } tt.opts.GitClient = &git.Client{ GhPath: "some/path/gh", GitPath: "some/path/git", } pm := prompter.NewMockPrompter(t) tt.opts.Prompter = pm if tt.promptStubs != nil { tt.promptStubs(pm) } cs, restoreRun := run.Stub() defer restoreRun(t) if tt.execStubs != nil { tt.execStubs(cs) } if tt.opts.Since == nil { tt.opts.Since = func(t time.Time) time.Duration { return 2 * time.Second } } defer reg.Verify(t) err := forkRun(tt.opts) if tt.wantErr { assert.Error(t, err, tt.errMsg) return } 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/repo/license/license.go
pkg/cmd/repo/license/license.go
package license import ( cmdList "github.com/cli/cli/v2/pkg/cmd/repo/license/list" cmdView "github.com/cli/cli/v2/pkg/cmd/repo/license/view" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/spf13/cobra" ) func NewCmdLicense(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "license <command>", Short: "Explore repository licenses", } 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/license/list/list_test.go
pkg/cmd/repo/license/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: "license list tty", isTTY: true, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "licenses"), httpmock.StringResponse(`[ { "key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZW1pdA==" }, { "key": "lgpl-3.0", "name": "GNU Lesser General Public License v3.0", "spdx_id": "LGPL-3.0", "url": "https://api.github.com/licenses/lgpl-3.0", "node_id": "MDc6TGljZW5zZW1pdA==" }, { "key": "mpl-2.0", "name": "Mozilla Public License 2.0", "spdx_id": "MPL-2.0", "url": "https://api.github.com/licenses/mpl-2.0", "node_id": "MDc6TGljZW5zZW1pdA==" }, { "key": "agpl-3.0", "name": "GNU Affero General Public License v3.0", "spdx_id": "AGPL-3.0", "url": "https://api.github.com/licenses/agpl-3.0", "node_id": "MDc6TGljZW5zZW1pdA==" }, { "key": "unlicense", "name": "The Unlicense", "spdx_id": "Unlicense", "url": "https://api.github.com/licenses/unlicense", "node_id": "MDc6TGljZW5zZW1pdA==" }, { "key": "apache-2.0", "name": "Apache License 2.0", "spdx_id": "Apache-2.0", "url": "https://api.github.com/licenses/apache-2.0", "node_id": "MDc6TGljZW5zZW1pdA==" }, { "key": "gpl-3.0", "name": "GNU General Public License v3.0", "spdx_id": "GPL-3.0", "url": "https://api.github.com/licenses/gpl-3.0", "node_id": "MDc6TGljZW5zZW1pdA==" } ]`, )) }, wantStdout: heredoc.Doc(` LICENSE KEY SPDX ID LICENSE NAME mit MIT MIT License lgpl-3.0 LGPL-3.0 GNU Lesser General Public License v3.0 mpl-2.0 MPL-2.0 Mozilla Public License 2.0 agpl-3.0 AGPL-3.0 GNU Affero General Public License v3.0 unlicense Unlicense The Unlicense apache-2.0 Apache-2.0 Apache License 2.0 gpl-3.0 GPL-3.0 GNU General Public License v3.0 `), wantStderr: "", opts: &ListOptions{}, }, { name: "license list no license templates tty", isTTY: true, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "licenses"), httpmock.StringResponse(`[]`), ) }, wantStdout: "", wantStderr: "", wantErr: true, errMsg: "No repository licenses 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/license/list/list.go
pkg/cmd/repo/license/list/list.go
package list 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/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 common repository licenses", Long: heredoc.Doc(` List common repository licenses. For even more licenses, visit <https://choosealicense.com/appendix> `), 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() licenses, err := api.RepoLicenses(client, hostname) if err != nil { return err } if len(licenses) == 0 { return cmdutil.NewNoResultsError("No repository licenses found") } return renderLicensesTable(licenses, opts) } func renderLicensesTable(licenses []api.License, opts *ListOptions) error { t := tableprinter.New(opts.IO, tableprinter.WithHeader("LICENSE KEY", "SPDX ID", "LICENSE NAME")) for _, l := range licenses { t.AddField(l.Key) t.AddField(l.SPDXID) t.AddField(l.Name) 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/license/view/view.go
pkg/cmd/repo/license/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/browser" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/text" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type ViewOptions struct { IO *iostreams.IOStreams HTTPClient func() (*http.Client, error) Config func() (gh.Config, error) License string Web bool Browser browser.Browser } func NewCmdView(f *cmdutil.Factory, runF func(*ViewOptions) error) *cobra.Command { opts := &ViewOptions{ IO: f.IOStreams, HTTPClient: f.HttpClient, Config: f.Config, Browser: f.Browser, } cmd := &cobra.Command{ Use: "view {<license-key> | <spdx-id>}", Short: "View a specific repository license", Long: heredoc.Docf(` View a specific repository license by license key or SPDX ID. Run %[1]sgh repo license list%[1]s to see available commonly used licenses. For even more licenses, visit <https://choosealicense.com/appendix>. `, "`"), Example: heredoc.Doc(` # View the MIT license from SPDX ID $ gh repo license view MIT # View the MIT license from license key $ gh repo license view mit # View the GNU AGPL-3.0 license from SPDX ID $ gh repo license view AGPL-3.0 # View the GNU AGPL-3.0 license from license key $ gh repo license view agpl-3.0 # Create a LICENSE.md with the MIT license $ gh repo license view MIT > LICENSE.md `), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.License = args[0] if runF != nil { return runF(opts) } return viewRun(opts) }, } cmd.Flags().BoolVarP(&opts.Web, "web", "w", false, "Open https://choosealicense.com/ in the browser") return cmd } func viewRun(opts *ViewOptions) error { if opts.License == "" { return errors.New("no license 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() license, err := api.RepoLicense(client, hostname, opts.License) if err != nil { var httpErr api.HTTPError if errors.As(err, &httpErr) { if httpErr.StatusCode == 404 { return fmt.Errorf("'%s' is not a valid license name or SPDX ID.\n\nRun `gh repo license list` to see available commonly used licenses. For even more licenses, visit %s", opts.License, text.DisplayURL("https://choosealicense.com/appendix")) } } return err } if opts.Web { url := fmt.Sprintf("https://choosealicense.com/licenses/%s", license.Key) if opts.IO.IsStdoutTTY() { fmt.Fprintf(opts.IO.Out, "Opening %s in your browser.\n", text.DisplayURL(url)) } return opts.Browser.Browse(url) } return renderLicense(license, opts) } func renderLicense(license *api.License, opts *ViewOptions) error { cs := opts.IO.ColorScheme() var out strings.Builder if opts.IO.IsStdoutTTY() { out.WriteString(fmt.Sprintf("\n%s\n", cs.Muted(license.Description))) out.WriteString(fmt.Sprintf("\n%s\n", cs.Mutedf("To implement: %s", license.Implementation))) out.WriteString(fmt.Sprintf("\n%s\n\n", cs.Mutedf("For more information, see: %s", license.HTMLURL))) } out.WriteString(license.Body) _, 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/license/view/view_test.go
pkg/cmd/repo/license/view/view_test.go
package view import ( "bytes" "net/http" "testing" "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/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 TestNewCmdView(t *testing.T) { tests := []struct { name string args []string wantErr bool wantOpts *ViewOptions tty bool }{ { name: "No license key or SPDX ID provided", args: []string{}, wantErr: true, wantOpts: &ViewOptions{ License: "", }, }, { name: "Happy path single license key", args: []string{"mit"}, wantErr: false, wantOpts: &ViewOptions{ License: "mit", }, }, { name: "Happy path too many license keys", args: []string{"mit", "apache-2.0"}, wantErr: true, wantOpts: &ViewOptions{ License: "", }, }, } 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.License, tt.wantOpts.License) }) } } func TestViewRun(t *testing.T) { tests := []struct { name string opts *ViewOptions isTTY bool httpStubs func(reg *httpmock.Registry) wantStdout string wantStderr string wantErr bool errMsg string wantBrowsedURL string }{ { name: "happy path with license no tty", opts: &ViewOptions{License: "mit"}, wantErr: false, isTTY: false, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "licenses/mit"), httpmock.StringResponse(`{ "key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz", "html_url": "http://choosealicense.com/licenses/mit/", "description": "A short and simple permissive license with conditions only requiring preservation of copyright and license notices. Licensed works, modifications, and larger works may be distributed under different terms and without source code.", "implementation": "Create a text file (typically named LICENSE or LICENSE.txt) in the root of your source code and copy the text of the license into the file. Replace [year] with the current year and [fullname] with the name (or names) of the copyright holders.", "permissions": [ "commercial-use", "modifications", "distribution", "private-use" ], "conditions": [ "include-copyright" ], "limitations": [ "liability", "warranty" ], "body": "MIT License\n\nCopyright (c) [year] [fullname]\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n", "featured": true }`)) }, wantStdout: heredoc.Doc(` MIT License Copyright (c) [year] [fullname] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. `), }, { name: "happy path with license tty", opts: &ViewOptions{License: "mit"}, wantErr: false, isTTY: true, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "licenses/mit"), httpmock.StringResponse(`{ "key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz", "html_url": "http://choosealicense.com/licenses/mit/", "description": "A short and simple permissive license with conditions only requiring preservation of copyright and license notices. Licensed works, modifications, and larger works may be distributed under different terms and without source code.", "implementation": "Create a text file (typically named LICENSE or LICENSE.txt) in the root of your source code and copy the text of the license into the file. Replace [year] with the current year and [fullname] with the name (or names) of the copyright holders.", "permissions": [ "commercial-use", "modifications", "distribution", "private-use" ], "conditions": [ "include-copyright" ], "limitations": [ "liability", "warranty" ], "body": "MIT License\n\nCopyright (c) [year] [fullname]\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n", "featured": true }`)) }, wantStdout: heredoc.Doc(` A short and simple permissive license with conditions only requiring preservation of copyright and license notices. Licensed works, modifications, and larger works may be distributed under different terms and without source code. To implement: Create a text file (typically named LICENSE or LICENSE.txt) in the root of your source code and copy the text of the license into the file. Replace [year] with the current year and [fullname] with the name (or names) of the copyright holders. For more information, see: http://choosealicense.com/licenses/mit/ MIT License Copyright (c) [year] [fullname] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. `), }, { name: "License not found", opts: &ViewOptions{License: "404"}, wantErr: true, errMsg: heredoc.Docf(` '404' is not a valid license name or SPDX ID. Run %[1]sgh repo license list%[1]s to see available commonly used licenses. For even more licenses, visit https://choosealicense.com/appendix`, "`"), httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "licenses/404"), httpmock.StatusStringResponse(404, `{ "message": "Not Found", "documentation_url": "https://docs.github.com/rest/licenses/licenses#get-a-license", "status": "404" }`, )) }, }, { name: "web flag happy path", opts: &ViewOptions{ License: "mit", Web: true, }, wantErr: false, isTTY: true, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "licenses/mit"), httpmock.StringResponse(`{ "key": "mit", "name": "MIT License", "spdx_id": "MIT", "url": "https://api.github.com/licenses/mit", "node_id": "MDc6TGljZW5zZTEz", "html_url": "http://choosealicense.com/licenses/mit/", "description": "A short and simple permissive license with conditions only requiring preservation of copyright and license notices. Licensed works, modifications, and larger works may be distributed under different terms and without source code.", "implementation": "Create a text file (typically named LICENSE or LICENSE.txt) in the root of your source code and copy the text of the license into the file. Replace [year] with the current year and [fullname] with the name (or names) of the copyright holders.", "permissions": [ "commercial-use", "modifications", "distribution", "private-use" ], "conditions": [ "include-copyright" ], "limitations": [ "liability", "warranty" ], "body": "MIT License\n\nCopyright (c) [year] [fullname]\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n", "featured": true }`)) }, wantBrowsedURL: "https://choosealicense.com/licenses/mit", wantStdout: "Opening https://choosealicense.com/licenses/mit in your browser.\n", }, } for _, tt := range tests { reg := &httpmock.Registry{} if tt.httpStubs != nil { tt.httpStubs(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 browser := &browser.Stub{} tt.opts.Browser = browser 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()) assert.Equal(t, tt.wantBrowsedURL, browser.BrowsedURL()) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/list/list_test.go
pkg/cmd/repo/list/list_test.go
package list import ( "bytes" "io" "net/http" "strings" "testing" "time" "github.com/MakeNowJust/heredoc" "github.com/google/shlex" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "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/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" ) func TestJSONFields(t *testing.T) { jsonfieldstest.ExpectCommandToSupportJSONFields(t, NewCmdList, []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 TestNewCmdList(t *testing.T) { tests := []struct { name string cli string wants ListOptions wantsErr string }{ { name: "no arguments", cli: "", wants: ListOptions{ Limit: 30, Owner: "", Visibility: "", Fork: false, Source: false, Language: "", Topic: []string(nil), Archived: false, NonArchived: false, }, }, { name: "with owner", cli: "monalisa", wants: ListOptions{ Limit: 30, Owner: "monalisa", Visibility: "", Fork: false, Source: false, Language: "", Topic: []string(nil), Archived: false, NonArchived: false, }, }, { name: "with limit", cli: "-L 101", wants: ListOptions{ Limit: 101, Owner: "", Visibility: "", Fork: false, Source: false, Language: "", Topic: []string(nil), Archived: false, NonArchived: false, }, }, { name: "only public", cli: "--visibility=public", wants: ListOptions{ Limit: 30, Owner: "", Visibility: "public", Fork: false, Source: false, Language: "", Topic: []string(nil), Archived: false, NonArchived: false, }, }, { name: "only private", cli: "--visibility=private", wants: ListOptions{ Limit: 30, Owner: "", Visibility: "private", Fork: false, Source: false, Language: "", Topic: []string(nil), Archived: false, NonArchived: false, }, }, { name: "only forks", cli: "--fork", wants: ListOptions{ Limit: 30, Owner: "", Visibility: "", Fork: true, Source: false, Language: "", Topic: []string(nil), Archived: false, NonArchived: false, }, }, { name: "only sources", cli: "--source", wants: ListOptions{ Limit: 30, Owner: "", Visibility: "", Fork: false, Source: true, Language: "", Topic: []string(nil), Archived: false, NonArchived: false, }, }, { name: "with language", cli: "-l go", wants: ListOptions{ Limit: 30, Owner: "", Visibility: "", Fork: false, Source: false, Language: "go", Topic: []string(nil), Archived: false, NonArchived: false, }, }, { name: "only archived", cli: "--archived", wants: ListOptions{ Limit: 30, Owner: "", Visibility: "", Fork: false, Source: false, Language: "", Topic: []string(nil), Archived: true, NonArchived: false, }, }, { name: "only non-archived", cli: "--no-archived", wants: ListOptions{ Limit: 30, Owner: "", Visibility: "", Fork: false, Source: false, Language: "", Topic: []string(nil), Archived: false, NonArchived: true, }, }, { name: "with topic", cli: "--topic cli", wants: ListOptions{ Limit: 30, Owner: "", Visibility: "", Fork: false, Source: false, Language: "", Topic: []string{"cli"}, Archived: false, NonArchived: false, }, }, { name: "with multiple topic", cli: "--topic cli --topic multiple-topic", wants: ListOptions{ Limit: 30, Owner: "", Visibility: "", Fork: false, Source: false, Language: "", Topic: []string{"cli", "multiple-topic"}, Archived: false, NonArchived: false, }, }, { name: "invalid visibility", cli: "--visibility=bad", wantsErr: "invalid argument \"bad\" for \"--visibility\" flag: valid values are {public|private|internal}", }, { name: "no forks with sources", cli: "--fork --source", wantsErr: "specify only one of `--source` or `--fork`", }, { name: "conflicting archived", cli: "--archived --no-archived", wantsErr: "specify only one of `--archived` or `--no-archived`", }, { name: "too many arguments", cli: "monalisa hubot", wantsErr: "accepts at most 1 arg(s), received 2", }, { name: "invalid limit", cli: "-L 0", wantsErr: "invalid limit: 0", }, } 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 *ListOptions cmd := NewCmdList(f, func(opts *ListOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err = cmd.ExecuteC() if tt.wantsErr != "" { assert.EqualError(t, err, tt.wantsErr) return } require.NoError(t, err) assert.Equal(t, tt.wants.Limit, gotOpts.Limit) assert.Equal(t, tt.wants.Owner, gotOpts.Owner) assert.Equal(t, tt.wants.Visibility, gotOpts.Visibility) assert.Equal(t, tt.wants.Fork, gotOpts.Fork) assert.Equal(t, tt.wants.Topic, gotOpts.Topic) assert.Equal(t, tt.wants.Source, gotOpts.Source) assert.Equal(t, tt.wants.Archived, gotOpts.Archived) assert.Equal(t, tt.wants.NonArchived, gotOpts.NonArchived) }) } } 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 }, } cmd := NewCmdList(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 TestRepoList_nontty(t *testing.T) { ios, _, stdout, stderr := iostreams.Test() ios.SetStdoutTTY(false) ios.SetStdinTTY(false) ios.SetStderrTTY(false) httpReg := &httpmock.Registry{} defer httpReg.Verify(t) httpReg.Register( httpmock.GraphQL(`query RepositoryList\b`), httpmock.FileResponse("./fixtures/repoList.json"), ) opts := ListOptions{ IO: ios, HttpClient: func() (*http.Client, error) { return &http.Client{Transport: httpReg}, nil }, Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, Now: func() time.Time { t, _ := time.Parse(time.RFC822, "19 Feb 21 15:00 UTC") return t }, Limit: 30, } err := listRun(&opts) assert.NoError(t, err) assert.Equal(t, "", stderr.String()) assert.Equal(t, heredoc.Doc(` octocat/hello-world My first repository public 2021-02-19T06:34:58Z octocat/cli GitHub CLI public, fork 2021-02-19T06:06:06Z octocat/testing private 2021-02-11T22:32:05Z `), stdout.String()) } func TestRepoList_tty(t *testing.T) { ios, _, stdout, stderr := iostreams.Test() ios.SetStdoutTTY(true) ios.SetStdinTTY(true) ios.SetStderrTTY(true) httpReg := &httpmock.Registry{} defer httpReg.Verify(t) httpReg.Register( httpmock.GraphQL(`query RepositoryList\b`), httpmock.FileResponse("./fixtures/repoList.json"), ) opts := ListOptions{ IO: ios, HttpClient: func() (*http.Client, error) { return &http.Client{Transport: httpReg}, nil }, Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, Now: func() time.Time { t, _ := time.Parse(time.RFC822, "19 Feb 21 15:00 UTC") return t }, Limit: 30, } err := listRun(&opts) assert.NoError(t, err) assert.Equal(t, "", stderr.String()) assert.Equal(t, heredoc.Doc(` Showing 3 of 3 repositories in @octocat NAME DESCRIPTION INFO UPDATED octocat/hello-world My first repository public about 8 hours ago octocat/cli GitHub CLI public, fork about 8 hours ago octocat/testing private about 7 days ago `), stdout.String()) } func TestRepoList_filtering(t *testing.T) { http := &httpmock.Registry{} defer http.Verify(t) http.Register( httpmock.GraphQL(`query RepositoryList\b`), httpmock.GraphQLQuery(`{}`, func(_ string, params map[string]interface{}) { assert.Equal(t, "PRIVATE", params["privacy"]) assert.Equal(t, float64(2), params["perPage"]) }), ) output, err := runCommand(http, true, `--visibility=private --limit 2 `) if err != nil { t.Fatal(err) } assert.Equal(t, "", output.Stderr()) assert.Equal(t, "\nNo results match your search\n\n", output.String()) } func TestRepoList_noVisibilityField(t *testing.T) { ios, _, stdout, stderr := iostreams.Test() ios.SetStdoutTTY(false) ios.SetStdinTTY(false) ios.SetStderrTTY(false) reg := &httpmock.Registry{} defer reg.Verify(t) reg.Register( httpmock.GraphQL(`query RepositoryList\b`), httpmock.GraphQLQuery(`{"data":{"repositoryOwner":{"login":"octocat","repositories":{"totalCount":0}}}}`, func(query string, params map[string]interface{}) { assert.False(t, strings.Contains(query, "visibility")) }, ), ) opts := ListOptions{ IO: ios, HttpClient: func() (*http.Client, error) { return &http.Client{Transport: reg}, nil }, Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, Now: func() time.Time { t, _ := time.Parse(time.RFC822, "19 Feb 21 15:00 UTC") return t }, Limit: 30, Detector: &fd.DisabledDetectorMock{}, } err := listRun(&opts) assert.NoError(t, err) assert.Equal(t, "", stderr.String()) assert.Equal(t, "", stdout.String()) } func TestRepoList_invalidOwner(t *testing.T) { ios, _, stdout, stderr := iostreams.Test() ios.SetStdoutTTY(false) ios.SetStdinTTY(false) ios.SetStderrTTY(false) reg := &httpmock.Registry{} defer reg.Verify(t) reg.Register( httpmock.GraphQL(`query RepositoryList\b`), httpmock.StringResponse(`{ "data": { "repositoryOwner": null } }`), ) opts := ListOptions{ Owner: "nonexist", IO: ios, HttpClient: func() (*http.Client, error) { return &http.Client{Transport: reg}, nil }, Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, Now: func() time.Time { t, _ := time.Parse(time.RFC822, "19 Feb 21 15:00 UTC") return t }, Limit: 30, Detector: &fd.DisabledDetectorMock{}, } err := listRun(&opts) assert.EqualError(t, err, `the owner handle "nonexist" was not recognized as either a GitHub user or an organization`) assert.Equal(t, "", stderr.String()) assert.Equal(t, "", stdout.String()) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/list/list.go
pkg/cmd/repo/list/list.go
package list import ( "fmt" "net/http" "strings" "time" "github.com/MakeNowJust/heredoc" "github.com/spf13/cobra" "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/tableprinter" "github.com/cli/cli/v2/internal/text" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" ) type ListOptions struct { HttpClient func() (*http.Client, error) Config func() (gh.Config, error) IO *iostreams.IOStreams Exporter cmdutil.Exporter Detector fd.Detector Limit int Owner string Visibility string Fork bool Source bool Language string Topic []string Archived bool NonArchived bool Now func() time.Time } func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Command { opts := ListOptions{ IO: f.IOStreams, Config: f.Config, HttpClient: f.HttpClient, Now: time.Now, } var ( flagPublic bool flagPrivate bool ) cmd := &cobra.Command{ Use: "list [<owner>]", Args: cobra.MaximumNArgs(1), Short: "List repositories owned by user or organization", Long: heredoc.Docf(` List repositories owned by a user or organization. Note that the list will only include repositories owned by the provided argument, and the %[1]s--fork%[1]s or %[1]s--source%[1]s flags will not traverse ownership boundaries. For example, when listing the forks in an organization, the output would not include those owned by individual users. `, "`"), Aliases: []string{"ls"}, RunE: func(c *cobra.Command, args []string) error { if opts.Limit < 1 { return cmdutil.FlagErrorf("invalid limit: %v", opts.Limit) } if err := cmdutil.MutuallyExclusive("specify only one of `--public`, `--private`, or `--visibility`", flagPublic, flagPrivate, opts.Visibility != ""); err != nil { return err } if opts.Source && opts.Fork { return cmdutil.FlagErrorf("specify only one of `--source` or `--fork`") } if opts.Archived && opts.NonArchived { return cmdutil.FlagErrorf("specify only one of `--archived` or `--no-archived`") } if flagPrivate { opts.Visibility = "private" } else if flagPublic { opts.Visibility = "public" } if len(args) > 0 { opts.Owner = args[0] } if runF != nil { return runF(&opts) } return listRun(&opts) }, } cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum number of repositories to list") cmd.Flags().BoolVar(&opts.Source, "source", false, "Show only non-forks") cmd.Flags().BoolVar(&opts.Fork, "fork", false, "Show only forks") cmd.Flags().StringVarP(&opts.Language, "language", "l", "", "Filter by primary coding language") cmd.Flags().StringSliceVarP(&opts.Topic, "topic", "", nil, "Filter by topic") cmdutil.StringEnumFlag(cmd, &opts.Visibility, "visibility", "", "", []string{"public", "private", "internal"}, "Filter by repository visibility") cmd.Flags().BoolVar(&opts.Archived, "archived", false, "Show only archived repositories") cmd.Flags().BoolVar(&opts.NonArchived, "no-archived", false, "Omit archived repositories") cmdutil.AddJSONFlags(cmd, &opts.Exporter, api.RepositoryFields) cmd.Flags().BoolVar(&flagPrivate, "private", false, "Show only private repositories") cmd.Flags().BoolVar(&flagPublic, "public", false, "Show only public repositories") _ = cmd.Flags().MarkDeprecated("public", "use `--visibility=public` instead") _ = cmd.Flags().MarkDeprecated("private", "use `--visibility=private` instead") return cmd } var defaultFields = []string{"nameWithOwner", "description", "isPrivate", "isFork", "isArchived", "createdAt", "pushedAt"} func listRun(opts *ListOptions) error { httpClient, err := opts.HttpClient() if err != nil { return err } cfg, err := opts.Config() if err != nil { return err } host, _ := cfg.Authentication().DefaultHost() if opts.Detector == nil { cachedClient := api.NewCachedHTTPClient(httpClient, time.Hour*24) opts.Detector = fd.NewDetector(cachedClient, host) } features, err := opts.Detector.RepositoryFeatures() if err != nil { return err } fields := defaultFields if features.VisibilityField { fields = append(defaultFields, "visibility") } filter := FilterOptions{ Visibility: opts.Visibility, Fork: opts.Fork, Source: opts.Source, Language: opts.Language, Topic: opts.Topic, Archived: opts.Archived, NonArchived: opts.NonArchived, Fields: fields, } if opts.Exporter != nil { filter.Fields = opts.Exporter.Fields() } listResult, err := listRepos(httpClient, host, opts.Limit, opts.Owner, filter) if err != nil { return err } if opts.Owner != "" && listResult.Owner == "" && !listResult.FromSearch { return fmt.Errorf("the owner handle %q was not recognized as either a GitHub user or an organization", opts.Owner) } 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, listResult.Repositories) } cs := opts.IO.ColorScheme() tp := tableprinter.New(opts.IO, tableprinter.WithHeader("NAME", "DESCRIPTION", "INFO", "UPDATED")) totalMatchCount := len(listResult.Repositories) for _, repo := range listResult.Repositories { info := repoInfo(repo) infoColor := cs.Muted if repo.IsPrivate { infoColor = cs.Yellow } t := repo.PushedAt if repo.PushedAt == nil { t = &repo.CreatedAt } tp.AddField(repo.NameWithOwner, tableprinter.WithColor(cs.Bold)) tp.AddField(text.RemoveExcessiveWhitespace(repo.Description)) tp.AddField(info, tableprinter.WithColor(infoColor)) tp.AddTimeField(opts.Now(), *t, cs.Muted) tp.EndRow() } if listResult.FromSearch && opts.Limit > 1000 { fmt.Fprintln(opts.IO.ErrOut, "warning: this query uses the Search API which is capped at 1000 results maximum") } if opts.IO.IsStdoutTTY() { hasFilters := filter.Visibility != "" || filter.Fork || filter.Source || filter.Language != "" || len(filter.Topic) > 0 title := listHeader(listResult.Owner, totalMatchCount, listResult.TotalCount, hasFilters) fmt.Fprintf(opts.IO.Out, "\n%s\n\n", title) } if totalMatchCount > 0 { return tp.Render() } return nil } func listHeader(owner string, matchCount, totalMatchCount int, hasFilters bool) string { if totalMatchCount == 0 { if hasFilters { return "No results match your search" } else if owner != "" { return "There are no repositories in @" + owner } return "No results" } var matchStr string if hasFilters { matchStr = " that match your search" } return fmt.Sprintf("Showing %d of %d repositories in @%s%s", matchCount, totalMatchCount, owner, matchStr) } func repoInfo(r api.Repository) string { tags := []string{visibilityLabel(r)} if r.IsFork { tags = append(tags, "fork") } if r.IsArchived { tags = append(tags, "archived") } return strings.Join(tags, ", ") } func visibilityLabel(repo api.Repository) string { if repo.Visibility != "" { return strings.ToLower(repo.Visibility) } else if repo.IsPrivate { return "private" } return "public" }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/list/http_test.go
pkg/cmd/repo/list/http_test.go
package list import ( "encoding/json" "io" "net/http" "os" "testing" "github.com/cli/cli/v2/pkg/httpmock" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func Test_listReposWithLanguage(t *testing.T) { reg := httpmock.Registry{} defer reg.Verify(t) var searchData struct { Query string Variables map[string]interface{} } reg.Register( httpmock.GraphQL(`query RepositoryListSearch\b`), func(req *http.Request) (*http.Response, error) { jsonData, err := io.ReadAll(req.Body) if err != nil { return nil, err } err = json.Unmarshal(jsonData, &searchData) if err != nil { return nil, err } respBody, err := os.Open("./fixtures/repoSearch.json") if err != nil { return nil, err } return &http.Response{ StatusCode: 200, Request: req, Body: respBody, }, nil }, ) client := http.Client{Transport: &reg} res, err := listRepos(&client, "github.com", 10, "", FilterOptions{ Language: "go", }) require.NoError(t, err) assert.Equal(t, 3, res.TotalCount) assert.Equal(t, true, res.FromSearch) assert.Equal(t, "octocat", res.Owner) assert.Equal(t, "octocat/hello-world", res.Repositories[0].NameWithOwner) assert.Equal(t, float64(10), searchData.Variables["perPage"]) assert.Equal(t, `sort:updated-desc fork:true language:go user:@me`, searchData.Variables["query"]) } func Test_searchQuery(t *testing.T) { type args struct { owner string filter FilterOptions } tests := []struct { name string args args want string }{ { name: "blank", want: "sort:updated-desc fork:true user:@me", }, { name: "in org", args: args{ owner: "cli", }, want: "sort:updated-desc fork:true user:cli", }, { name: "only public", args: args{ owner: "", filter: FilterOptions{ Visibility: "public", }, }, want: "sort:updated-desc fork:true is:public user:@me", }, { name: "only private", args: args{ owner: "", filter: FilterOptions{ Visibility: "private", }, }, want: "sort:updated-desc fork:true is:private user:@me", }, { name: "only forks", args: args{ owner: "", filter: FilterOptions{ Fork: true, }, }, want: "sort:updated-desc fork:only user:@me", }, { name: "no forks", args: args{ owner: "", filter: FilterOptions{ Source: true, }, }, want: "sort:updated-desc fork:false user:@me", }, { name: "with language", args: args{ owner: "", filter: FilterOptions{ Language: "ruby", }, }, want: `sort:updated-desc fork:true language:ruby user:@me`, }, { name: "only archived", args: args{ owner: "", filter: FilterOptions{ Archived: true, }, }, want: "sort:updated-desc archived:true fork:true user:@me", }, { name: "only non-archived", args: args{ owner: "", filter: FilterOptions{ NonArchived: true, }, }, want: "sort:updated-desc archived:false fork:true user:@me", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := searchQuery(tt.args.owner, tt.args.filter); got != tt.want { t.Errorf("searchQuery() = %q, want %q", got, tt.want) } }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/list/http.go
pkg/cmd/repo/list/http.go
package list import ( "fmt" "net/http" "strings" "github.com/shurcooL/githubv4" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/pkg/search" ) type RepositoryList struct { Owner string Repositories []api.Repository TotalCount int FromSearch bool } type FilterOptions struct { Visibility string // private, public, internal Fork bool Source bool Language string Topic []string Archived bool NonArchived bool Fields []string } func listRepos(client *http.Client, hostname string, limit int, owner string, filter FilterOptions) (*RepositoryList, error) { if filter.Language != "" || filter.Archived || filter.NonArchived || len(filter.Topic) > 0 || filter.Visibility == "internal" { return searchRepos(client, hostname, limit, owner, filter) } perPage := limit if perPage > 100 { perPage = 100 } variables := map[string]interface{}{ "perPage": githubv4.Int(perPage), } if filter.Visibility != "" { variables["privacy"] = githubv4.RepositoryPrivacy(strings.ToUpper(filter.Visibility)) } if filter.Fork { variables["fork"] = githubv4.Boolean(true) } else if filter.Source { variables["fork"] = githubv4.Boolean(false) } inputs := []string{"$perPage:Int!", "$endCursor:String", "$privacy:RepositoryPrivacy", "$fork:Boolean"} var ownerConnection string if owner == "" { ownerConnection = "repositoryOwner: viewer" } else { ownerConnection = "repositoryOwner(login: $owner)" variables["owner"] = githubv4.String(owner) inputs = append(inputs, "$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, privacy: $privacy, isFork: $fork, ownerAffiliations: OWNER, orderBy: { field: PUSHED_AT, direction: DESC }) { nodes{%s} totalCount pageInfo{hasNextPage,endCursor} } } }`, strings.Join(inputs, ","), ownerConnection, api.RepositoryGraphQL(filter.Fields)) apiClient := api.NewClientFromHTTP(client) listResult := RepositoryList{} pagination: for { var res result err := apiClient.GraphQL(hostname, query, variables, &res) if err != nil { return nil, err } owner := res.RepositoryOwner listResult.TotalCount = owner.Repositories.TotalCount listResult.Owner = owner.Login for _, repo := range owner.Repositories.Nodes { listResult.Repositories = append(listResult.Repositories, repo) if len(listResult.Repositories) >= limit { break pagination } } if !owner.Repositories.PageInfo.HasNextPage { break } variables["endCursor"] = githubv4.String(owner.Repositories.PageInfo.EndCursor) } return &listResult, nil } func searchRepos(client *http.Client, hostname string, limit int, owner string, filter FilterOptions) (*RepositoryList, error) { type result struct { Search struct { RepositoryCount int Nodes []api.Repository PageInfo struct { HasNextPage bool EndCursor string } } } query := fmt.Sprintf(`query RepositoryListSearch($query:String!,$perPage:Int!,$endCursor:String) { search(type: REPOSITORY, query: $query, first: $perPage, after: $endCursor) { repositoryCount nodes{...on Repository{%s}} pageInfo{hasNextPage,endCursor} } }`, api.RepositoryGraphQL(filter.Fields)) perPage := limit if perPage > 100 { perPage = 100 } variables := map[string]interface{}{ "query": githubv4.String(searchQuery(owner, filter)), "perPage": githubv4.Int(perPage), } apiClient := api.NewClientFromHTTP(client) listResult := RepositoryList{FromSearch: true} pagination: for { var result result err := apiClient.GraphQL(hostname, query, variables, &result) if err != nil { return nil, err } listResult.TotalCount = result.Search.RepositoryCount for _, repo := range result.Search.Nodes { if listResult.Owner == "" && repo.NameWithOwner != "" { idx := strings.IndexRune(repo.NameWithOwner, '/') listResult.Owner = repo.NameWithOwner[:idx] } listResult.Repositories = append(listResult.Repositories, repo) if len(listResult.Repositories) >= limit { break pagination } } if !result.Search.PageInfo.HasNextPage { break } variables["endCursor"] = githubv4.String(result.Search.PageInfo.EndCursor) } return &listResult, nil } func searchQuery(owner string, filter FilterOptions) string { if owner == "" { owner = "@me" } fork := "true" if filter.Fork { fork = "only" } else if filter.Source { fork = "false" } var archived *bool if filter.Archived { trueBool := true archived = &trueBool } if filter.NonArchived { falseBool := false archived = &falseBool } q := search.Query{ Keywords: []string{"sort:updated-desc"}, Qualifiers: search.Qualifiers{ Archived: archived, Fork: fork, Is: []string{filter.Visibility}, Language: filter.Language, Topic: filter.Topic, User: []string{owner}, }, } return q.StandardSearchString() }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/archive/archive.go
pkg/cmd/repo/archive/archive.go
package archive 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 ArchiveOptions 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 NewCmdArchive(f *cmdutil.Factory, runF func(*ArchiveOptions) error) *cobra.Command { opts := &ArchiveOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, Config: f.Config, BaseRepo: f.BaseRepo, Prompter: f.Prompter, } cmd := &cobra.Command{ Use: "archive [<repository>]", Short: "Archive a repository", Long: heredoc.Doc(`Archive a GitHub repository. With no argument, archives 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 archiveRun(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 archiveRun(opts *ArchiveOptions) error { cs := opts.IO.ColorScheme() httpClient, err := opts.HttpClient() if err != nil { return err } apiClient := api.NewClientFromHTTP(httpClient) var toArchive ghrepo.Interface if opts.RepoArg == "" { toArchive, 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 } toArchive, err = ghrepo.FromFullName(repoSelector) if err != nil { return err } } fields := []string{"name", "owner", "isArchived", "id"} repo, err := api.FetchRepository(apiClient, toArchive, fields) if err != nil { return err } fullName := ghrepo.FullName(toArchive) if repo.IsArchived { fmt.Fprintf(opts.IO.ErrOut, "%s Repository %s is already archived\n", cs.WarningIcon(), fullName) return nil } if !opts.Confirmed { confirmed, err := opts.Prompter.Confirm(fmt.Sprintf("Archive %s?", fullName), false) if err != nil { return fmt.Errorf("failed to prompt: %w", err) } if !confirmed { return cmdutil.CancelError } } err = archiveRepo(httpClient, repo) if err != nil { return err } if opts.IO.IsStdoutTTY() { fmt.Fprintf(opts.IO.Out, "%s Archived 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/archive/archive_test.go
pkg/cmd/repo/archive/archive_test.go
package archive 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 TestNewCmdArchive(t *testing.T) { tests := []struct { name string input string wantErr bool output ArchiveOptions 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: ArchiveOptions{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 *ArchiveOptions cmd := NewCmdArchive(f, func(opts *ArchiveOptions) 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_ArchiveRun(t *testing.T) { queryResponse := `{ "data": { "repository": { "id": "THE-ID","isArchived": %s} } }` tests := []struct { name string opts ArchiveOptions httpStubs func(*httpmock.Registry) prompterStubs func(pm *prompter.MockPrompter) isTTY bool wantStdout string wantStderr string }{ { name: "unarchived repo tty", wantStdout: "✓ Archived repository OWNER/REPO\n", prompterStubs: func(pm *prompter.MockPrompter) { pm.RegisterConfirm("Archive OWNER/REPO?", func(_ string, _ bool) (bool, error) { return true, nil }) }, isTTY: true, opts: ArchiveOptions{RepoArg: "OWNER/REPO"}, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(fmt.Sprintf(queryResponse, "false"))) reg.Register( httpmock.GraphQL(`mutation ArchiveRepository\b`), httpmock.StringResponse(`{}`)) }, }, { name: "infer base repo", wantStdout: "✓ Archived repository OWNER/REPO\n", opts: ArchiveOptions{}, prompterStubs: func(pm *prompter.MockPrompter) { pm.RegisterConfirm("Archive OWNER/REPO?", func(_ string, _ bool) (bool, error) { return true, nil }) }, isTTY: true, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(fmt.Sprintf(queryResponse, "false"))) reg.Register( httpmock.GraphQL(`mutation ArchiveRepository\b`), httpmock.StringResponse(`{}`)) }, }, { name: "archived repo tty", wantStderr: "! Repository OWNER/REPO is already archived\n", opts: ArchiveOptions{RepoArg: "OWNER/REPO"}, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(fmt.Sprintf(queryResponse, "true"))) }, }, } 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.NewMockPrompter(t) 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 := archiveRun(&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/archive/http.go
pkg/cmd/repo/archive/http.go
package archive import ( "net/http" "github.com/cli/cli/v2/api" "github.com/shurcooL/githubv4" ) func archiveRepo(client *http.Client, repo *api.Repository) error { var mutation struct { ArchiveRepository struct { Repository struct { ID string } } `graphql:"archiveRepository(input: $input)"` } variables := map[string]interface{}{ "input": githubv4.ArchiveRepositoryInput{ RepositoryID: repo.ID, }, } gql := api.NewClientFromHTTP(client) err := gql.Mutate(repo.RepoHost(), "ArchiveRepository", &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/rename/rename_test.go
pkg/cmd/repo/rename/rename_test.go
package rename import ( "bytes" "net/http" "testing" "github.com/cli/cli/v2/context" "github.com/cli/cli/v2/git" "github.com/cli/cli/v2/internal/config" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/internal/run" "github.com/cli/cli/v2/pkg/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 TestNewCmdRename(t *testing.T) { testCases := []struct { name string input string output RenameOptions errMsg string tty bool wantErr bool }{ { name: "no arguments no tty", input: "", errMsg: "new name argument required when not running interactively", wantErr: true, }, { name: "one argument no tty confirmed", input: "REPO --yes", output: RenameOptions{ newRepoSelector: "REPO", }, }, { name: "one argument no tty", input: "REPO", errMsg: "--yes required when passing a single argument", wantErr: true, }, { name: "one argument tty confirmed", input: "REPO --yes", tty: true, output: RenameOptions{ newRepoSelector: "REPO", }, }, { name: "one argument tty", input: "REPO", tty: true, output: RenameOptions{ newRepoSelector: "REPO", DoConfirm: true, }, }, { name: "full flag argument", input: "--repo OWNER/REPO NEW_REPO", output: RenameOptions{ newRepoSelector: "NEW_REPO", }, }, } for _, tt := range testCases { 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 *RenameOptions cmd := NewCmdRename(f, func(opts *RenameOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err = cmd.ExecuteC() if tt.wantErr { assert.EqualError(t, err, tt.errMsg) return } assert.NoError(t, err) assert.Equal(t, tt.output.newRepoSelector, gotOpts.newRepoSelector) }) } } func TestRenameRun(t *testing.T) { testCases := []struct { name string opts RenameOptions httpStubs func(*httpmock.Registry) execStubs func(*run.CommandStubber) promptStubs func(*prompter.MockPrompter) wantOut string tty bool wantErr bool errMsg string }{ { name: "none argument", wantOut: "✓ Renamed repository OWNER/NEW_REPO\n✓ Updated the \"origin\" remote\n", promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterInput("Rename OWNER/REPO to:", func(_, _ string) (string, error) { return "NEW_REPO", nil }) }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("PATCH", "repos/OWNER/REPO"), httpmock.StatusStringResponse(200, `{"name":"NEW_REPO","owner":{"login":"OWNER"}}`)) }, execStubs: func(cs *run.CommandStubber) { cs.Register(`git remote set-url origin https://github.com/OWNER/NEW_REPO.git`, 0, "") }, tty: true, }, { name: "repo override", opts: RenameOptions{ HasRepoOverride: true, }, wantOut: "✓ Renamed repository OWNER/NEW_REPO\n", promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterInput("Rename OWNER/REPO to:", func(_, _ string) (string, error) { return "NEW_REPO", nil }) }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("PATCH", "repos/OWNER/REPO"), httpmock.StatusStringResponse(200, `{"name":"NEW_REPO","owner":{"login":"OWNER"}}`)) }, tty: true, }, { name: "owner repo change name argument tty", opts: RenameOptions{ newRepoSelector: "NEW_REPO", }, wantOut: "✓ Renamed repository OWNER/NEW_REPO\n✓ Updated the \"origin\" remote\n", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("PATCH", "repos/OWNER/REPO"), httpmock.StatusStringResponse(200, `{"name":"NEW_REPO","owner":{"login":"OWNER"}}`)) }, execStubs: func(cs *run.CommandStubber) { cs.Register(`git remote set-url origin https://github.com/OWNER/NEW_REPO.git`, 0, "") }, tty: true, }, { name: "owner repo change name argument no tty", opts: RenameOptions{ newRepoSelector: "NEW_REPO", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("PATCH", "repos/OWNER/REPO"), httpmock.StatusStringResponse(200, `{"name":"NEW_REPO","owner":{"login":"OWNER"}}`)) }, execStubs: func(cs *run.CommandStubber) { cs.Register(`git remote set-url origin https://github.com/OWNER/NEW_REPO.git`, 0, "") }, }, { name: "confirmation with yes", tty: true, opts: RenameOptions{ newRepoSelector: "NEW_REPO", DoConfirm: true, }, wantOut: "✓ Renamed repository OWNER/NEW_REPO\n✓ Updated the \"origin\" remote\n", promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterConfirm("Rename OWNER/REPO to NEW_REPO?", func(_ string, _ bool) (bool, error) { return true, nil }) }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("PATCH", "repos/OWNER/REPO"), httpmock.StatusStringResponse(200, `{"name":"NEW_REPO","owner":{"login":"OWNER"}}`)) }, execStubs: func(cs *run.CommandStubber) { cs.Register(`git remote set-url origin https://github.com/OWNER/NEW_REPO.git`, 0, "") }, }, { name: "confirmation with no", tty: true, opts: RenameOptions{ newRepoSelector: "NEW_REPO", DoConfirm: true, }, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterConfirm("Rename OWNER/REPO to NEW_REPO?", func(_ string, _ bool) (bool, error) { return false, nil }) }, wantOut: "", }, { name: "error on name with slash", tty: true, opts: RenameOptions{ newRepoSelector: "org/new-name", }, wantErr: true, errMsg: "New repository name cannot contain '/' character - to transfer a repository to a new owner, see <https://docs.github.com/en/repositories/creating-and-managing-repositories/transferring-a-repository>.", }, } for _, tt := range testCases { pm := prompter.NewMockPrompter(t) tt.opts.Prompter = pm if tt.promptStubs != nil { tt.promptStubs(pm) } repo, _ := ghrepo.FromFullName("OWNER/REPO") tt.opts.BaseRepo = func() (ghrepo.Interface, error) { return repo, nil } tt.opts.Config = func() (gh.Config, error) { return config.NewBlankConfig(), nil } tt.opts.Remotes = func() (context.Remotes, error) { return []*context.Remote{ { Remote: &git.Remote{Name: "origin"}, Repo: repo, }, }, nil } cs, restoreRun := run.Stub() defer restoreRun(t) if tt.execStubs != nil { tt.execStubs(cs) } 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 tt.opts.GitClient = &git.Client{GitPath: "some/path/git"} t.Run(tt.name, func(t *testing.T) { defer reg.Verify(t) err := renameRun(&tt.opts) if tt.wantErr { assert.EqualError(t, err, tt.errMsg) return } assert.NoError(t, err) assert.Equal(t, tt.wantOut, stdout.String()) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/rename/rename.go
pkg/cmd/repo/rename/rename.go
package rename import ( "context" "fmt" "net/http" "strings" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/api" ghContext "github.com/cli/cli/v2/context" "github.com/cli/cli/v2/git" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type iprompter interface { Input(string, string) (string, error) Confirm(string, bool) (bool, error) } type RenameOptions struct { HttpClient func() (*http.Client, error) GitClient *git.Client IO *iostreams.IOStreams Prompter iprompter Config func() (gh.Config, error) BaseRepo func() (ghrepo.Interface, error) Remotes func() (ghContext.Remotes, error) DoConfirm bool HasRepoOverride bool newRepoSelector string } func NewCmdRename(f *cmdutil.Factory, runf func(*RenameOptions) error) *cobra.Command { opts := &RenameOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, GitClient: f.GitClient, Remotes: f.Remotes, Config: f.Config, Prompter: f.Prompter, } var confirm bool cmd := &cobra.Command{ Use: "rename [<new-name>]", Short: "Rename a repository", Long: heredoc.Docf(` Rename a GitHub repository. %[1]s<new-name>%[1]s is the desired repository name without the owner. By default, the current repository is renamed. Otherwise, the repository specified with %[1]s--repo%[1]s is renamed. To transfer repository ownership to another user account or organization, you must follow additional steps on %[1]sgithub.com%[1]s. For more information on transferring repository ownership, see: <https://docs.github.com/en/repositories/creating-and-managing-repositories/transferring-a-repository> `, "`"), Example: heredoc.Doc(` # Rename the current repository (foo/bar -> foo/baz) $ gh repo rename baz # Rename the specified repository (qux/quux -> qux/baz) $ gh repo rename -R qux/quux baz `), Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.BaseRepo = f.BaseRepo opts.HasRepoOverride = cmd.Flags().Changed("repo") if len(args) > 0 { opts.newRepoSelector = args[0] } else if !opts.IO.CanPrompt() { return cmdutil.FlagErrorf("new name argument required when not running interactively") } if len(args) == 1 && !confirm && !opts.HasRepoOverride { if !opts.IO.CanPrompt() { return cmdutil.FlagErrorf("--yes required when passing a single argument") } opts.DoConfirm = true } if runf != nil { return runf(opts) } return renameRun(opts) }, } cmdutil.EnableRepoOverride(cmd, f) cmd.Flags().BoolVar(&confirm, "confirm", false, "Skip confirmation prompt") _ = cmd.Flags().MarkDeprecated("confirm", "use `--yes` instead") cmd.Flags().BoolVarP(&confirm, "yes", "y", false, "Skip the confirmation prompt") return cmd } func renameRun(opts *RenameOptions) error { httpClient, err := opts.HttpClient() if err != nil { return err } newRepoName := opts.newRepoSelector currRepo, err := opts.BaseRepo() if err != nil { return err } if newRepoName == "" { if newRepoName, err = opts.Prompter.Input(fmt.Sprintf( "Rename %s to:", ghrepo.FullName(currRepo)), ""); err != nil { return err } } if strings.Contains(newRepoName, "/") { return fmt.Errorf("New repository name cannot contain '/' character - to transfer a repository to a new owner, see <https://docs.github.com/en/repositories/creating-and-managing-repositories/transferring-a-repository>.") } if opts.DoConfirm { var confirmed bool if confirmed, err = opts.Prompter.Confirm(fmt.Sprintf( "Rename %s to %s?", ghrepo.FullName(currRepo), newRepoName), false); err != nil { return err } if !confirmed { return nil } } apiClient := api.NewClientFromHTTP(httpClient) newRepo, err := api.RenameRepo(apiClient, currRepo, newRepoName) if err != nil { return err } cs := opts.IO.ColorScheme() if opts.IO.IsStdoutTTY() { fmt.Fprintf(opts.IO.Out, "%s Renamed repository %s\n", cs.SuccessIcon(), ghrepo.FullName(newRepo)) } if opts.HasRepoOverride { return nil } remote, err := updateRemote(currRepo, newRepo, opts) if err != nil { if remote != nil { fmt.Fprintf(opts.IO.ErrOut, "%s Warning: unable to update remote %q: %v\n", cs.WarningIcon(), remote.Name, err) } else { fmt.Fprintf(opts.IO.ErrOut, "%s Warning: unable to update remote: %v\n", cs.WarningIcon(), err) } } else if opts.IO.IsStdoutTTY() { fmt.Fprintf(opts.IO.Out, "%s Updated the %q remote\n", cs.SuccessIcon(), remote.Name) } return nil } func updateRemote(repo ghrepo.Interface, renamed ghrepo.Interface, opts *RenameOptions) (*ghContext.Remote, error) { cfg, err := opts.Config() if err != nil { return nil, err } protocol := cfg.GitProtocol(repo.RepoHost()).Value remotes, err := opts.Remotes() if err != nil { return nil, err } remote, err := remotes.FindByRepo(repo.RepoOwner(), repo.RepoName()) if err != nil { return nil, err } remoteURL := ghrepo.FormatRemoteURL(renamed, protocol) err = opts.GitClient.UpdateRemoteURL(context.Background(), remote.Name, remoteURL) return remote, err }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/garden/http.go
pkg/cmd/repo/garden/http.go
package garden import ( "encoding/json" "errors" "fmt" "io" "net/http" "strings" "time" "github.com/cli/cli/v2/internal/ghinstance" "github.com/cli/cli/v2/internal/ghrepo" ) func getCommits(client *http.Client, repo ghrepo.Interface, maxCommits int) ([]*Commit, error) { type Item struct { Author struct { Login string } Sha string } type Result []Item commits := []*Commit{} pathF := func(page int) string { return fmt.Sprintf("repos/%s/%s/commits?per_page=100&page=%d", repo.RepoOwner(), repo.RepoName(), page) } page := 1 paginating := true for paginating { if len(commits) >= maxCommits { break } result := Result{} links, err := getResponse(client, repo.RepoHost(), pathF(page), &result) if err != nil { return nil, err } for _, r := range result { colorFunc := shaToColorFunc(r.Sha) handle := r.Author.Login if handle == "" { handle = "a mysterious stranger" } commits = append(commits, &Commit{ Handle: handle, Sha: r.Sha, Char: colorFunc(string(handle[0])), }) } if len(links) == 0 || !strings.Contains(links[0], "last") { paginating = false } page++ time.Sleep(500) } // reverse to get older commits first for i, j := 0, len(commits)-1; i < j; i, j = i+1, j-1 { commits[i], commits[j] = commits[j], commits[i] } return commits, nil } // getResponse performs the API call and returns the response's link header values. // If the "Link" header is missing, the returned slice will be nil. func getResponse(client *http.Client, host, path string, data interface{}) ([]string, error) { url := ghinstance.RESTPrefix(host) + path req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/json; charset=utf-8") resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() success := resp.StatusCode >= 200 && resp.StatusCode < 300 if !success { return nil, errors.New("api call failed") } links := resp.Header["Link"] if resp.StatusCode == http.StatusNoContent { return links, nil } b, err := io.ReadAll(resp.Body) if err != nil { return nil, err } err = json.Unmarshal(b, &data) if err != nil { return nil, err } return links, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/garden/garden.go
pkg/cmd/repo/garden/garden.go
package garden import ( "bytes" "errors" "fmt" "math/rand" "net/http" "os" "os/exec" "runtime" "strconv" "strings" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/utils" "github.com/spf13/cobra" "golang.org/x/term" ) type Geometry struct { Width int Height int Density float64 Repository ghrepo.Interface } type Player struct { X int Y int Char string Geo *Geometry ShoeMoistureContent int } type Commit struct { Email string Handle string Sha string Char string } type Cell struct { Char string StatusLine string } const ( DirUp Direction = iota DirDown DirLeft DirRight Quit ) type Direction = int func (p *Player) move(direction Direction) bool { switch direction { case DirUp: if p.Y == 0 { return false } p.Y-- case DirDown: if p.Y == p.Geo.Height-1 { return false } p.Y++ case DirLeft: if p.X == 0 { return false } p.X-- case DirRight: if p.X == p.Geo.Width-1 { return false } p.X++ } return true } type GardenOptions struct { HttpClient func() (*http.Client, error) IO *iostreams.IOStreams BaseRepo func() (ghrepo.Interface, error) Config func() (gh.Config, error) RepoArg string } func NewCmdGarden(f *cmdutil.Factory, runF func(*GardenOptions) error) *cobra.Command { opts := GardenOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, BaseRepo: f.BaseRepo, Config: f.Config, } cmd := &cobra.Command{ Use: "garden [<repository>]", Short: "Explore a git repository as a garden", Long: "Use arrow keys, WASD or vi keys to move. q to quit.", Hidden: true, RunE: func(c *cobra.Command, args []string) error { if len(args) > 0 { opts.RepoArg = args[0] } if runF != nil { return runF(&opts) } return gardenRun(&opts) }, } return cmd } func gardenRun(opts *GardenOptions) error { cs := opts.IO.ColorScheme() out := opts.IO.Out if runtime.GOOS == "windows" { return errors.New("sorry :( this command only works on linux and macos") } if !opts.IO.IsStdoutTTY() { return errors.New("must be connected to a terminal") } 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 { var err error 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) } } seed := computeSeed(ghrepo.FullName(toView)) r := rand.New(rand.NewSource(seed)) termWidth, termHeight, err := utils.TerminalSize(out) if err != nil { return err } termWidth -= 10 termHeight -= 10 geo := &Geometry{ Width: termWidth, Height: termHeight, Repository: toView, // TODO based on number of commits/cells instead of just hardcoding Density: 0.3, } maxCommits := (geo.Width * geo.Height) / 2 opts.IO.StartProgressIndicator() fmt.Fprintln(out, "gathering commits; this could take a minute...") commits, err := getCommits(httpClient, toView, maxCommits) opts.IO.StopProgressIndicator() if err != nil { return err } player := &Player{0, 0, cs.Bold("@"), geo, 0} garden := plantGarden(r, commits, geo) if len(garden) < geo.Height { geo.Height = len(garden) } if geo.Height > 0 && len(garden[0]) < geo.Width { geo.Width = len(garden[0]) } else if len(garden) == 0 { geo.Width = 0 } clear(opts.IO) drawGarden(opts.IO, garden, player) // TODO: use opts.IO instead of os.Stdout oldTermState, err := term.MakeRaw(int(os.Stdout.Fd())) if err != nil { return fmt.Errorf("term.MakeRaw: %w", err) } dirc := make(chan Direction) go func() { b := make([]byte, 3) for { _, _ = opts.IO.In.Read(b) switch { case isLeft(b): dirc <- DirLeft case isRight(b): dirc <- DirRight case isUp(b): dirc <- DirUp case isDown(b): dirc <- DirDown case isQuit(b): dirc <- Quit } } }() for { oldX := player.X oldY := player.Y d := <-dirc if d == Quit { break } else if !player.move(d) { continue } underPlayer := garden[player.Y][player.X] previousCell := garden[oldY][oldX] // print whatever was just under player fmt.Fprint(out, "\033[;H") // move to top left for x := 0; x < oldX && x < player.Geo.Width; x++ { fmt.Fprint(out, "\033[C") } for y := 0; y < oldY && y < player.Geo.Height; y++ { fmt.Fprint(out, "\033[B") } fmt.Fprint(out, previousCell.Char) // print player character fmt.Fprint(out, "\033[;H") // move to top left for x := 0; x < player.X && x < player.Geo.Width; x++ { fmt.Fprint(out, "\033[C") } for y := 0; y < player.Y && y < player.Geo.Height; y++ { fmt.Fprint(out, "\033[B") } fmt.Fprint(out, player.Char) // handle stream wettening if strings.Contains(underPlayer.StatusLine, "stream") { player.ShoeMoistureContent = 5 } else { if player.ShoeMoistureContent > 0 { player.ShoeMoistureContent-- } } // status line stuff sl := statusLine(garden, player, opts.IO) fmt.Fprint(out, "\033[;H") // move to top left for y := 0; y < player.Geo.Height-1; y++ { fmt.Fprint(out, "\033[B") } fmt.Fprintln(out) fmt.Fprintln(out) fmt.Fprint(out, cs.Bold(sl)) } clear(opts.IO) fmt.Fprint(out, "\033[?25h") // TODO: use opts.IO instead of os.Stdout _ = term.Restore(int(os.Stdout.Fd()), oldTermState) fmt.Fprintln(out, cs.Bold("You turn and walk away from the wildflower garden...")) return nil } func isLeft(b []byte) bool { left := []byte{27, 91, 68} r := rune(b[0]) return bytes.EqualFold(b, left) || r == 'a' || r == 'h' } func isRight(b []byte) bool { right := []byte{27, 91, 67} r := rune(b[0]) return bytes.EqualFold(b, right) || r == 'd' || r == 'l' } func isDown(b []byte) bool { down := []byte{27, 91, 66} r := rune(b[0]) return bytes.EqualFold(b, down) || r == 's' || r == 'j' } func isUp(b []byte) bool { up := []byte{27, 91, 65} r := rune(b[0]) return bytes.EqualFold(b, up) || r == 'w' || r == 'k' } var ctrlC = []byte{0x3, 0x5b, 0x43} func isQuit(b []byte) bool { return rune(b[0]) == 'q' || bytes.Equal(b, ctrlC) } func plantGarden(r *rand.Rand, commits []*Commit, geo *Geometry) [][]*Cell { cellIx := 0 grassCell := &Cell{RGB(0, 200, 0, ","), "You're standing on a patch of grass in a field of wildflowers."} garden := [][]*Cell{} streamIx := r.Intn(geo.Width - 1) if streamIx == geo.Width/2 { streamIx-- } tint := 0 for y := 0; y < geo.Height; y++ { if cellIx == len(commits)-1 { break } garden = append(garden, []*Cell{}) for x := 0; x < geo.Width; x++ { if (y > 0 && (x == 0 || x == geo.Width-1)) || y == geo.Height-1 { garden[y] = append(garden[y], &Cell{ Char: RGB(0, 150, 0, "^"), StatusLine: "You're standing under a tall, leafy tree.", }) continue } if x == streamIx { garden[y] = append(garden[y], &Cell{ Char: RGB(tint, tint, 255, "#"), StatusLine: "You're standing in a shallow stream. It's refreshing.", }) tint += 15 streamIx-- if r.Float64() < 0.5 { streamIx++ } if streamIx < 0 { streamIx = 0 } if streamIx > geo.Width { streamIx = geo.Width } continue } if y == 0 && (x < geo.Width/2 || x > geo.Width/2) { garden[y] = append(garden[y], &Cell{ Char: RGB(0, 200, 0, ","), StatusLine: "You're standing by a wildflower garden. There is a light breeze.", }) continue } else if y == 0 && x == geo.Width/2 { garden[y] = append(garden[y], &Cell{ Char: RGB(139, 69, 19, "+"), StatusLine: fmt.Sprintf("You're standing in front of a weather-beaten sign that says %s.", ghrepo.FullName(geo.Repository)), }) continue } if cellIx == len(commits)-1 { garden[y] = append(garden[y], grassCell) continue } chance := r.Float64() if chance <= geo.Density { commit := commits[cellIx] garden[y] = append(garden[y], &Cell{ Char: commits[cellIx].Char, StatusLine: fmt.Sprintf("You're standing at a flower called %s planted by %s.", commit.Sha[0:6], commit.Handle), }) cellIx++ } else { garden[y] = append(garden[y], grassCell) } } } return garden } func drawGarden(io *iostreams.IOStreams, garden [][]*Cell, player *Player) { out := io.Out cs := io.ColorScheme() fmt.Fprint(out, "\033[?25l") // hide cursor. it needs to be restored at command exit. sl := "" for y, gardenRow := range garden { for x, gardenCell := range gardenRow { char := "" underPlayer := (player.X == x && player.Y == y) if underPlayer { sl = gardenCell.StatusLine char = cs.Bold(player.Char) if strings.Contains(gardenCell.StatusLine, "stream") { player.ShoeMoistureContent = 5 } } else { char = gardenCell.Char } fmt.Fprint(out, char) } fmt.Fprintln(out) } fmt.Println() fmt.Fprintln(out, cs.Bold(sl)) } func statusLine(garden [][]*Cell, player *Player, io *iostreams.IOStreams) string { width := io.TerminalWidth() statusLines := []string{garden[player.Y][player.X].StatusLine} if player.ShoeMoistureContent > 1 { statusLines = append(statusLines, "Your shoes squish with water from the stream.") } else if player.ShoeMoistureContent == 1 { statusLines = append(statusLines, "Your shoes seem to have dried out.") } else { statusLines = append(statusLines, "") } for i, line := range statusLines { if len(line) < width { paddingSize := width - len(line) statusLines[i] = line + strings.Repeat(" ", paddingSize) } } return strings.Join(statusLines, "\n") } func shaToColorFunc(sha string) func(string) string { return func(c string) string { red, err := strconv.ParseInt(sha[0:2], 16, 64) if err != nil { panic(err) } green, err := strconv.ParseInt(sha[2:4], 16, 64) if err != nil { panic(err) } blue, err := strconv.ParseInt(sha[4:6], 16, 64) if err != nil { panic(err) } return fmt.Sprintf("\033[38;2;%d;%d;%dm%s\033[0m", red, green, blue, c) } } func computeSeed(seed string) int64 { lol := "" for _, r := range seed { lol += fmt.Sprintf("%d", int(r)) } result, err := strconv.ParseInt(lol[0:10], 10, 64) if err != nil { panic(err) } return result } func clear(io *iostreams.IOStreams) { cmd := exec.Command("clear") cmd.Stdout = io.Out _ = cmd.Run() } func RGB(r, g, b int, x string) string { return fmt.Sprintf("\033[38;2;%d;%d;%dm%s\033[0m", r, g, b, x) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/edit/edit.go
pkg/cmd/repo/edit/edit.go
package edit import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "strings" "time" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/api" fd "github.com/cli/cli/v2/internal/featuredetection" "github.com/cli/cli/v2/internal/ghinstance" "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/set" "github.com/spf13/cobra" "golang.org/x/sync/errgroup" ) type iprompter interface { MultiSelect(prompt string, defaults []string, options []string) ([]int, error) Input(string, string) (string, error) Confirm(string, bool) (bool, error) Select(string, string, []string) (int, error) } const ( allowMergeCommits = "Allow Merge Commits" allowSquashMerge = "Allow Squash Merging" allowRebaseMerge = "Allow Rebase Merging" optionAllowForking = "Allow Forking" optionDefaultBranchName = "Default Branch Name" optionDescription = "Description" optionHomePageURL = "Home Page URL" optionIssues = "Issues" optionMergeOptions = "Merge Options" optionProjects = "Projects" optionDiscussions = "Discussions" optionTemplateRepo = "Template Repository" optionTopics = "Topics" optionVisibility = "Visibility" optionWikis = "Wikis" ) type EditOptions struct { HTTPClient *http.Client Repository ghrepo.Interface IO *iostreams.IOStreams Edits EditRepositoryInput AddTopics []string RemoveTopics []string AcceptVisibilityChangeConsequences bool InteractiveMode bool Detector fd.Detector Prompter iprompter // Cache of current repo topics to avoid retrieving them // in multiple flows. topicsCache []string } type EditRepositoryInput struct { enableAdvancedSecurity *bool enableSecretScanning *bool enableSecretScanningPushProtection *bool AllowForking *bool `json:"allow_forking,omitempty"` AllowUpdateBranch *bool `json:"allow_update_branch,omitempty"` DefaultBranch *string `json:"default_branch,omitempty"` DeleteBranchOnMerge *bool `json:"delete_branch_on_merge,omitempty"` Description *string `json:"description,omitempty"` EnableAutoMerge *bool `json:"allow_auto_merge,omitempty"` EnableIssues *bool `json:"has_issues,omitempty"` EnableMergeCommit *bool `json:"allow_merge_commit,omitempty"` EnableProjects *bool `json:"has_projects,omitempty"` EnableDiscussions *bool `json:"has_discussions,omitempty"` EnableRebaseMerge *bool `json:"allow_rebase_merge,omitempty"` EnableSquashMerge *bool `json:"allow_squash_merge,omitempty"` EnableWiki *bool `json:"has_wiki,omitempty"` Homepage *string `json:"homepage,omitempty"` IsTemplate *bool `json:"is_template,omitempty"` SecurityAndAnalysis *SecurityAndAnalysisInput `json:"security_and_analysis,omitempty"` Visibility *string `json:"visibility,omitempty"` } func NewCmdEdit(f *cmdutil.Factory, runF func(options *EditOptions) error) *cobra.Command { opts := &EditOptions{ IO: f.IOStreams, Prompter: f.Prompter, } cmd := &cobra.Command{ Use: "edit [<repository>]", Short: "Edit repository settings", Annotations: map[string]string{ "help:arguments": heredoc.Doc(` A repository can be supplied as an argument in any of the following formats: - "OWNER/REPO" - by URL, e.g. "https://github.com/OWNER/REPO" `), }, Long: heredoc.Docf(` Edit repository settings. To toggle a setting off, use the %[1]s--<flag>=false%[1]s syntax. Changing repository visibility can have unexpected consequences including but not limited to: - Losing stars and watchers, affecting repository ranking - Detaching public forks from the network - Disabling push rulesets - Allowing access to GitHub Actions history and logs When the %[1]s--visibility%[1]s flag is used, %[1]s--accept-visibility-change-consequences%[1]s flag is required. For information on all the potential consequences, see <https://gh.io/setting-repository-visibility>. `, "`"), Args: cobra.MaximumNArgs(1), Example: heredoc.Doc(` # Enable issues and wiki $ gh repo edit --enable-issues --enable-wiki # Disable projects $ gh repo edit --enable-projects=false `), RunE: func(cmd *cobra.Command, args []string) error { if len(args) > 0 { var err error opts.Repository, err = ghrepo.FromFullName(args[0]) if err != nil { return err } } else { var err error opts.Repository, err = f.BaseRepo() if err != nil { return err } } if httpClient, err := f.HttpClient(); err == nil { opts.HTTPClient = httpClient } else { return err } if cmd.Flags().NFlag() == 0 { opts.InteractiveMode = true } if opts.InteractiveMode && !opts.IO.CanPrompt() { return cmdutil.FlagErrorf("specify properties to edit when not running interactively") } if opts.Edits.Visibility != nil && !opts.AcceptVisibilityChangeConsequences { return cmdutil.FlagErrorf("use of --visibility flag requires --accept-visibility-change-consequences flag") } if hasSecurityEdits(opts.Edits) { opts.Edits.SecurityAndAnalysis = transformSecurityAndAnalysisOpts(opts) } if runF != nil { return runF(opts) } return editRun(cmd.Context(), opts) }, } cmdutil.NilStringFlag(cmd, &opts.Edits.Description, "description", "d", "Description of the repository") cmdutil.NilStringFlag(cmd, &opts.Edits.Homepage, "homepage", "h", "Repository home page `URL`") cmdutil.NilStringFlag(cmd, &opts.Edits.DefaultBranch, "default-branch", "", "Set the default branch `name` for the repository") cmdutil.NilStringFlag(cmd, &opts.Edits.Visibility, "visibility", "", "Change the visibility of the repository to {public,private,internal}") cmdutil.NilBoolFlag(cmd, &opts.Edits.IsTemplate, "template", "", "Make the repository available as a template repository") cmdutil.NilBoolFlag(cmd, &opts.Edits.EnableIssues, "enable-issues", "", "Enable issues in the repository") cmdutil.NilBoolFlag(cmd, &opts.Edits.EnableProjects, "enable-projects", "", "Enable projects in the repository") cmdutil.NilBoolFlag(cmd, &opts.Edits.EnableWiki, "enable-wiki", "", "Enable wiki in the repository") cmdutil.NilBoolFlag(cmd, &opts.Edits.EnableDiscussions, "enable-discussions", "", "Enable discussions in the repository") cmdutil.NilBoolFlag(cmd, &opts.Edits.EnableMergeCommit, "enable-merge-commit", "", "Enable merging pull requests via merge commit") cmdutil.NilBoolFlag(cmd, &opts.Edits.EnableSquashMerge, "enable-squash-merge", "", "Enable merging pull requests via squashed commit") cmdutil.NilBoolFlag(cmd, &opts.Edits.EnableRebaseMerge, "enable-rebase-merge", "", "Enable merging pull requests via rebase") cmdutil.NilBoolFlag(cmd, &opts.Edits.EnableAutoMerge, "enable-auto-merge", "", "Enable auto-merge functionality") cmdutil.NilBoolFlag(cmd, &opts.Edits.enableAdvancedSecurity, "enable-advanced-security", "", "Enable advanced security in the repository") cmdutil.NilBoolFlag(cmd, &opts.Edits.enableSecretScanning, "enable-secret-scanning", "", "Enable secret scanning in the repository") cmdutil.NilBoolFlag(cmd, &opts.Edits.enableSecretScanningPushProtection, "enable-secret-scanning-push-protection", "", "Enable secret scanning push protection in the repository. Secret scanning must be enabled first") cmdutil.NilBoolFlag(cmd, &opts.Edits.DeleteBranchOnMerge, "delete-branch-on-merge", "", "Delete head branch when pull requests are merged") cmdutil.NilBoolFlag(cmd, &opts.Edits.AllowForking, "allow-forking", "", "Allow forking of an organization repository") cmdutil.NilBoolFlag(cmd, &opts.Edits.AllowUpdateBranch, "allow-update-branch", "", "Allow a pull request head branch that is behind its base branch to be updated") cmd.Flags().StringSliceVar(&opts.AddTopics, "add-topic", nil, "Add repository topic") cmd.Flags().StringSliceVar(&opts.RemoveTopics, "remove-topic", nil, "Remove repository topic") cmd.Flags().BoolVar(&opts.AcceptVisibilityChangeConsequences, "accept-visibility-change-consequences", false, "Accept the consequences of changing the repository visibility") return cmd } func editRun(ctx context.Context, opts *EditOptions) error { repo := opts.Repository if opts.InteractiveMode { detector := opts.Detector if detector == nil { cachedClient := api.NewCachedHTTPClient(opts.HTTPClient, time.Hour*24) detector = fd.NewDetector(cachedClient, repo.RepoHost()) } repoFeatures, err := detector.RepositoryFeatures() if err != nil { return err } apiClient := api.NewClientFromHTTP(opts.HTTPClient) fieldsToRetrieve := []string{ "defaultBranchRef", "deleteBranchOnMerge", "description", "hasIssuesEnabled", "hasProjectsEnabled", "hasWikiEnabled", // TODO: GitHub Enterprise Server does not support has_discussions yet // "hasDiscussionsEnabled", "homepageUrl", "isInOrganization", "isTemplate", "mergeCommitAllowed", "rebaseMergeAllowed", "repositoryTopics", "stargazerCount", "squashMergeAllowed", "watchers", } if repoFeatures.VisibilityField { fieldsToRetrieve = append(fieldsToRetrieve, "visibility") } if repoFeatures.AutoMerge { fieldsToRetrieve = append(fieldsToRetrieve, "autoMergeAllowed") } opts.IO.StartProgressIndicator() fetchedRepo, err := api.FetchRepository(apiClient, opts.Repository, fieldsToRetrieve) opts.IO.StopProgressIndicator() if err != nil { return err } err = interactiveRepoEdit(opts, fetchedRepo) if err != nil { return err } } if opts.Edits.SecurityAndAnalysis != nil { apiClient := api.NewClientFromHTTP(opts.HTTPClient) repo, err := api.FetchRepository(apiClient, opts.Repository, []string{"viewerCanAdminister"}) if err != nil { return err } if !repo.ViewerCanAdminister { return fmt.Errorf("you do not have sufficient permissions to edit repository security and analysis features") } } apiPath := fmt.Sprintf("repos/%s/%s", repo.RepoOwner(), repo.RepoName()) body := &bytes.Buffer{} enc := json.NewEncoder(body) if err := enc.Encode(opts.Edits); err != nil { return err } g := errgroup.Group{} if body.Len() > 3 { g.Go(func() error { apiClient := api.NewClientFromHTTP(opts.HTTPClient) _, err := api.CreateRepoTransformToV4(apiClient, repo.RepoHost(), "PATCH", apiPath, body) return err }) } if len(opts.AddTopics) > 0 || len(opts.RemoveTopics) > 0 { g.Go(func() error { // opts.topicsCache gets populated in interactive mode if !opts.InteractiveMode { var err error opts.topicsCache, err = getTopics(ctx, opts.HTTPClient, repo) if err != nil { return err } } oldTopics := set.NewStringSet() oldTopics.AddValues(opts.topicsCache) newTopics := set.NewStringSet() newTopics.AddValues(opts.topicsCache) newTopics.AddValues(opts.AddTopics) newTopics.RemoveValues(opts.RemoveTopics) if oldTopics.Equal(newTopics) { return nil } return setTopics(ctx, opts.HTTPClient, repo, newTopics.ToSlice()) }) } err := g.Wait() if err != nil { return err } if opts.IO.IsStdoutTTY() { cs := opts.IO.ColorScheme() fmt.Fprintf(opts.IO.Out, "%s Edited repository %s\n", cs.SuccessIcon(), ghrepo.FullName(repo)) } return nil } func interactiveChoice(p iprompter, r *api.Repository) ([]string, error) { options := []string{ optionDefaultBranchName, optionDescription, optionHomePageURL, optionIssues, optionMergeOptions, optionProjects, // TODO: GitHub Enterprise Server does not support has_discussions yet // optionDiscussions, optionTemplateRepo, optionTopics, optionVisibility, optionWikis, } if r.IsInOrganization { options = append(options, optionAllowForking) } var answers []string selected, err := p.MultiSelect("What do you want to edit?", nil, options) if err != nil { return nil, err } for _, i := range selected { answers = append(answers, options[i]) } return answers, err } func interactiveRepoEdit(opts *EditOptions, r *api.Repository) error { for _, v := range r.RepositoryTopics.Nodes { opts.topicsCache = append(opts.topicsCache, v.Topic.Name) } p := opts.Prompter choices, err := interactiveChoice(p, r) if err != nil { return err } for _, c := range choices { switch c { case optionDescription: answer, err := p.Input("Description of the repository", r.Description) if err != nil { return err } opts.Edits.Description = &answer case optionHomePageURL: a, err := p.Input("Repository home page URL", r.HomepageURL) if err != nil { return err } opts.Edits.Homepage = &a case optionTopics: addTopics, err := p.Input("Add topics?(csv format)", "") if err != nil { return err } if len(strings.TrimSpace(addTopics)) > 0 { opts.AddTopics = parseTopics(addTopics) } if len(opts.topicsCache) > 0 { selected, err := p.MultiSelect("Remove Topics", nil, opts.topicsCache) if err != nil { return err } for _, i := range selected { opts.RemoveTopics = append(opts.RemoveTopics, opts.topicsCache[i]) } } case optionDefaultBranchName: name, err := p.Input("Default branch name", r.DefaultBranchRef.Name) if err != nil { return err } opts.Edits.DefaultBranch = &name case optionWikis: c, err := p.Confirm("Enable Wikis?", r.HasWikiEnabled) if err != nil { return err } opts.Edits.EnableWiki = &c case optionIssues: a, err := p.Confirm("Enable Issues?", r.HasIssuesEnabled) if err != nil { return err } opts.Edits.EnableIssues = &a case optionProjects: a, err := p.Confirm("Enable Projects?", r.HasProjectsEnabled) if err != nil { return err } opts.Edits.EnableProjects = &a case optionVisibility: cs := opts.IO.ColorScheme() fmt.Fprintf(opts.IO.ErrOut, "%s Danger zone: changing repository visibility can have unexpected consequences; consult https://gh.io/setting-repository-visibility before continuing.\n", cs.WarningIcon()) visibilityOptions := []string{"public", "private", "internal"} selected, err := p.Select("Visibility", strings.ToLower(r.Visibility), visibilityOptions) if err != nil { return err } selectedVisibility := visibilityOptions[selected] if selectedVisibility != r.Visibility && (r.StargazerCount > 0 || r.Watchers.TotalCount > 0) { fmt.Fprintf(opts.IO.ErrOut, "%s Changing the repository visibility to %s will cause permanent loss of %s and %s.\n", cs.WarningIcon(), selectedVisibility, text.Pluralize(r.StargazerCount, "star"), text.Pluralize(r.Watchers.TotalCount, "watcher")) } confirmed, err := p.Confirm(fmt.Sprintf("Do you want to change visibility to %s?", selectedVisibility), false) if err != nil { return err } if confirmed { opts.Edits.Visibility = &selectedVisibility } case optionMergeOptions: var defaultMergeOptions []string var selectedMergeOptions []string if r.MergeCommitAllowed { defaultMergeOptions = append(defaultMergeOptions, allowMergeCommits) } if r.SquashMergeAllowed { defaultMergeOptions = append(defaultMergeOptions, allowSquashMerge) } if r.RebaseMergeAllowed { defaultMergeOptions = append(defaultMergeOptions, allowRebaseMerge) } mergeOpts := []string{allowMergeCommits, allowSquashMerge, allowRebaseMerge} selected, err := p.MultiSelect( "Allowed merge strategies", defaultMergeOptions, mergeOpts) if err != nil { return err } for _, i := range selected { selectedMergeOptions = append(selectedMergeOptions, mergeOpts[i]) } enableMergeCommit := isIncluded(allowMergeCommits, selectedMergeOptions) opts.Edits.EnableMergeCommit = &enableMergeCommit enableSquashMerge := isIncluded(allowSquashMerge, selectedMergeOptions) opts.Edits.EnableSquashMerge = &enableSquashMerge enableRebaseMerge := isIncluded(allowRebaseMerge, selectedMergeOptions) opts.Edits.EnableRebaseMerge = &enableRebaseMerge if !enableMergeCommit && !enableSquashMerge && !enableRebaseMerge { return fmt.Errorf("you need to allow at least one merge strategy") } opts.Edits.EnableAutoMerge = &r.AutoMergeAllowed c, err := p.Confirm("Enable Auto Merge?", r.AutoMergeAllowed) if err != nil { return err } opts.Edits.EnableAutoMerge = &c opts.Edits.DeleteBranchOnMerge = &r.DeleteBranchOnMerge c, err = p.Confirm( "Automatically delete head branches after merging?", r.DeleteBranchOnMerge) if err != nil { return err } opts.Edits.DeleteBranchOnMerge = &c case optionTemplateRepo: c, err := p.Confirm("Convert into a template repository?", r.IsTemplate) if err != nil { return err } opts.Edits.IsTemplate = &c case optionAllowForking: c, err := p.Confirm( "Allow forking (of an organization repository)?", r.ForkingAllowed) if err != nil { return err } opts.Edits.AllowForking = &c } } return nil } func parseTopics(s string) []string { topics := strings.Split(s, ",") for i, topic := range topics { topics[i] = strings.TrimSpace(topic) } return topics } func getTopics(ctx context.Context, httpClient *http.Client, repo ghrepo.Interface) ([]string, error) { apiPath := fmt.Sprintf("repos/%s/%s/topics", repo.RepoOwner(), repo.RepoName()) req, err := http.NewRequestWithContext(ctx, "GET", ghinstance.RESTPrefix(repo.RepoHost())+apiPath, nil) if err != nil { return nil, err } // "mercy-preview" is still needed for some GitHub Enterprise versions req.Header.Set("Accept", "application/vnd.github.mercy-preview+json") res, err := httpClient.Do(req) if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode != http.StatusOK { return nil, api.HandleHTTPError(res) } var responseData struct { Names []string `json:"names"` } dec := json.NewDecoder(res.Body) err = dec.Decode(&responseData) return responseData.Names, err } func setTopics(ctx context.Context, httpClient *http.Client, repo ghrepo.Interface, topics []string) error { payload := struct { Names []string `json:"names"` }{ Names: topics, } body := &bytes.Buffer{} dec := json.NewEncoder(body) if err := dec.Encode(&payload); err != nil { return err } apiPath := fmt.Sprintf("repos/%s/%s/topics", repo.RepoOwner(), repo.RepoName()) req, err := http.NewRequestWithContext(ctx, "PUT", ghinstance.RESTPrefix(repo.RepoHost())+apiPath, body) if err != nil { return err } req.Header.Set("Content-type", "application/json") // "mercy-preview" is still needed for some GitHub Enterprise versions req.Header.Set("Accept", "application/vnd.github.mercy-preview+json") res, err := httpClient.Do(req) if err != nil { return err } defer res.Body.Close() if res.StatusCode != http.StatusOK { return api.HandleHTTPError(res) } if res.Body != nil { _, _ = io.Copy(io.Discard, res.Body) } return nil } func isIncluded(value string, opts []string) bool { for _, opt := range opts { if strings.EqualFold(opt, value) { return true } } return false } func boolToStatus(status bool) *string { var result string if status { result = "enabled" } else { result = "disabled" } return &result } func hasSecurityEdits(edits EditRepositoryInput) bool { return edits.enableAdvancedSecurity != nil || edits.enableSecretScanning != nil || edits.enableSecretScanningPushProtection != nil } type SecurityAndAnalysisInput struct { EnableAdvancedSecurity *SecurityAndAnalysisStatus `json:"advanced_security,omitempty"` EnableSecretScanning *SecurityAndAnalysisStatus `json:"secret_scanning,omitempty"` EnableSecretScanningPushProtection *SecurityAndAnalysisStatus `json:"secret_scanning_push_protection,omitempty"` } type SecurityAndAnalysisStatus struct { Status *string `json:"status,omitempty"` } // Transform security and analysis parameters to properly serialize EditRepositoryInput // See API Docs: https://docs.github.com/en/rest/repos/repos?apiVersion=2022-11-28#update-a-repository func transformSecurityAndAnalysisOpts(opts *EditOptions) *SecurityAndAnalysisInput { securityOptions := &SecurityAndAnalysisInput{} if opts.Edits.enableAdvancedSecurity != nil { securityOptions.EnableAdvancedSecurity = &SecurityAndAnalysisStatus{ Status: boolToStatus(*opts.Edits.enableAdvancedSecurity), } } if opts.Edits.enableSecretScanning != nil { securityOptions.EnableSecretScanning = &SecurityAndAnalysisStatus{ Status: boolToStatus(*opts.Edits.enableSecretScanning), } } if opts.Edits.enableSecretScanningPushProtection != nil { securityOptions.EnableSecretScanningPushProtection = &SecurityAndAnalysisStatus{ Status: boolToStatus(*opts.Edits.enableSecretScanningPushProtection), } } return securityOptions }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/edit/edit_test.go
pkg/cmd/repo/edit/edit_test.go
package edit import ( "bytes" "context" "io" "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" "github.com/stretchr/testify/require" ) func TestNewCmdEdit(t *testing.T) { tests := []struct { name string args string wantOpts EditOptions wantErr string }{ { name: "change repo description", args: "--description hello", wantOpts: EditOptions{ Repository: ghrepo.NewWithHost("OWNER", "REPO", "github.com"), Edits: EditRepositoryInput{ Description: sp("hello"), }, }, }, { name: "deny public visibility change without accepting consequences", args: "--visibility public", wantOpts: EditOptions{ Repository: ghrepo.NewWithHost("OWNER", "REPO", "github.com"), Edits: EditRepositoryInput{}, }, wantErr: "use of --visibility flag requires --accept-visibility-change-consequences flag", }, { name: "allow public visibility change with accepting consequences", args: "--visibility public --accept-visibility-change-consequences", wantOpts: EditOptions{ Repository: ghrepo.NewWithHost("OWNER", "REPO", "github.com"), Edits: EditRepositoryInput{ Visibility: sp("public"), }, }, }, { name: "deny private visibility change without accepting consequences", args: "--visibility private", wantOpts: EditOptions{ Repository: ghrepo.NewWithHost("OWNER", "REPO", "github.com"), Edits: EditRepositoryInput{}, }, wantErr: "use of --visibility flag requires --accept-visibility-change-consequences flag", }, { name: "allow private visibility change with accepting consequences", args: "--visibility private --accept-visibility-change-consequences", wantOpts: EditOptions{ Repository: ghrepo.NewWithHost("OWNER", "REPO", "github.com"), Edits: EditRepositoryInput{ Visibility: sp("private"), }, }, }, { name: "deny internal visibility change without accepting consequences", args: "--visibility internal", wantOpts: EditOptions{ Repository: ghrepo.NewWithHost("OWNER", "REPO", "github.com"), Edits: EditRepositoryInput{}, }, wantErr: "use of --visibility flag requires --accept-visibility-change-consequences flag", }, { name: "allow internal visibility change with accepting consequences", args: "--visibility internal --accept-visibility-change-consequences", wantOpts: EditOptions{ Repository: ghrepo.NewWithHost("OWNER", "REPO", "github.com"), Edits: EditRepositoryInput{ Visibility: sp("internal"), }, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() ios.SetStdoutTTY(true) ios.SetStdinTTY(true) ios.SetStderrTTY(true) f := &cmdutil.Factory{ IOStreams: ios, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil }, HttpClient: func() (*http.Client, error) { return nil, nil }, } argv, err := shlex.Split(tt.args) 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(io.Discard) cmd.SetErr(io.Discard) _, err = cmd.ExecuteC() if tt.wantErr != "" { assert.EqualError(t, err, tt.wantErr) return } require.NoError(t, err) assert.Equal(t, ghrepo.FullName(tt.wantOpts.Repository), ghrepo.FullName(gotOpts.Repository)) assert.Equal(t, tt.wantOpts.Edits, gotOpts.Edits) }) } } func Test_editRun(t *testing.T) { tests := []struct { name string opts EditOptions httpStubs func(*testing.T, *httpmock.Registry) wantsStderr string wantsErr string }{ { name: "change name and description", opts: EditOptions{ Repository: ghrepo.NewWithHost("OWNER", "REPO", "github.com"), Edits: EditRepositoryInput{ Homepage: sp("newURL"), Description: sp("hello world!"), }, }, httpStubs: func(t *testing.T, r *httpmock.Registry) { r.Register( httpmock.REST("PATCH", "repos/OWNER/REPO"), httpmock.RESTPayload(200, `{}`, func(payload map[string]interface{}) { assert.Equal(t, 2, len(payload)) assert.Equal(t, "newURL", payload["homepage"]) assert.Equal(t, "hello world!", payload["description"]) })) }, }, { name: "add and remove topics", opts: EditOptions{ Repository: ghrepo.NewWithHost("OWNER", "REPO", "github.com"), AddTopics: []string{"topic1", "topic2"}, RemoveTopics: []string{"topic3"}, }, httpStubs: func(t *testing.T, r *httpmock.Registry) { r.Register( httpmock.REST("GET", "repos/OWNER/REPO/topics"), httpmock.StringResponse(`{"names":["topic2", "topic3", "go"]}`)) r.Register( httpmock.REST("PUT", "repos/OWNER/REPO/topics"), httpmock.RESTPayload(200, `{}`, func(payload map[string]interface{}) { assert.Equal(t, 1, len(payload)) assert.Equal(t, []interface{}{"topic2", "go", "topic1"}, payload["names"]) })) }, }, { name: "allow update branch", opts: EditOptions{ Repository: ghrepo.NewWithHost("OWNER", "REPO", "github.com"), Edits: EditRepositoryInput{ AllowUpdateBranch: bp(true), }, }, httpStubs: func(t *testing.T, r *httpmock.Registry) { r.Register( httpmock.REST("PATCH", "repos/OWNER/REPO"), httpmock.RESTPayload(200, `{}`, func(payload map[string]interface{}) { assert.Equal(t, 1, len(payload)) assert.Equal(t, true, payload["allow_update_branch"]) })) }, }, { name: "enable/disable security and analysis settings", opts: EditOptions{ Repository: ghrepo.NewWithHost("OWNER", "REPO", "github.com"), Edits: EditRepositoryInput{ SecurityAndAnalysis: &SecurityAndAnalysisInput{ EnableAdvancedSecurity: &SecurityAndAnalysisStatus{ Status: sp("enabled"), }, EnableSecretScanning: &SecurityAndAnalysisStatus{ Status: sp("enabled"), }, EnableSecretScanningPushProtection: &SecurityAndAnalysisStatus{ Status: sp("disabled"), }, }, }, }, httpStubs: func(t *testing.T, r *httpmock.Registry) { r.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(`{"data": { "repository": { "viewerCanAdminister": true } } }`)) r.Register( httpmock.REST("PATCH", "repos/OWNER/REPO"), httpmock.RESTPayload(200, `{}`, func(payload map[string]interface{}) { assert.Equal(t, 1, len(payload)) securityAndAnalysis := payload["security_and_analysis"].(map[string]interface{}) assert.Equal(t, "enabled", securityAndAnalysis["advanced_security"].(map[string]interface{})["status"]) assert.Equal(t, "enabled", securityAndAnalysis["secret_scanning"].(map[string]interface{})["status"]) assert.Equal(t, "disabled", securityAndAnalysis["secret_scanning_push_protection"].(map[string]interface{})["status"]) })) }, }, { name: "does not have sufficient permissions for security edits", opts: EditOptions{ Repository: ghrepo.NewWithHost("OWNER", "REPO", "github.com"), Edits: EditRepositoryInput{ SecurityAndAnalysis: &SecurityAndAnalysisInput{ EnableAdvancedSecurity: &SecurityAndAnalysisStatus{ Status: sp("enabled"), }, EnableSecretScanning: &SecurityAndAnalysisStatus{ Status: sp("enabled"), }, EnableSecretScanningPushProtection: &SecurityAndAnalysisStatus{ Status: sp("disabled"), }, }, }, }, httpStubs: func(t *testing.T, r *httpmock.Registry) { r.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(`{"data": { "repository": { "viewerCanAdminister": false } } }`)) }, wantsErr: "you do not have sufficient permissions to edit repository security and analysis features", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() ios.SetStdoutTTY(true) ios.SetStdinTTY(true) ios.SetStderrTTY(true) httpReg := &httpmock.Registry{} defer httpReg.Verify(t) if tt.httpStubs != nil { tt.httpStubs(t, httpReg) } opts := &tt.opts opts.HTTPClient = &http.Client{Transport: httpReg} opts.IO = ios err := editRun(context.Background(), opts) if tt.wantsErr == "" { require.NoError(t, err) } else { assert.EqualError(t, err, tt.wantsErr) return } }) } } func Test_editRun_interactive(t *testing.T) { editList := []string{ "Default Branch Name", "Description", "Home Page URL", "Issues", "Merge Options", "Projects", "Template Repository", "Topics", "Visibility", "Wikis"} tests := []struct { name string opts EditOptions promptStubs func(*prompter.MockPrompter) httpStubs func(*testing.T, *httpmock.Registry) wantsStderr string wantsErr string }{ { name: "forking of org repo", opts: EditOptions{ Repository: ghrepo.NewWithHost("OWNER", "REPO", "github.com"), InteractiveMode: true, }, promptStubs: func(pm *prompter.MockPrompter) { el := append(editList, optionAllowForking) pm.RegisterMultiSelect("What do you want to edit?", nil, el, func(_ string, _, opts []string) ([]int, error) { return []int{10}, nil }) pm.RegisterConfirm("Allow forking (of an organization repository)?", func(_ string, _ bool) (bool, error) { return true, nil }) }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "visibility": "public", "description": "description", "homePageUrl": "https://url.com", "defaultBranchRef": { "name": "main" }, "isInOrganization": true, "repositoryTopics": { "nodes": [{ "topic": { "name": "x" } }] } } } }`)) reg.Register( httpmock.REST("PATCH", "repos/OWNER/REPO"), httpmock.RESTPayload(200, `{}`, func(payload map[string]interface{}) { assert.Equal(t, true, payload["allow_forking"]) })) }, }, { name: "skipping visibility without confirmation", opts: EditOptions{ Repository: ghrepo.NewWithHost("OWNER", "REPO", "github.com"), InteractiveMode: true, }, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterMultiSelect("What do you want to edit?", nil, editList, func(_ string, _, opts []string) ([]int, error) { return []int{8}, nil }) pm.RegisterSelect("Visibility", []string{"public", "private", "internal"}, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "private") }) pm.RegisterConfirm("Do you want to change visibility to private?", func(_ string, _ bool) (bool, error) { return false, nil }) }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "visibility": "public", "description": "description", "homePageUrl": "https://url.com", "defaultBranchRef": { "name": "main" }, "stargazerCount": 10, "isInOrganization": false, "repositoryTopics": { "nodes": [{ "topic": { "name": "x" } }] } } } }`)) reg.Exclude(t, httpmock.REST("PATCH", "repos/OWNER/REPO")) }, wantsStderr: "Changing the repository visibility to private will cause permanent loss of 10 stars and 0 watchers.", }, { name: "changing visibility with confirmation", opts: EditOptions{ Repository: ghrepo.NewWithHost("OWNER", "REPO", "github.com"), InteractiveMode: true, }, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterMultiSelect("What do you want to edit?", nil, editList, func(_ string, _, opts []string) ([]int, error) { return []int{8}, nil }) pm.RegisterSelect("Visibility", []string{"public", "private", "internal"}, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "private") }) pm.RegisterConfirm("Do you want to change visibility to private?", func(_ string, _ bool) (bool, error) { return true, nil }) }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "visibility": "public", "description": "description", "homePageUrl": "https://url.com", "defaultBranchRef": { "name": "main" }, "stargazerCount": 10, "watchers": { "totalCount": 15 }, "isInOrganization": false, "repositoryTopics": { "nodes": [{ "topic": { "name": "x" } }] } } } }`)) reg.Register( httpmock.REST("PATCH", "repos/OWNER/REPO"), httpmock.RESTPayload(200, `{}`, func(payload map[string]interface{}) { assert.Equal(t, "private", payload["visibility"]) })) }, wantsStderr: "Changing the repository visibility to private will cause permanent loss of 10 stars and 15 watchers", }, { name: "the rest", opts: EditOptions{ Repository: ghrepo.NewWithHost("OWNER", "REPO", "github.com"), InteractiveMode: true, }, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterMultiSelect("What do you want to edit?", nil, editList, func(_ string, _, opts []string) ([]int, error) { return []int{0, 2, 3, 5, 6, 9}, nil }) pm.RegisterInput("Default branch name", func(_, _ string) (string, error) { return "trunk", nil }) pm.RegisterInput("Repository home page URL", func(_, _ string) (string, error) { return "https://zombo.com", nil }) pm.RegisterConfirm("Enable Issues?", func(_ string, _ bool) (bool, error) { return true, nil }) pm.RegisterConfirm("Enable Projects?", func(_ string, _ bool) (bool, error) { return true, nil }) pm.RegisterConfirm("Convert into a template repository?", func(_ string, _ bool) (bool, error) { return true, nil }) pm.RegisterConfirm("Enable Wikis?", func(_ string, _ bool) (bool, error) { return true, nil }) }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "visibility": "public", "description": "description", "homePageUrl": "https://url.com", "defaultBranchRef": { "name": "main" }, "stargazerCount": 10, "isInOrganization": false, "repositoryTopics": { "nodes": [{ "topic": { "name": "x" } }] } } } }`)) reg.Register( httpmock.REST("PATCH", "repos/OWNER/REPO"), httpmock.RESTPayload(200, `{}`, func(payload map[string]interface{}) { assert.Equal(t, "trunk", payload["default_branch"]) assert.Equal(t, "https://zombo.com", payload["homepage"]) assert.Equal(t, true, payload["has_issues"]) assert.Equal(t, true, payload["has_projects"]) assert.Equal(t, true, payload["is_template"]) assert.Equal(t, true, payload["has_wiki"]) })) }, }, { name: "updates repo description", opts: EditOptions{ Repository: ghrepo.NewWithHost("OWNER", "REPO", "github.com"), InteractiveMode: true, }, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterMultiSelect("What do you want to edit?", nil, editList, func(_ string, _, opts []string) ([]int, error) { return []int{1}, nil }) pm.RegisterInput("Description of the repository", func(_, _ string) (string, error) { return "awesome repo description", nil }) }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "description": "old description", "homePageUrl": "https://url.com", "defaultBranchRef": { "name": "main" }, "isInOrganization": false, "repositoryTopics": { "nodes": [{ "topic": { "name": "x" } }] } } } }`)) reg.Register( httpmock.REST("PATCH", "repos/OWNER/REPO"), httpmock.RESTPayload(200, `{}`, func(payload map[string]interface{}) { assert.Equal(t, "awesome repo description", payload["description"]) })) }, }, { name: "updates repo topics", opts: EditOptions{ Repository: ghrepo.NewWithHost("OWNER", "REPO", "github.com"), InteractiveMode: true, }, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterMultiSelect("What do you want to edit?", nil, editList, func(_ string, _, opts []string) ([]int, error) { return []int{1, 7}, nil }) pm.RegisterInput("Description of the repository", func(_, _ string) (string, error) { return "awesome repo description", nil }) pm.RegisterInput("Add topics?(csv format)", func(_, _ string) (string, error) { return "a, b,c,d ", nil }) pm.RegisterMultiSelect("Remove Topics", nil, []string{"x"}, func(_ string, _, opts []string) ([]int, error) { return []int{0}, nil }) }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "description": "old description", "homePageUrl": "https://url.com", "defaultBranchRef": { "name": "main" }, "isInOrganization": false, "repositoryTopics": { "nodes": [{ "topic": { "name": "x" } }] } } } }`)) reg.Register( httpmock.REST("PATCH", "repos/OWNER/REPO"), httpmock.RESTPayload(200, `{}`, func(payload map[string]interface{}) { assert.Equal(t, "awesome repo description", payload["description"]) })) reg.Register( httpmock.REST("PUT", "repos/OWNER/REPO/topics"), httpmock.RESTPayload(200, `{}`, func(payload map[string]interface{}) { assert.Equal(t, []interface{}{"a", "b", "c", "d"}, payload["names"]) })) }, }, { name: "updates repo merge options", opts: EditOptions{ Repository: ghrepo.NewWithHost("OWNER", "REPO", "github.com"), InteractiveMode: true, }, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterMultiSelect("What do you want to edit?", nil, editList, func(_ string, _, opts []string) ([]int, error) { return []int{4}, nil }) pm.RegisterMultiSelect("Allowed merge strategies", nil, []string{allowMergeCommits, allowSquashMerge, allowRebaseMerge}, func(_ string, _, opts []string) ([]int, error) { return []int{0, 2}, nil }) pm.RegisterConfirm("Enable Auto Merge?", func(_ string, _ bool) (bool, error) { return false, nil }) pm.RegisterConfirm("Automatically delete head branches after merging?", func(_ string, _ bool) (bool, error) { return false, nil }) }, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(` { "data": { "repository": { "description": "old description", "homePageUrl": "https://url.com", "defaultBranchRef": { "name": "main" }, "isInOrganization": false, "squashMergeAllowed": false, "rebaseMergeAllowed": true, "mergeCommitAllowed": true, "deleteBranchOnMerge": false, "repositoryTopics": { "nodes": [{ "topic": { "name": "x" } }] } } } }`)) reg.Register( httpmock.REST("PATCH", "repos/OWNER/REPO"), httpmock.RESTPayload(200, `{}`, func(payload map[string]interface{}) { assert.Equal(t, true, payload["allow_merge_commit"]) assert.Equal(t, false, payload["allow_squash_merge"]) assert.Equal(t, true, payload["allow_rebase_merge"]) })) }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, stderr := iostreams.Test() ios.SetStdoutTTY(true) ios.SetStdinTTY(true) ios.SetStderrTTY(true) httpReg := &httpmock.Registry{} defer httpReg.Verify(t) if tt.httpStubs != nil { tt.httpStubs(t, httpReg) } pm := prompter.NewMockPrompter(t) tt.opts.Prompter = pm if tt.promptStubs != nil { tt.promptStubs(pm) } opts := &tt.opts opts.HTTPClient = &http.Client{Transport: httpReg} opts.IO = ios err := editRun(context.Background(), opts) if tt.wantsErr == "" { require.NoError(t, err) } else { require.EqualError(t, err, tt.wantsErr) return } assert.Contains(t, stderr.String(), tt.wantsStderr) }) } } func Test_transformSecurityAndAnalysisOpts(t *testing.T) { tests := []struct { name string opts EditOptions want *SecurityAndAnalysisInput }{ { name: "Enable all security and analysis settings", opts: EditOptions{ Edits: EditRepositoryInput{ enableAdvancedSecurity: bp(true), enableSecretScanning: bp(true), enableSecretScanningPushProtection: bp(true), }, }, want: &SecurityAndAnalysisInput{ EnableAdvancedSecurity: &SecurityAndAnalysisStatus{ Status: sp("enabled"), }, EnableSecretScanning: &SecurityAndAnalysisStatus{ Status: sp("enabled"), }, EnableSecretScanningPushProtection: &SecurityAndAnalysisStatus{ Status: sp("enabled"), }, }, }, { name: "Disable all security and analysis settings", opts: EditOptions{ Edits: EditRepositoryInput{ enableAdvancedSecurity: bp(false), enableSecretScanning: bp(false), enableSecretScanningPushProtection: bp(false), }, }, want: &SecurityAndAnalysisInput{ EnableAdvancedSecurity: &SecurityAndAnalysisStatus{ Status: sp("disabled"), }, EnableSecretScanning: &SecurityAndAnalysisStatus{ Status: sp("disabled"), }, EnableSecretScanningPushProtection: &SecurityAndAnalysisStatus{ Status: sp("disabled"), }, }, }, { name: "Enable only advanced security", opts: EditOptions{ Edits: EditRepositoryInput{ enableAdvancedSecurity: bp(true), }, }, want: &SecurityAndAnalysisInput{ EnableAdvancedSecurity: &SecurityAndAnalysisStatus{ Status: sp("enabled"), }, EnableSecretScanning: nil, EnableSecretScanningPushProtection: nil, }, }, { name: "Disable only secret scanning", opts: EditOptions{ Edits: EditRepositoryInput{ enableSecretScanning: bp(false), }, }, want: &SecurityAndAnalysisInput{ EnableAdvancedSecurity: nil, EnableSecretScanning: &SecurityAndAnalysisStatus{ Status: sp("disabled"), }, EnableSecretScanningPushProtection: nil, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { opts := &tt.opts transformed := transformSecurityAndAnalysisOpts(opts) assert.Equal(t, tt.want, transformed) }) } } func sp(v string) *string { return &v } func bp(b bool) *bool { return &b }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/deploy-key/deploy-key.go
pkg/cmd/repo/deploy-key/deploy-key.go
package deploykey import ( cmdAdd "github.com/cli/cli/v2/pkg/cmd/repo/deploy-key/add" cmdDelete "github.com/cli/cli/v2/pkg/cmd/repo/deploy-key/delete" cmdList "github.com/cli/cli/v2/pkg/cmd/repo/deploy-key/list" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/spf13/cobra" ) func NewCmdDeployKey(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "deploy-key <command>", Short: "Manage deploy keys in a repository", } cmdutil.EnableRepoOverride(cmd, f) cmd.AddCommand(cmdList.NewCmdList(f, nil)) cmd.AddCommand(cmdAdd.NewCmdAdd(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/repo/deploy-key/delete/delete.go
pkg/cmd/repo/deploy-key/delete/delete.go
package delete import ( "fmt" "net/http" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type DeleteOptions struct { IO *iostreams.IOStreams HTTPClient func() (*http.Client, error) BaseRepo func() (ghrepo.Interface, error) KeyID string } func NewCmdDelete(f *cmdutil.Factory, runF func(*DeleteOptions) error) *cobra.Command { opts := &DeleteOptions{ HTTPClient: f.HttpClient, IO: f.IOStreams, } cmd := &cobra.Command{ Use: "delete <key-id>", Short: "Delete a deploy key from a GitHub repository", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.BaseRepo = f.BaseRepo opts.KeyID = args[0] if runF != nil { return runF(opts) } return deleteRun(opts) }, } return cmd } func deleteRun(opts *DeleteOptions) error { httpClient, err := opts.HTTPClient() if err != nil { return err } repo, err := opts.BaseRepo() if err != nil { return err } if err := deleteDeployKey(httpClient, repo, opts.KeyID); err != nil { return err } if !opts.IO.IsStdoutTTY() { return nil } cs := opts.IO.ColorScheme() _, err = fmt.Fprintf(opts.IO.Out, "%s Deploy key deleted from %s\n", cs.SuccessIconWithColor(cs.Red), cs.Bold(ghrepo.FullName(repo))) return err }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/deploy-key/delete/delete_test.go
pkg/cmd/repo/deploy-key/delete/delete_test.go
package delete import ( "net/http" "testing" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/stretchr/testify/assert" ) func Test_deleteRun(t *testing.T) { ios, _, stdout, stderr := iostreams.Test() ios.SetStdinTTY(false) ios.SetStdoutTTY(true) ios.SetStderrTTY(true) tr := httpmock.Registry{} defer tr.Verify(t) tr.Register( httpmock.REST("DELETE", "repos/OWNER/REPO/keys/1234"), httpmock.StringResponse(`{}`)) err := deleteRun(&DeleteOptions{ IO: ios, HTTPClient: func() (*http.Client, error) { return &http.Client{Transport: &tr}, nil }, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil }, KeyID: "1234", }) assert.NoError(t, err) assert.Equal(t, "", stderr.String()) assert.Equal(t, "✓ Deploy key deleted from OWNER/REPO\n", stdout.String()) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/deploy-key/delete/http.go
pkg/cmd/repo/deploy-key/delete/http.go
package delete import ( "fmt" "io" "net/http" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghinstance" "github.com/cli/cli/v2/internal/ghrepo" ) func deleteDeployKey(httpClient *http.Client, repo ghrepo.Interface, id string) error { path := fmt.Sprintf("repos/%s/%s/keys/%s", repo.RepoOwner(), repo.RepoName(), id) url := ghinstance.RESTPrefix(repo.RepoHost()) + path 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) } _, err = io.Copy(io.Discard, resp.Body) if err != nil { return err } return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/deploy-key/list/list_test.go
pkg/cmd/repo/deploy-key/list/list_test.go
package list import ( "fmt" "net/http" "testing" "time" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" ) func TestListRun(t *testing.T) { tests := []struct { name string opts ListOptions isTTY bool httpStubs func(t *testing.T, reg *httpmock.Registry) wantStdout string wantStderr string wantErr bool }{ { name: "list tty", isTTY: true, httpStubs: func(t *testing.T, reg *httpmock.Registry) { createdAt := time.Now().Add(time.Duration(-24) * time.Hour) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/keys"), httpmock.StringResponse(fmt.Sprintf(`[ { "id": 1234, "key": "ssh-rsa AAAABbBB123", "title": "Mac", "created_at": "%[1]s", "read_only": true }, { "id": 5678, "key": "ssh-rsa EEEEEEEK247", "title": "hubot@Windows", "created_at": "%[1]s", "read_only": false } ]`, createdAt.Format(time.RFC3339))), ) }, wantStdout: heredoc.Doc(` ID TITLE TYPE KEY CREATED AT 1234 Mac read-only ssh-rsa AAAABbBB123 about 1 day ago 5678 hubot@Windows read-write ssh-rsa EEEEEEEK247 about 1 day ago `), wantStderr: "", }, { name: "list non-tty", isTTY: false, httpStubs: func(t *testing.T, reg *httpmock.Registry) { createdAt, _ := time.Parse(time.RFC3339, "2020-08-31T15:44:24+02:00") reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/keys"), httpmock.StringResponse(fmt.Sprintf(`[ { "id": 1234, "key": "ssh-rsa AAAABbBB123", "title": "Mac", "created_at": "%[1]s", "read_only": false }, { "id": 5678, "key": "ssh-rsa EEEEEEEK247", "title": "hubot@Windows", "created_at": "%[1]s", "read_only": true } ]`, createdAt.Format(time.RFC3339))), ) }, wantStdout: heredoc.Doc(` 1234 Mac read-write ssh-rsa AAAABbBB123 2020-08-31T15:44:24+02:00 5678 hubot@Windows read-only ssh-rsa EEEEEEEK247 2020-08-31T15:44:24+02:00 `), wantStderr: "", }, { name: "no keys", isTTY: true, httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/keys"), httpmock.StringResponse(`[]`)) }, wantStdout: "", wantStderr: "", wantErr: 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) reg := &httpmock.Registry{} if tt.httpStubs != nil { tt.httpStubs(t, reg) } opts := tt.opts opts.IO = ios opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil } opts.HTTPClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } err := listRun(&opts) if (err != nil) != tt.wantErr { t.Errorf("listRun() return error: %v", err) return } if stdout.String() != tt.wantStdout { t.Errorf("wants stdout %q, got %q", tt.wantStdout, stdout.String()) } if stderr.String() != tt.wantStderr { t.Errorf("wants stderr %q, got %q", tt.wantStderr, stderr.String()) } }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/deploy-key/list/list.go
pkg/cmd/repo/deploy-key/list/list.go
package list import ( "fmt" "net/http" "strconv" "time" "github.com/cli/cli/v2/internal/ghrepo" "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) BaseRepo func() (ghrepo.Interface, error) Exporter cmdutil.Exporter } var deployKeyFields = []string{ "id", "key", "title", "createdAt", "readOnly", } func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Command { opts := &ListOptions{ IO: f.IOStreams, HTTPClient: f.HttpClient, } cmd := &cobra.Command{ Use: "list", Short: "List deploy keys in a GitHub repository", Aliases: []string{"ls"}, Args: cobra.ExactArgs(0), RunE: func(cmd *cobra.Command, args []string) error { opts.BaseRepo = f.BaseRepo if runF != nil { return runF(opts) } return listRun(opts) }, } cmdutil.AddJSONFlags(cmd, &opts.Exporter, deployKeyFields) return cmd } func listRun(opts *ListOptions) error { apiClient, err := opts.HTTPClient() if err != nil { return err } repo, err := opts.BaseRepo() if err != nil { return err } deployKeys, err := repoKeys(apiClient, repo) if err != nil { return err } if len(deployKeys) == 0 { return cmdutil.NewNoResultsError(fmt.Sprintf("no deploy keys found in %s", ghrepo.FullName(repo))) } if opts.Exporter != nil { return opts.Exporter.Write(opts.IO, deployKeys) } t := tableprinter.New(opts.IO, tableprinter.WithHeader("ID", "TITLE", "TYPE", "KEY", "CREATED AT")) cs := opts.IO.ColorScheme() now := time.Now() for _, deployKey := range deployKeys { sshID := strconv.Itoa(deployKey.ID) t.AddField(sshID) t.AddField(deployKey.Title) sshType := "read-only" if !deployKey.ReadOnly { sshType = "read-write" } t.AddField(sshType) t.AddField(deployKey.Key, tableprinter.WithTruncate(truncateMiddle)) t.AddTimeField(now, deployKey.CreatedAt, 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/repo/deploy-key/list/http.go
pkg/cmd/repo/deploy-key/list/http.go
package list import ( "encoding/json" "fmt" "io" "net/http" "time" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghinstance" "github.com/cli/cli/v2/internal/ghrepo" ) type deployKey struct { ID int `json:"id"` Key string `json:"key"` Title string `json:"title"` CreatedAt time.Time `json:"created_at"` ReadOnly bool `json:"read_only"` } func repoKeys(httpClient *http.Client, repo ghrepo.Interface) ([]deployKey, error) { path := fmt.Sprintf("repos/%s/%s/keys?per_page=100", repo.RepoOwner(), repo.RepoName()) url := ghinstance.RESTPrefix(repo.RepoHost()) + path 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 []deployKey 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/repo/deploy-key/add/add.go
pkg/cmd/repo/deploy-key/add/add.go
package add import ( "fmt" "io" "net/http" "os" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type AddOptions struct { IO *iostreams.IOStreams HTTPClient func() (*http.Client, error) BaseRepo func() (ghrepo.Interface, error) KeyFile string Title string AllowWrite bool } func NewCmdAdd(f *cmdutil.Factory, runF func(*AddOptions) error) *cobra.Command { opts := &AddOptions{ HTTPClient: f.HttpClient, IO: f.IOStreams, } cmd := &cobra.Command{ Use: "add <key-file>", Short: "Add a deploy key to a GitHub repository", Long: heredoc.Doc(` Add a deploy key to a GitHub repository. Note that any key added by gh will be associated with the current authentication token. If you de-authorize the GitHub CLI app or authentication token from your account, any deploy keys added by GitHub CLI will be removed as well. `), Example: heredoc.Doc(` # Generate a passwordless SSH key and add it as a deploy key to a repository $ ssh-keygen -t ed25519 -C "my description" -N "" -f ~/.ssh/gh-test $ gh repo deploy-key add ~/.ssh/gh-test.pub `), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.BaseRepo = f.BaseRepo opts.KeyFile = args[0] if runF != nil { return runF(opts) } return addRun(opts) }, } cmd.Flags().StringVarP(&opts.Title, "title", "t", "", "Title of the new key") cmd.Flags().BoolVarP(&opts.AllowWrite, "allow-write", "w", false, "Allow write access for the key") return cmd } func addRun(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 } repo, err := opts.BaseRepo() if err != nil { return err } if err := uploadDeployKey(httpClient, repo, keyReader, opts.Title, opts.AllowWrite); err != nil { return err } if !opts.IO.IsStdoutTTY() { return nil } cs := opts.IO.ColorScheme() _, err = fmt.Fprintf(opts.IO.Out, "%s Deploy key added to %s\n", cs.SuccessIcon(), cs.Bold(ghrepo.FullName(repo))) return err }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/deploy-key/add/http.go
pkg/cmd/repo/deploy-key/add/http.go
package add import ( "bytes" "encoding/json" "fmt" "io" "net/http" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghinstance" "github.com/cli/cli/v2/internal/ghrepo" ) func uploadDeployKey(httpClient *http.Client, repo ghrepo.Interface, keyFile io.Reader, title string, isWritable bool) error { path := fmt.Sprintf("repos/%s/%s/keys", repo.RepoOwner(), repo.RepoName()) url := ghinstance.RESTPrefix(repo.RepoHost()) + path keyBytes, err := io.ReadAll(keyFile) if err != nil { return err } payload := map[string]interface{}{ "title": title, "key": string(keyBytes), "read_only": !isWritable, } payloadBytes, err := json.Marshal(payload) if err != nil { return err } req, err := http.NewRequest("POST", url, bytes.NewBuffer(payloadBytes)) if err != nil { return err } resp, err := httpClient.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode > 299 { return api.HandleHTTPError(resp) } _, err = io.Copy(io.Discard, resp.Body) if err != nil { return err } return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/repo/deploy-key/add/add_test.go
pkg/cmd/repo/deploy-key/add/add_test.go
package add import ( "net/http" "testing" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" ) func Test_addRun(t *testing.T) { tests := []struct { name string opts AddOptions isTTY bool stdin string httpStubs func(t *testing.T, reg *httpmock.Registry) wantStdout string wantStderr string wantErr bool }{ { name: "add from stdin", isTTY: true, opts: AddOptions{ KeyFile: "-", Title: "my sacred key", AllowWrite: false, }, stdin: "PUBKEY\n", httpStubs: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/keys"), httpmock.RESTPayload(200, `{}`, func(payload map[string]interface{}) { if title := payload["title"].(string); title != "my sacred key" { t.Errorf("POST title %q, want %q", title, "my sacred key") } if key := payload["key"].(string); key != "PUBKEY\n" { t.Errorf("POST key %q, want %q", key, "PUBKEY\n") } if isReadOnly := payload["read_only"].(bool); !isReadOnly { t.Errorf("POST read_only %v, want %v", isReadOnly, true) } })) }, wantStdout: "✓ Deploy key added to OWNER/REPO\n", wantStderr: "", wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, stdin, stdout, stderr := iostreams.Test() stdin.WriteString(tt.stdin) ios.SetStdinTTY(tt.isTTY) ios.SetStdoutTTY(tt.isTTY) ios.SetStderrTTY(tt.isTTY) reg := &httpmock.Registry{} if tt.httpStubs != nil { tt.httpStubs(t, reg) } opts := tt.opts opts.IO = ios opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.New("OWNER", "REPO"), nil } opts.HTTPClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } err := addRun(&opts) if (err != nil) != tt.wantErr { t.Errorf("addRun() return error: %v", err) return } if stdout.String() != tt.wantStdout { t.Errorf("wants stdout %q, got %q", tt.wantStdout, stdout.String()) } if stderr.String() != tt.wantStderr { t.Errorf("wants stderr %q, got %q", tt.wantStderr, stderr.String()) } }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false