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/config/list/list.go
pkg/cmd/config/list/list.go
package list import ( "fmt" "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/spf13/cobra" ) type ListOptions struct { IO *iostreams.IOStreams Config func() (gh.Config, error) Hostname string } func NewCmdConfigList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Command { opts := &ListOptions{ IO: f.IOStreams, Config: f.Config, } cmd := &cobra.Command{ Use: "list", Short: "Print a list of configuration keys and values", Aliases: []string{"ls"}, Args: cobra.ExactArgs(0), RunE: func(cmd *cobra.Command, args []string) error { if runF != nil { return runF(opts) } return listRun(opts) }, } cmd.Flags().StringVarP(&opts.Hostname, "host", "h", "", "Get per-host configuration") return cmd } func listRun(opts *ListOptions) error { cfg, err := opts.Config() if err != nil { return err } var host string if opts.Hostname != "" { host = opts.Hostname } else { host, _ = cfg.Authentication().DefaultHost() } for _, option := range config.Options { fmt.Fprintf(opts.IO.Out, "%s=%s\n", option.Key, option.CurrentValue(cfg, host)) } return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/config/get/get_test.go
pkg/cmd/config/get/get_test.go
package get import ( "bytes" "testing" "github.com/cli/cli/v2/internal/config" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNewCmdConfigGet(t *testing.T) { tests := []struct { name string input string output GetOptions wantsErr bool }{ { name: "no arguments", input: "", output: GetOptions{}, wantsErr: true, }, { name: "get key", input: "key", output: GetOptions{Key: "key"}, wantsErr: false, }, { name: "get key with host", input: "key --host test.com", output: GetOptions{Hostname: "test.com", Key: "key"}, wantsErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { f := &cmdutil.Factory{ Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, } argv, err := shlex.Split(tt.input) assert.NoError(t, err) var gotOpts *GetOptions cmd := NewCmdConfigGet(f, func(opts *GetOptions) error { gotOpts = opts return nil }) cmd.Flags().BoolP("help", "x", false, "") cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) return } assert.NoError(t, err) assert.Equal(t, tt.output.Hostname, gotOpts.Hostname) assert.Equal(t, tt.output.Key, gotOpts.Key) }) } } func Test_getRun(t *testing.T) { tests := []struct { name string input *GetOptions stdout string err error }{ { name: "get key", input: &GetOptions{ Key: "editor", Config: func() gh.Config { cfg := config.NewBlankConfig() cfg.Set("", "editor", "ed") return cfg }(), }, stdout: "ed\n", }, { name: "get key scoped by host", input: &GetOptions{ Hostname: "github.com", Key: "editor", Config: func() gh.Config { cfg := config.NewBlankConfig() cfg.Set("", "editor", "ed") cfg.Set("github.com", "editor", "vim") return cfg }(), }, stdout: "vim\n", }, { name: "non-existent key", input: &GetOptions{ Key: "non-existent", Config: config.NewBlankConfig(), }, err: nonExistentKeyError{key: "non-existent"}, }, } for _, tt := range tests { ios, _, stdout, _ := iostreams.Test() tt.input.IO = ios t.Run(tt.name, func(t *testing.T) { err := getRun(tt.input) require.Equal(t, err, tt.err) require.Equal(t, tt.stdout, stdout.String()) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/config/get/get.go
pkg/cmd/config/get/get.go
package get import ( "errors" "fmt" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type GetOptions struct { IO *iostreams.IOStreams Config gh.Config Hostname string Key string } func NewCmdConfigGet(f *cmdutil.Factory, runF func(*GetOptions) error) *cobra.Command { opts := &GetOptions{ IO: f.IOStreams, } cmd := &cobra.Command{ Use: "get <key>", Short: "Print the value of a given configuration key", Example: heredoc.Doc(` $ gh config get git_protocol `), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { config, err := f.Config() if err != nil { return err } opts.Config = config opts.Key = args[0] if runF != nil { return runF(opts) } return getRun(opts) }, } cmd.Flags().StringVarP(&opts.Hostname, "host", "h", "", "Get per-host setting") return cmd } func getRun(opts *GetOptions) error { // search keyring storage when fetching the `oauth_token` value if opts.Hostname != "" && opts.Key == "oauth_token" { token, _ := opts.Config.Authentication().ActiveToken(opts.Hostname) if token == "" { return errors.New(`could not find key "oauth_token"`) } fmt.Fprintf(opts.IO.Out, "%s\n", token) return nil } optionalEntry := opts.Config.GetOrDefault(opts.Hostname, opts.Key) if optionalEntry.IsNone() { return nonExistentKeyError{key: opts.Key} } val := optionalEntry.Unwrap().Value if val != "" { fmt.Fprintf(opts.IO.Out, "%s\n", val) } return nil } type nonExistentKeyError struct { key string } func (e nonExistentKeyError) Error() string { return fmt.Sprintf("could not find key \"%s\"", e.key) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/config/clear-cache/clear_cache_test.go
pkg/cmd/config/clear-cache/clear_cache_test.go
package clearcache import ( "fmt" "os" "path/filepath" "testing" "github.com/cli/cli/v2/pkg/iostreams" "github.com/stretchr/testify/assert" ) func TestClearCacheRun(t *testing.T) { cacheDir := filepath.Join(t.TempDir(), "gh-cli-cache") ios, _, stdout, stderr := iostreams.Test() opts := &ClearCacheOptions{ IO: ios, CacheDir: cacheDir, } if err := os.Mkdir(opts.CacheDir, 0600); err != nil { assert.NoError(t, err) } if err := clearCacheRun(opts); err != nil { assert.NoError(t, err) } assert.NoDirExistsf(t, opts.CacheDir, fmt.Sprintf("Cache dir: %s still exists", opts.CacheDir)) assert.Equal(t, "✓ Cleared the cache\n", stdout.String()) assert.Equal(t, "", stderr.String()) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/config/clear-cache/clear_cache.go
pkg/cmd/config/clear-cache/clear_cache.go
package clearcache import ( "fmt" "os" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/go-gh/v2/pkg/config" "github.com/spf13/cobra" ) type ClearCacheOptions struct { IO *iostreams.IOStreams CacheDir string } func NewCmdConfigClearCache(f *cmdutil.Factory, runF func(*ClearCacheOptions) error) *cobra.Command { opts := &ClearCacheOptions{ IO: f.IOStreams, CacheDir: config.CacheDir(), } cmd := &cobra.Command{ Use: "clear-cache", Short: "Clear the cli cache", Example: heredoc.Doc(` # Clear the cli cache $ gh config clear-cache `), Args: cobra.ExactArgs(0), RunE: func(_ *cobra.Command, _ []string) error { if runF != nil { return runF(opts) } return clearCacheRun(opts) }, } return cmd } func clearCacheRun(opts *ClearCacheOptions) error { if err := os.RemoveAll(opts.CacheDir); err != nil { return err } cs := opts.IO.ColorScheme() fmt.Fprintf(opts.IO.Out, "%s Cleared the cache\n", cs.SuccessIcon()) return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/config/set/set_test.go
pkg/cmd/config/set/set_test.go
package set import ( "bytes" "testing" "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 TestNewCmdConfigSet(t *testing.T) { tests := []struct { name string input string output SetOptions wantsErr bool }{ { name: "no arguments", input: "", output: SetOptions{}, wantsErr: true, }, { name: "no value argument", input: "key", output: SetOptions{}, wantsErr: true, }, { name: "set key value", input: "key value", output: SetOptions{Key: "key", Value: "value"}, wantsErr: false, }, { name: "set key value with host", input: "key value --host test.com", output: SetOptions{Hostname: "test.com", Key: "key", Value: "value"}, wantsErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { _ = config.StubWriteConfig(t) f := &cmdutil.Factory{ Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, } argv, err := shlex.Split(tt.input) assert.NoError(t, err) var gotOpts *SetOptions cmd := NewCmdConfigSet(f, func(opts *SetOptions) error { gotOpts = opts return nil }) cmd.Flags().BoolP("help", "x", false, "") cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) return } assert.NoError(t, err) assert.Equal(t, tt.output.Hostname, gotOpts.Hostname) assert.Equal(t, tt.output.Key, gotOpts.Key) assert.Equal(t, tt.output.Value, gotOpts.Value) }) } } func Test_setRun(t *testing.T) { tests := []struct { name string input *SetOptions expectedValue string stdout string stderr string wantsErr bool errMsg string }{ { name: "set key value", input: &SetOptions{ Config: config.NewBlankConfig(), Key: "editor", Value: "vim", }, expectedValue: "vim", }, { name: "set key value scoped by host", input: &SetOptions{ Config: config.NewBlankConfig(), Hostname: "github.com", Key: "editor", Value: "vim", }, expectedValue: "vim", }, { name: "set unknown key", input: &SetOptions{ Config: config.NewBlankConfig(), Key: "unknownKey", Value: "someValue", }, expectedValue: "someValue", stderr: "! warning: 'unknownKey' is not a known configuration key\n", }, { name: "set invalid value", input: &SetOptions{ Config: config.NewBlankConfig(), Key: "git_protocol", Value: "invalid", }, wantsErr: true, errMsg: "failed to set \"git_protocol\" to \"invalid\": valid values are 'https', 'ssh'", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { _ = config.StubWriteConfig(t) ios, _, stdout, stderr := iostreams.Test() tt.input.IO = ios err := setRun(tt.input) if tt.wantsErr { assert.EqualError(t, err, tt.errMsg) return } assert.NoError(t, err) assert.Equal(t, tt.stdout, stdout.String()) assert.Equal(t, tt.stderr, stderr.String()) optionalEntry := tt.input.Config.GetOrDefault(tt.input.Hostname, tt.input.Key) entry := optionalEntry.Expect("expected a value to be set") assert.Equal(t, tt.expectedValue, entry.Value) assert.Equal(t, gh.ConfigUserProvided, entry.Source) }) } } func Test_ValidateValue(t *testing.T) { err := ValidateValue("git_protocol", "sshpps") assert.EqualError(t, err, "invalid value") err = ValidateValue("git_protocol", "ssh") assert.NoError(t, err) err = ValidateValue("editor", "vim") assert.NoError(t, err) err = ValidateValue("got", "123") assert.NoError(t, err) err = ValidateValue("http_unix_socket", "really_anything/is/allowed/and/net.Dial\\(...\\)/will/ultimately/validate") assert.NoError(t, err) } func Test_ValidateKey(t *testing.T) { err := ValidateKey("invalid") assert.EqualError(t, err, "invalid key") err = ValidateKey("git_protocol") assert.NoError(t, err) err = ValidateKey("editor") assert.NoError(t, err) err = ValidateKey("prompt") assert.NoError(t, err) err = ValidateKey("pager") assert.NoError(t, err) err = ValidateKey("http_unix_socket") assert.NoError(t, err) err = ValidateKey("browser") assert.NoError(t, err) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/config/set/set.go
pkg/cmd/config/set/set.go
package set import ( "errors" "fmt" "strings" "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/spf13/cobra" ) type SetOptions struct { IO *iostreams.IOStreams Config gh.Config Key string Value string Hostname string } func NewCmdConfigSet(f *cmdutil.Factory, runF func(*SetOptions) error) *cobra.Command { opts := &SetOptions{ IO: f.IOStreams, } cmd := &cobra.Command{ Use: "set <key> <value>", Short: "Update configuration with a value for the given key", Example: heredoc.Doc(` $ gh config set editor vim $ gh config set editor "code --wait" $ gh config set git_protocol ssh --host github.com $ gh config set prompt disabled `), Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { config, err := f.Config() if err != nil { return err } opts.Config = config opts.Key = args[0] opts.Value = args[1] if runF != nil { return runF(opts) } return setRun(opts) }, } cmd.Flags().StringVarP(&opts.Hostname, "host", "h", "", "Set per-host setting") return cmd } func setRun(opts *SetOptions) error { err := ValidateKey(opts.Key) if err != nil { warningIcon := opts.IO.ColorScheme().WarningIcon() fmt.Fprintf(opts.IO.ErrOut, "%s warning: '%s' is not a known configuration key\n", warningIcon, opts.Key) } err = ValidateValue(opts.Key, opts.Value) if err != nil { var invalidValue InvalidValueError if errors.As(err, &invalidValue) { var values []string for _, v := range invalidValue.ValidValues { values = append(values, fmt.Sprintf("'%s'", v)) } return fmt.Errorf("failed to set %q to %q: valid values are %v", opts.Key, opts.Value, strings.Join(values, ", ")) } } opts.Config.Set(opts.Hostname, opts.Key, opts.Value) err = opts.Config.Write() if err != nil { return fmt.Errorf("failed to write config to disk: %w", err) } return nil } func ValidateKey(key string) error { for _, configKey := range config.Options { if key == configKey.Key { return nil } } return fmt.Errorf("invalid key") } type InvalidValueError struct { ValidValues []string } func (e InvalidValueError) Error() string { return "invalid value" } func ValidateValue(key, value string) error { var validValues []string for _, v := range config.Options { if v.Key == key { validValues = v.AllowedValues break } } if validValues == nil { return nil } for _, v := range validValues { if v == value { return nil } } return InvalidValueError{ValidValues: validValues} }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/variable/variable.go
pkg/cmd/variable/variable.go
package variable import ( "github.com/MakeNowJust/heredoc" cmdDelete "github.com/cli/cli/v2/pkg/cmd/variable/delete" cmdGet "github.com/cli/cli/v2/pkg/cmd/variable/get" cmdList "github.com/cli/cli/v2/pkg/cmd/variable/list" cmdSet "github.com/cli/cli/v2/pkg/cmd/variable/set" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/spf13/cobra" ) func NewCmdVariable(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "variable <command>", Short: "Manage GitHub Actions variables", Long: heredoc.Docf(` Variables can be set at the repository, environment or organization level for use in GitHub Actions or Dependabot. Run %[1]sgh help variable set%[1]s to learn how to get started. `, "`"), } cmdutil.EnableRepoOverride(cmd, f) cmd.AddCommand(cmdGet.NewCmdGet(f, nil)) cmd.AddCommand(cmdSet.NewCmdSet(f, nil)) cmd.AddCommand(cmdList.NewCmdList(f, nil)) cmd.AddCommand(cmdDelete.NewCmdDelete(f, nil)) return cmd }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/variable/delete/delete.go
pkg/cmd/variable/delete/delete.go
package delete import ( "fmt" "net/http" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/variable/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type DeleteOptions struct { HttpClient func() (*http.Client, error) IO *iostreams.IOStreams Config func() (gh.Config, error) BaseRepo func() (ghrepo.Interface, error) VariableName string OrgName string EnvName string } func NewCmdDelete(f *cmdutil.Factory, runF func(*DeleteOptions) error) *cobra.Command { opts := &DeleteOptions{ IO: f.IOStreams, Config: f.Config, HttpClient: f.HttpClient, } cmd := &cobra.Command{ Use: "delete <variable-name>", Short: "Delete variables", Long: heredoc.Doc(` Delete a variable on one of the following levels: - repository (default): available to GitHub Actions runs or Dependabot in a repository - environment: available to GitHub Actions runs for a deployment environment in a repository - organization: available to GitHub Actions runs or Dependabot within an organization `), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { // support `-R, --repo` override opts.BaseRepo = f.BaseRepo if err := cmdutil.MutuallyExclusive("specify only one of `--org` or `--env`", opts.OrgName != "", opts.EnvName != ""); err != nil { return err } opts.VariableName = args[0] if runF != nil { return runF(opts) } return removeRun(opts) }, Aliases: []string{ "remove", }, } cmd.Flags().StringVarP(&opts.OrgName, "org", "o", "", "Delete a variable for an organization") cmd.Flags().StringVarP(&opts.EnvName, "env", "e", "", "Delete a variable for an environment") return cmd } func removeRun(opts *DeleteOptions) error { c, err := opts.HttpClient() if err != nil { return fmt.Errorf("could not create http client: %w", err) } client := api.NewClientFromHTTP(c) orgName := opts.OrgName envName := opts.EnvName variableEntity, err := shared.GetVariableEntity(orgName, envName) if err != nil { return err } var baseRepo ghrepo.Interface if variableEntity == shared.Repository || variableEntity == shared.Environment { baseRepo, err = opts.BaseRepo() if err != nil { return err } } cfg, err := opts.Config() if err != nil { return err } var path string var host string switch variableEntity { case shared.Organization: path = fmt.Sprintf("orgs/%s/actions/variables/%s", orgName, opts.VariableName) host, _ = cfg.Authentication().DefaultHost() case shared.Environment: path = fmt.Sprintf("repos/%s/environments/%s/variables/%s", ghrepo.FullName(baseRepo), envName, opts.VariableName) host = baseRepo.RepoHost() case shared.Repository: path = fmt.Sprintf("repos/%s/actions/variables/%s", ghrepo.FullName(baseRepo), opts.VariableName) host = baseRepo.RepoHost() } err = client.REST(host, "DELETE", path, nil, nil) if err != nil { return fmt.Errorf("failed to delete variable %s: %w", opts.VariableName, err) } if opts.IO.IsStdoutTTY() { var target string switch variableEntity { case shared.Organization: target = orgName case shared.Repository, shared.Environment: target = ghrepo.FullName(baseRepo) } cs := opts.IO.ColorScheme() if envName != "" { fmt.Fprintf(opts.IO.Out, "%s Deleted variable %s from %s environment on %s\n", cs.SuccessIconWithColor(cs.Red), opts.VariableName, envName, target) } else { fmt.Fprintf(opts.IO.Out, "%s Deleted variable %s from %s\n", cs.SuccessIconWithColor(cs.Red), opts.VariableName, target) } } return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/variable/delete/delete_test.go
pkg/cmd/variable/delete/delete_test.go
package delete import ( "bytes" "net/http" "testing" "github.com/cli/cli/v2/internal/config" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNewCmdDelete(t *testing.T) { tests := []struct { name string cli string wants DeleteOptions wantsErr bool }{ { name: "no args", wantsErr: true, }, { name: "repo", cli: "cool", wants: DeleteOptions{ VariableName: "cool", }, }, { name: "org", cli: "cool --org anOrg", wants: DeleteOptions{ VariableName: "cool", OrgName: "anOrg", }, }, { name: "env", cli: "cool --env anEnv", wants: DeleteOptions{ VariableName: "cool", EnvName: "anEnv", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() f := &cmdutil.Factory{ IOStreams: ios, } argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts *DeleteOptions cmd := NewCmdDelete(f, func(opts *DeleteOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) return } assert.NoError(t, err) assert.Equal(t, tt.wants.VariableName, gotOpts.VariableName) assert.Equal(t, tt.wants.OrgName, gotOpts.OrgName) assert.Equal(t, tt.wants.EnvName, gotOpts.EnvName) }) } } func TestRemoveRun(t *testing.T) { tests := []struct { name string opts *DeleteOptions host string httpStubs func(*httpmock.Registry) }{ { name: "repo", opts: &DeleteOptions{ VariableName: "cool_variable", }, host: "github.com", httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.WithHost(httpmock.REST("DELETE", "repos/owner/repo/actions/variables/cool_variable"), "api.github.com"), httpmock.StatusStringResponse(204, "No Content")) }, }, { name: "repo GHES", opts: &DeleteOptions{ VariableName: "cool_variable", }, host: "example.com", httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.WithHost(httpmock.REST("DELETE", "api/v3/repos/owner/repo/actions/variables/cool_variable"), "example.com"), httpmock.StatusStringResponse(204, "No Content")) }, }, { name: "env", opts: &DeleteOptions{ VariableName: "cool_variable", EnvName: "development", }, host: "github.com", httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.WithHost(httpmock.REST("DELETE", "repos/owner/repo/environments/development/variables/cool_variable"), "api.github.com"), httpmock.StatusStringResponse(204, "No Content")) }, }, { name: "env GHES", opts: &DeleteOptions{ VariableName: "cool_variable", EnvName: "development", }, host: "example.com", httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.WithHost(httpmock.REST("DELETE", "api/v3/repos/owner/repo/environments/development/variables/cool_variable"), "example.com"), httpmock.StatusStringResponse(204, "No Content")) }, }, { name: "org", opts: &DeleteOptions{ VariableName: "cool_variable", OrgName: "UmbrellaCorporation", }, host: "github.com", httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.WithHost(httpmock.REST("DELETE", "orgs/UmbrellaCorporation/actions/variables/cool_variable"), "api.github.com"), httpmock.StatusStringResponse(204, "No Content")) }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { reg := &httpmock.Registry{} tt.httpStubs(reg) defer reg.Verify(t) ios, _, _, _ := iostreams.Test() tt.opts.IO = ios tt.opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } tt.opts.Config = func() (gh.Config, error) { return config.NewBlankConfig(), nil } tt.opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.FromFullNameWithHost("owner/repo", tt.host) } err := removeRun(tt.opts) 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/variable/list/list_test.go
pkg/cmd/variable/list/list_test.go
package list import ( "bytes" "fmt" "net/http" "net/url" "strings" "testing" "time" "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/variable/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNewCmdList(t *testing.T) { tests := []struct { name string cli string wants ListOptions }{ { name: "repo", cli: "", wants: ListOptions{ OrgName: "", }, }, { name: "org", cli: "-oUmbrellaCorporation", wants: ListOptions{ OrgName: "UmbrellaCorporation", }, }, { name: "env", cli: "-eDevelopment", wants: ListOptions{ EnvName: "Development", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() f := &cmdutil.Factory{ IOStreams: ios, } argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts *ListOptions cmd := NewCmdList(f, func(opts *ListOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err = cmd.ExecuteC() assert.NoError(t, err) assert.Equal(t, tt.wants.OrgName, gotOpts.OrgName) assert.Equal(t, tt.wants.EnvName, gotOpts.EnvName) }) } } func Test_listRun(t *testing.T) { tests := []struct { name string tty bool opts *ListOptions jsonFields []string wantOut []string }{ { name: "repo tty", tty: true, opts: &ListOptions{}, wantOut: []string{ "NAME VALUE UPDATED", "VARIABLE_ONE one about 34 years ago", "VARIABLE_TWO two about 2 years ago", "VARIABLE_THREE three about 47 years ago", }, }, { name: "repo not tty", tty: false, opts: &ListOptions{}, wantOut: []string{ "VARIABLE_ONE\tone\t1988-10-11T00:00:00Z", "VARIABLE_TWO\ttwo\t2020-12-04T00:00:00Z", "VARIABLE_THREE\tthree\t1975-11-30T00:00:00Z", }, }, { name: "repo not tty, json", tty: false, opts: &ListOptions{}, jsonFields: []string{"name", "value"}, wantOut: []string{`[ {"name":"VARIABLE_ONE","value":"one"}, {"name":"VARIABLE_TWO","value":"two"}, {"name":"VARIABLE_THREE","value":"three"} ]`}, }, { name: "org tty", tty: true, opts: &ListOptions{ OrgName: "UmbrellaCorporation", }, wantOut: []string{ "NAME VALUE UPDATED VISIBILITY", "VARIABLE_ONE org_one about 34 years ago Visible to all repositories", "VARIABLE_TWO org_two about 2 years ago Visible to private repositories", "VARIABLE_THREE org_three about 47 years ago Visible to 2 selected reposito...", }, }, { name: "org not tty", tty: false, opts: &ListOptions{ OrgName: "UmbrellaCorporation", }, wantOut: []string{ "VARIABLE_ONE\torg_one\t1988-10-11T00:00:00Z\tALL", "VARIABLE_TWO\torg_two\t2020-12-04T00:00:00Z\tPRIVATE", "VARIABLE_THREE\torg_three\t1975-11-30T00:00:00Z\tSELECTED", }, }, { name: "org not tty, json", tty: false, opts: &ListOptions{ OrgName: "UmbrellaCorporation", }, jsonFields: []string{"name", "value"}, wantOut: []string{`[ {"name":"VARIABLE_ONE","value":"org_one"}, {"name":"VARIABLE_TWO","value":"org_two"}, {"name":"VARIABLE_THREE","value":"org_three"} ]`}, }, { name: "env tty", tty: true, opts: &ListOptions{ EnvName: "Development", }, wantOut: []string{ "NAME VALUE UPDATED", "VARIABLE_ONE one about 34 years ago", "VARIABLE_TWO two about 2 years ago", "VARIABLE_THREE three about 47 years ago", }, }, { name: "env not tty", tty: false, opts: &ListOptions{ EnvName: "Development", }, wantOut: []string{ "VARIABLE_ONE\tone\t1988-10-11T00:00:00Z", "VARIABLE_TWO\ttwo\t2020-12-04T00:00:00Z", "VARIABLE_THREE\tthree\t1975-11-30T00:00:00Z", }, }, { name: "env not tty, json", tty: false, opts: &ListOptions{ EnvName: "Development", }, jsonFields: []string{"name", "value"}, wantOut: []string{`[ {"name":"VARIABLE_ONE","value":"one"}, {"name":"VARIABLE_TWO","value":"two"}, {"name":"VARIABLE_THREE","value":"three"} ]`}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { reg := &httpmock.Registry{} defer reg.Verify(t) path := "repos/owner/repo/actions/variables" if tt.opts.EnvName != "" { path = fmt.Sprintf("repos/owner/repo/environments/%s/variables", tt.opts.EnvName) } else if tt.opts.OrgName != "" { path = fmt.Sprintf("orgs/%s/actions/variables", tt.opts.OrgName) } t0, _ := time.Parse("2006-01-02", "1988-10-11") t1, _ := time.Parse("2006-01-02", "2020-12-04") t2, _ := time.Parse("2006-01-02", "1975-11-30") payload := struct { Variables []shared.Variable }{ Variables: []shared.Variable{ { Name: "VARIABLE_ONE", Value: "one", UpdatedAt: t0, }, { Name: "VARIABLE_TWO", Value: "two", UpdatedAt: t1, }, { Name: "VARIABLE_THREE", Value: "three", UpdatedAt: t2, }, }, } if tt.opts.OrgName != "" { payload.Variables = []shared.Variable{ { Name: "VARIABLE_ONE", Value: "org_one", UpdatedAt: t0, Visibility: shared.All, }, { Name: "VARIABLE_TWO", Value: "org_two", UpdatedAt: t1, Visibility: shared.Private, }, { Name: "VARIABLE_THREE", Value: "org_three", UpdatedAt: t2, Visibility: shared.Selected, SelectedReposURL: fmt.Sprintf("https://api.github.com/orgs/%s/actions/variables/VARIABLE_THREE/repositories", tt.opts.OrgName), }, } if tt.tty { reg.Register( httpmock.REST("GET", fmt.Sprintf("orgs/%s/actions/variables/VARIABLE_THREE/repositories", tt.opts.OrgName)), httpmock.JSONResponse(struct { TotalCount int `json:"total_count"` }{2})) } } reg.Register(httpmock.REST("GET", path), httpmock.JSONResponse(payload)) ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(tt.tty) tt.opts.IO = ios tt.opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.FromFullName("owner/repo") } tt.opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } tt.opts.Config = func() (gh.Config, error) { return config.NewBlankConfig(), nil } tt.opts.Now = func() time.Time { t, _ := time.Parse(time.RFC822, "15 Mar 23 00:00 UTC") return t } if tt.jsonFields != nil { jsonExporter := cmdutil.NewJSONExporter() jsonExporter.SetFields(tt.jsonFields) tt.opts.Exporter = jsonExporter } err := listRun(tt.opts) assert.NoError(t, err) expected := fmt.Sprintf("%s\n", strings.Join(tt.wantOut, "\n")) if tt.jsonFields != nil { assert.JSONEq(t, expected, stdout.String()) } else { assert.Equal(t, expected, stdout.String()) } }) } } // Test_listRun_populatesNumSelectedReposIfRequired asserts that NumSelectedRepos // field is populated **only** when it's going to be presented in the output. Since // populating this field costs further API requests (one per variable), it's important // to avoid extra calls when the output will not present the field's value. Note // that NumSelectedRepos is only meant for organization variables. // // We should only populate the NumSelectedRepos field in these cases: // 1. The command is run in the TTY mode without the `--json <fields>` option. // 2. The command is run with `--json <fields>` option, and `numSelectedRepos` // is among the selected fields. In this case, TTY mode is irrelevant. func Test_listRun_populatesNumSelectedReposIfRequired(t *testing.T) { tests := []struct { name string tty bool jsonFields []string wantPopulated bool }{ { name: "org tty", tty: true, wantPopulated: true, }, { name: "org tty, json with numSelectedRepos", tty: true, jsonFields: []string{"numSelectedRepos"}, wantPopulated: true, }, { name: "org tty, json without numSelectedRepos", tty: true, jsonFields: []string{"name"}, wantPopulated: false, }, { name: "org not tty", tty: false, wantPopulated: false, }, { name: "org not tty, json with numSelectedRepos", tty: false, jsonFields: []string{"numSelectedRepos"}, wantPopulated: true, }, { name: "org not tty, json without numSelectedRepos", tty: false, jsonFields: []string{"name"}, wantPopulated: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { reg := &httpmock.Registry{} reg.Verify(t) reg.Register( httpmock.REST("GET", "orgs/umbrellaOrganization/actions/variables"), httpmock.JSONResponse(struct{ Variables []shared.Variable }{ []shared.Variable{ { Name: "VARIABLE", Visibility: shared.Selected, SelectedReposURL: "https://api.github.com/orgs/umbrellaOrganization/actions/variables/VARIABLE/repositories", }, }, })) reg.Register( httpmock.REST("GET", "orgs/umbrellaOrganization/actions/variables/VARIABLE/repositories"), httpmock.JSONResponse(struct { TotalCount int `json:"total_count"` }{999})) opts := &ListOptions{ OrgName: "umbrellaOrganization", } if tt.jsonFields != nil { exporter := cmdutil.NewJSONExporter() exporter.SetFields(tt.jsonFields) opts.Exporter = exporter } ios, _, _, _ := iostreams.Test() ios.SetStdoutTTY(tt.tty) opts.IO = ios opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.FromFullName("owner/repo") } opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } opts.Config = func() (gh.Config, error) { return config.NewBlankConfig(), nil } opts.Now = func() time.Time { t, _ := time.Parse(time.RFC822, "4 Apr 24 00:00 UTC") return t } require.NoError(t, listRun(opts)) if tt.wantPopulated { // There should be 2 requests; one to get the variables list and // another to populate the numSelectedRepos field. assert.Len(t, reg.Requests, 2) } else { // Only one requests to get the variables list. assert.Len(t, reg.Requests, 1) } }) } } func Test_getVariables_pagination(t *testing.T) { reg := &httpmock.Registry{} defer reg.Verify(t) reg.Register( httpmock.QueryMatcher("GET", "path/to", url.Values{"per_page": []string{"100"}}), httpmock.WithHeader( httpmock.StringResponse(`{"variables":[{},{}]}`), "Link", `<http://example.com/page/0>; rel="previous", <http://example.com/page/2>; rel="next"`), ) reg.Register( httpmock.REST("GET", "page/2"), httpmock.StringResponse(`{"variables":[{},{}]}`), ) client := &http.Client{Transport: reg} variables, err := getVariables(client, "github.com", "path/to") assert.NoError(t, err) assert.Equal(t, 4, len(variables)) } func TestExportVariables(t *testing.T) { ios, _, stdout, _ := iostreams.Test() tf, _ := time.Parse(time.RFC3339, "2024-01-01T00:00:00Z") vs := []shared.Variable{{ Name: "v1", Value: "test1", UpdatedAt: tf, CreatedAt: tf, Visibility: shared.All, SelectedReposURL: "https://someurl.com", NumSelectedRepos: 1, }} exporter := cmdutil.NewJSONExporter() exporter.SetFields(shared.VariableJSONFields) require.NoError(t, exporter.Write(ios, vs)) require.JSONEq(t, `[{"name":"v1","numSelectedRepos":1,"selectedReposURL":"https://someurl.com","updatedAt":"2024-01-01T00:00:00Z","createdAt":"2024-01-01T00:00:00Z","value":"test1","visibility":"all"}]`, stdout.String()) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/variable/list/list.go
pkg/cmd/variable/list/list.go
package list import ( "fmt" "net/http" "slices" "strings" "time" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/tableprinter" "github.com/cli/cli/v2/pkg/cmd/variable/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type ListOptions struct { HttpClient func() (*http.Client, error) IO *iostreams.IOStreams Config func() (gh.Config, error) BaseRepo func() (ghrepo.Interface, error) Now func() time.Time Exporter cmdutil.Exporter OrgName string EnvName string } const fieldNumSelectedRepos = "numSelectedRepos" func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Command { opts := &ListOptions{ IO: f.IOStreams, Config: f.Config, HttpClient: f.HttpClient, Now: time.Now, } cmd := &cobra.Command{ Use: "list", Short: "List variables", Long: heredoc.Doc(` List variables on one of the following levels: - repository (default): available to GitHub Actions runs or Dependabot in a repository - environment: available to GitHub Actions runs for a deployment environment in a repository - organization: available to GitHub Actions runs or Dependabot within an organization `), Aliases: []string{"ls"}, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { // support `-R, --repo` override opts.BaseRepo = f.BaseRepo if err := cmdutil.MutuallyExclusive("specify only one of `--org` or `--env`", opts.OrgName != "", opts.EnvName != ""); err != nil { return err } if runF != nil { return runF(opts) } return listRun(opts) }, } cmd.Flags().StringVarP(&opts.OrgName, "org", "o", "", "List variables for an organization") cmd.Flags().StringVarP(&opts.EnvName, "env", "e", "", "List variables for an environment") cmdutil.AddJSONFlags(cmd, &opts.Exporter, shared.VariableJSONFields) return cmd } func listRun(opts *ListOptions) error { client, err := opts.HttpClient() if err != nil { return fmt.Errorf("could not create http client: %w", err) } orgName := opts.OrgName envName := opts.EnvName var baseRepo ghrepo.Interface if orgName == "" { baseRepo, err = opts.BaseRepo() if err != nil { return err } } variableEntity, err := shared.GetVariableEntity(orgName, envName) if err != nil { return err } // Since populating the `NumSelectedRepos` field costs further API requests // (one per secret), it's important to avoid extra calls when the output will // not present the field's value. So, we should only populate this field in // these cases: // 1. The command is run in the TTY mode without the `--json <fields>` option. // 2. The command is run with `--json <fields>` option, and `numSelectedRepos` // is among the selected fields. In this case, TTY mode is irrelevant. showSelectedRepoInfo := opts.IO.IsStdoutTTY() if opts.Exporter != nil { // Note that if there's an exporter set, then we don't mind the TTY mode // because we just have to populate the requested fields. showSelectedRepoInfo = slices.Contains(opts.Exporter.Fields(), fieldNumSelectedRepos) } var variables []shared.Variable switch variableEntity { case shared.Repository: variables, err = getRepoVariables(client, baseRepo) case shared.Environment: variables, err = getEnvVariables(client, baseRepo, envName) case shared.Organization: var cfg gh.Config var host string cfg, err = opts.Config() if err != nil { return err } host, _ = cfg.Authentication().DefaultHost() variables, err = getOrgVariables(client, host, orgName, showSelectedRepoInfo) } if err != nil { return fmt.Errorf("failed to get variables: %w", err) } if len(variables) == 0 && opts.Exporter == nil { return cmdutil.NewNoResultsError("no variables found") } if err := opts.IO.StartPager(); err == nil { defer opts.IO.StopPager() } else { fmt.Fprintf(opts.IO.ErrOut, "failed to start pager: %v\n", err) } if opts.Exporter != nil { return opts.Exporter.Write(opts.IO, variables) } var headers []string if variableEntity == shared.Organization { headers = []string{"Name", "Value", "Updated", "Visibility"} } else { headers = []string{"Name", "Value", "Updated"} } table := tableprinter.New(opts.IO, tableprinter.WithHeader(headers...)) for _, variable := range variables { table.AddField(variable.Name) table.AddField(variable.Value) table.AddTimeField(opts.Now(), variable.UpdatedAt, nil) if variable.Visibility != "" { if showSelectedRepoInfo { table.AddField(fmtVisibility(variable)) } else { table.AddField(strings.ToUpper(string(variable.Visibility))) } } table.EndRow() } err = table.Render() if err != nil { return err } return nil } func fmtVisibility(s shared.Variable) string { switch s.Visibility { case shared.All: return "Visible to all repositories" case shared.Private: return "Visible to private repositories" case shared.Selected: if s.NumSelectedRepos == 1 { return "Visible to 1 selected repository" } else { return fmt.Sprintf("Visible to %d selected repositories", s.NumSelectedRepos) } } return "" } func getRepoVariables(client *http.Client, repo ghrepo.Interface) ([]shared.Variable, error) { return getVariables(client, repo.RepoHost(), fmt.Sprintf("repos/%s/actions/variables", ghrepo.FullName(repo))) } func getEnvVariables(client *http.Client, repo ghrepo.Interface, envName string) ([]shared.Variable, error) { path := fmt.Sprintf("repos/%s/environments/%s/variables", ghrepo.FullName(repo), envName) return getVariables(client, repo.RepoHost(), path) } func getOrgVariables(client *http.Client, host, orgName string, showSelectedRepoInfo bool) ([]shared.Variable, error) { variables, err := getVariables(client, host, fmt.Sprintf("orgs/%s/actions/variables", orgName)) if err != nil { return nil, err } apiClient := api.NewClientFromHTTP(client) if showSelectedRepoInfo { err = shared.PopulateMultipleSelectedRepositoryInformation(apiClient, host, variables) if err != nil { return nil, err } } return variables, nil } func getVariables(client *http.Client, host, path string) ([]shared.Variable, error) { var results []shared.Variable apiClient := api.NewClientFromHTTP(client) path = fmt.Sprintf("%s?per_page=100", path) for path != "" { response := struct { Variables []shared.Variable }{} var err error path, err = apiClient.RESTWithNext(host, "GET", path, nil, &response) if err != nil { return nil, err } results = append(results, response.Variables...) } return results, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/variable/get/get_test.go
pkg/cmd/variable/get/get_test.go
package get import ( "bytes" "fmt" "net/http" "testing" "time" "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/variable/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNewCmdGet(t *testing.T) { tests := []struct { name string cli string wants GetOptions wantErr error }{ { name: "repo", cli: "FOO", wants: GetOptions{ OrgName: "", VariableName: "FOO", }, }, { name: "org", cli: "-o TestOrg BAR", wants: GetOptions{ OrgName: "TestOrg", VariableName: "BAR", }, }, { name: "env", cli: "-e Development BAZ", wants: GetOptions{ EnvName: "Development", VariableName: "BAZ", }, }, { name: "org and env", cli: "-o TestOrg -e Development QUX", wantErr: cmdutil.FlagErrorf("%s", "specify only one of `--org` or `--env`"), }, { name: "json", cli: "--json name,value FOO", wants: GetOptions{ VariableName: "FOO", Exporter: func() cmdutil.Exporter { exporter := cmdutil.NewJSONExporter() exporter.SetFields([]string{"name", "value"}) return exporter }(), }, }, } 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 *GetOptions cmd := NewCmdGet(f, func(opts *GetOptions) 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 != nil { require.Equal(t, err, tt.wantErr) return } require.NoError(t, err) require.Equal(t, tt.wants.OrgName, gotOpts.OrgName) require.Equal(t, tt.wants.EnvName, gotOpts.EnvName) require.Equal(t, tt.wants.VariableName, gotOpts.VariableName) require.Equal(t, tt.wants.Exporter, gotOpts.Exporter) }) } } func Test_getRun(t *testing.T) { tf, _ := time.Parse(time.RFC3339, "2024-01-01T00:00:00Z") tests := []struct { name string opts *GetOptions host string httpStubs func(*httpmock.Registry) jsonFields []string wantOut string wantErr error }{ { name: "getting repo variable", opts: &GetOptions{ VariableName: "VARIABLE_ONE", }, host: "github.com", httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.WithHost(httpmock.REST("GET", "repos/owner/repo/actions/variables/VARIABLE_ONE"), "api.github.com"), httpmock.JSONResponse(shared.Variable{ Value: "repo_var", })) }, wantOut: "repo_var\n", }, { name: "getting GHES repo variable", opts: &GetOptions{ VariableName: "VARIABLE_ONE", }, host: "example.com", httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.WithHost(httpmock.REST("GET", "api/v3/repos/owner/repo/actions/variables/VARIABLE_ONE"), "example.com"), httpmock.JSONResponse(shared.Variable{ Value: "repo_var", })) }, wantOut: "repo_var\n", }, { name: "getting org variable", opts: &GetOptions{ OrgName: "TestOrg", VariableName: "VARIABLE_ONE", }, host: "github.com", httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("GET", "orgs/TestOrg/actions/variables/VARIABLE_ONE"), httpmock.JSONResponse(shared.Variable{ Value: "org_var", })) }, wantOut: "org_var\n", }, { name: "getting env variable", opts: &GetOptions{ EnvName: "Development", VariableName: "VARIABLE_ONE", }, host: "github.com", httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.WithHost(httpmock.REST("GET", "repos/owner/repo/environments/Development/variables/VARIABLE_ONE"), "api.github.com"), httpmock.JSONResponse(shared.Variable{ Value: "env_var", })) }, wantOut: "env_var\n", }, { name: "getting GHES env variable", opts: &GetOptions{ EnvName: "Development", VariableName: "VARIABLE_ONE", }, host: "example.com", httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.WithHost(httpmock.REST("GET", "api/v3/repos/owner/repo/environments/Development/variables/VARIABLE_ONE"), "example.com"), httpmock.JSONResponse(shared.Variable{ Value: "env_var", })) }, wantOut: "env_var\n", }, { name: "json", opts: &GetOptions{ VariableName: "VARIABLE_ONE", }, host: "github.com", jsonFields: []string{"name", "value", "visibility", "updatedAt", "createdAt", "numSelectedRepos", "selectedReposURL"}, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("GET", "repos/owner/repo/actions/variables/VARIABLE_ONE"), httpmock.JSONResponse(shared.Variable{ Name: "VARIABLE_ONE", Value: "repo_var", UpdatedAt: tf, CreatedAt: tf, Visibility: shared.Organization, SelectedReposURL: "path/to/fetch/selected/repos", NumSelectedRepos: 0, // This should be populated in a second API call. })) reg.Register(httpmock.REST("GET", "path/to/fetch/selected/repos"), httpmock.JSONResponse(map[string]interface{}{ "total_count": 99, })) }, wantOut: `{ "name": "VARIABLE_ONE", "value": "repo_var", "updatedAt": "2024-01-01T00:00:00Z", "createdAt": "2024-01-01T00:00:00Z", "visibility": "organization", "selectedReposURL": "path/to/fetch/selected/repos", "numSelectedRepos": 99 }`, }, { name: "when the variable is not found, an error is returned", opts: &GetOptions{ VariableName: "VARIABLE_ONE", }, host: "github.com", httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("GET", "repos/owner/repo/actions/variables/VARIABLE_ONE"), httpmock.StatusStringResponse(404, "not found"), ) }, wantErr: fmt.Errorf("variable VARIABLE_ONE was not found"), }, { name: "when getting any variable from API fails, the error is bubbled with context", opts: &GetOptions{ VariableName: "VARIABLE_ONE", }, host: "github.com", httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("GET", "repos/owner/repo/actions/variables/VARIABLE_ONE"), httpmock.StatusStringResponse(400, "not found"), ) }, wantErr: fmt.Errorf("failed to get variable VARIABLE_ONE: HTTP 400 (https://api.github.com/repos/owner/repo/actions/variables/VARIABLE_ONE)"), }, } for _, tt := range tests { var runTest = func(tty bool) func(t *testing.T) { return func(t *testing.T) { reg := &httpmock.Registry{} tt.httpStubs(reg) defer reg.Verify(t) ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(tty) tt.opts.IO = ios tt.opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.FromFullNameWithHost("owner/repo", tt.host) } tt.opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } tt.opts.Config = func() (gh.Config, error) { return config.NewBlankConfig(), nil } if tt.jsonFields != nil { exporter := cmdutil.NewJSONExporter() exporter.SetFields(tt.jsonFields) tt.opts.Exporter = exporter } err := getRun(tt.opts) if err != nil { require.EqualError(t, tt.wantErr, err.Error()) return } require.NoError(t, err) if tt.jsonFields != nil { require.JSONEq(t, tt.wantOut, stdout.String()) } else { require.Equal(t, tt.wantOut, stdout.String()) } } } t.Run(tt.name+" tty", runTest(true)) t.Run(tt.name+" no-tty", runTest(false)) } } func TestExportVariables(t *testing.T) { ios, _, stdout, _ := iostreams.Test() tf, _ := time.Parse(time.RFC3339, "2024-01-01T00:00:00Z") vs := &shared.Variable{ Name: "v1", Value: "test1", UpdatedAt: tf, CreatedAt: tf, Visibility: shared.All, SelectedReposURL: "https://someurl.com", NumSelectedRepos: 1, } exporter := cmdutil.NewJSONExporter() exporter.SetFields(shared.VariableJSONFields) require.NoError(t, exporter.Write(ios, vs)) require.JSONEq(t, `{"name":"v1","numSelectedRepos":1,"selectedReposURL":"https://someurl.com","updatedAt":"2024-01-01T00:00:00Z","createdAt":"2024-01-01T00:00:00Z","value":"test1","visibility":"all"}`, stdout.String()) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/variable/get/get.go
pkg/cmd/variable/get/get.go
package get import ( "errors" "fmt" "net/http" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/variable/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type GetOptions struct { HttpClient func() (*http.Client, error) IO *iostreams.IOStreams Config func() (gh.Config, error) BaseRepo func() (ghrepo.Interface, error) Exporter cmdutil.Exporter VariableName string OrgName string EnvName string } func NewCmdGet(f *cmdutil.Factory, runF func(*GetOptions) error) *cobra.Command { opts := &GetOptions{ IO: f.IOStreams, Config: f.Config, HttpClient: f.HttpClient, } cmd := &cobra.Command{ Use: "get <variable-name>", Short: "Get variables", Long: heredoc.Doc(` Get a variable on one of the following levels: - repository (default): available to GitHub Actions runs or Dependabot in a repository - environment: available to GitHub Actions runs for a deployment environment in a repository - organization: available to GitHub Actions runs or Dependabot within an organization `), Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { // support `-R, --repo` override opts.BaseRepo = f.BaseRepo if err := cmdutil.MutuallyExclusive("specify only one of `--org` or `--env`", opts.OrgName != "", opts.EnvName != ""); err != nil { return err } opts.VariableName = args[0] if runF != nil { return runF(opts) } return getRun(opts) }, } cmd.Flags().StringVarP(&opts.OrgName, "org", "o", "", "Get a variable for an organization") cmd.Flags().StringVarP(&opts.EnvName, "env", "e", "", "Get a variable for an environment") cmdutil.AddJSONFlags(cmd, &opts.Exporter, shared.VariableJSONFields) return cmd } func getRun(opts *GetOptions) error { c, err := opts.HttpClient() if err != nil { return fmt.Errorf("could not create http client: %w", err) } client := api.NewClientFromHTTP(c) orgName := opts.OrgName envName := opts.EnvName variableEntity, err := shared.GetVariableEntity(orgName, envName) if err != nil { return err } var baseRepo ghrepo.Interface if variableEntity == shared.Repository || variableEntity == shared.Environment { baseRepo, err = opts.BaseRepo() if err != nil { return err } } cfg, err := opts.Config() if err != nil { return err } var path string var host string switch variableEntity { case shared.Organization: path = fmt.Sprintf("orgs/%s/actions/variables/%s", orgName, opts.VariableName) host, _ = cfg.Authentication().DefaultHost() case shared.Environment: path = fmt.Sprintf("repos/%s/environments/%s/variables/%s", ghrepo.FullName(baseRepo), envName, opts.VariableName) host = baseRepo.RepoHost() case shared.Repository: path = fmt.Sprintf("repos/%s/actions/variables/%s", ghrepo.FullName(baseRepo), opts.VariableName) host = baseRepo.RepoHost() } var variable shared.Variable if err = client.REST(host, "GET", path, nil, &variable); err != nil { var httpErr api.HTTPError if errors.As(err, &httpErr) && httpErr.StatusCode == http.StatusNotFound { return fmt.Errorf("variable %s was not found", opts.VariableName) } return fmt.Errorf("failed to get variable %s: %w", opts.VariableName, err) } if opts.Exporter != nil { if err := shared.PopulateSelectedRepositoryInformation(client, host, &variable); err != nil { return err } return opts.Exporter.Write(opts.IO, &variable) } fmt.Fprintf(opts.IO.Out, "%s\n", variable.Value) return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/variable/shared/shared_test.go
pkg/cmd/variable/shared/shared_test.go
package shared import ( "testing" "github.com/stretchr/testify/assert" ) func TestGetVariableEntity(t *testing.T) { tests := []struct { name string orgName string envName string want VariableEntity wantErr bool }{ { name: "org", orgName: "myOrg", want: Organization, }, { name: "env", envName: "myEnv", want: Environment, }, { name: "defaults to repo", want: Repository, }, { name: "errors when both org and env are set", orgName: "myOrg", envName: "myEnv", wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { entity, err := GetVariableEntity(tt.orgName, tt.envName) if tt.wantErr { assert.Error(t, err) } else { assert.NoError(t, err) assert.Equal(t, tt.want, entity) } }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/variable/shared/shared.go
pkg/cmd/variable/shared/shared.go
package shared import ( "errors" "fmt" "time" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/pkg/cmdutil" ) type Visibility string const ( All = "all" Private = "private" Selected = "selected" ) type VariableEntity string const ( Repository = "repository" Organization = "organization" Environment = "environment" ) type Variable struct { Name string `json:"name"` Value string `json:"value"` UpdatedAt time.Time `json:"updated_at"` CreatedAt time.Time `json:"created_at"` Visibility Visibility `json:"visibility"` SelectedReposURL string `json:"selected_repositories_url"` NumSelectedRepos int `json:"num_selected_repos"` } var VariableJSONFields = []string{ "name", "value", "visibility", "updatedAt", "createdAt", "numSelectedRepos", "selectedReposURL", } func (v *Variable) ExportData(fields []string) map[string]interface{} { return cmdutil.StructExportData(v, fields) } func GetVariableEntity(orgName, envName string) (VariableEntity, error) { orgSet := orgName != "" envSet := envName != "" if orgSet && envSet { return "", errors.New("cannot specify multiple variable entities") } if orgSet { return Organization, nil } if envSet { return Environment, nil } return Repository, nil } func PopulateMultipleSelectedRepositoryInformation(apiClient *api.Client, host string, variables []Variable) error { for i, variable := range variables { if err := PopulateSelectedRepositoryInformation(apiClient, host, &variable); err != nil { return err } variables[i] = variable } return nil } func PopulateSelectedRepositoryInformation(apiClient *api.Client, host string, variable *Variable) error { if variable.SelectedReposURL == "" { return nil } response := struct { TotalCount int `json:"total_count"` }{} if err := apiClient.REST(host, "GET", variable.SelectedReposURL, nil, &response); err != nil { return fmt.Errorf("failed determining selected repositories for %s: %w", variable.Name, err) } variable.NumSelectedRepos = response.TotalCount return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/variable/set/set_test.go
pkg/cmd/variable/set/set_test.go
package set import ( "bytes" "encoding/json" "io" "net/http" "os" "testing" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/config" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/pkg/cmd/variable/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" ) func TestNewCmdSet(t *testing.T) { tests := []struct { name string cli string wants SetOptions stdinTTY bool wantsErr bool }{ { name: "invalid visibility type", cli: "cool_variable --org coolOrg -v'mistyVeil'", wantsErr: true, }, { name: "selected visibility with no repos selected", cli: "cool_variable --org coolOrg -v'selected'", wantsErr: true, }, { name: "private visibility with repos selected", cli: "cool_variable --org coolOrg -v'private' -rcoolRepo", wantsErr: true, }, { name: "no name specified", cli: "", wantsErr: true, }, { name: "multiple names specified", cli: "cool_variable good_variable", wantsErr: true, }, { name: "visibility without org", cli: "cool_variable -vall", wantsErr: true, }, { name: "repos without explicit visibility", cli: "cool_variable -bs --org coolOrg -rcoolRepo", wants: SetOptions{ VariableName: "cool_variable", Visibility: shared.Selected, RepositoryNames: []string{"coolRepo"}, Body: "s", OrgName: "coolOrg", }, }, { name: "org with explicit visibility and selected repo", cli: "-ocoolOrg -bs -vselected -rcoolRepo cool_variable", wants: SetOptions{ VariableName: "cool_variable", Visibility: shared.Selected, RepositoryNames: []string{"coolRepo"}, Body: "s", OrgName: "coolOrg", }, }, { name: "org with explicit visibility and selected repos", cli: `--org=coolOrg -bs -vselected -r="coolRepo,radRepo,goodRepo" cool_variable`, wants: SetOptions{ VariableName: "cool_variable", Visibility: shared.Selected, RepositoryNames: []string{"coolRepo", "goodRepo", "radRepo"}, Body: "s", OrgName: "coolOrg", }, }, { name: "repo", cli: `cool_variable -b"a variable"`, wants: SetOptions{ VariableName: "cool_variable", Visibility: shared.Private, Body: "a variable", OrgName: "", }, }, { name: "env", cli: `cool_variable -b"a variable" -eRelease`, wants: SetOptions{ VariableName: "cool_variable", Visibility: shared.Private, Body: "a variable", OrgName: "", EnvName: "Release", }, }, { name: "visibility all", cli: `cool_variable --org coolOrg -b"cool" -vall`, wants: SetOptions{ VariableName: "cool_variable", Visibility: shared.All, Body: "cool", OrgName: "coolOrg", }, }, { name: "env file", cli: `--env-file test.env`, wants: SetOptions{ Visibility: shared.Private, EnvFile: "test.env", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() f := &cmdutil.Factory{ IOStreams: ios, } ios.SetStdinTTY(tt.stdinTTY) argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts *SetOptions cmd := NewCmdSet(f, func(opts *SetOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) return } assert.NoError(t, err) assert.Equal(t, tt.wants.VariableName, gotOpts.VariableName) assert.Equal(t, tt.wants.Body, gotOpts.Body) assert.Equal(t, tt.wants.Visibility, gotOpts.Visibility) assert.Equal(t, tt.wants.OrgName, gotOpts.OrgName) assert.Equal(t, tt.wants.EnvName, gotOpts.EnvName) assert.Equal(t, tt.wants.EnvFile, gotOpts.EnvFile) assert.ElementsMatch(t, tt.wants.RepositoryNames, gotOpts.RepositoryNames) }) } } func Test_setRun_repo(t *testing.T) { tests := []struct { name string httpStubs func(*httpmock.Registry) wantErr bool }{ { name: "create actions variable", httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("POST", "repos/owner/repo/actions/variables"), httpmock.StatusStringResponse(201, `{}`)) }, }, { name: "update actions variable", httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("POST", "repos/owner/repo/actions/variables"), httpmock.StatusStringResponse(409, `{}`)) reg.Register(httpmock.REST("PATCH", "repos/owner/repo/actions/variables/cool_variable"), httpmock.StatusStringResponse(204, `{}`)) }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { reg := &httpmock.Registry{} defer reg.Verify(t) if tt.httpStubs != nil { tt.httpStubs(reg) } ios, _, _, _ := iostreams.Test() opts := &SetOptions{ HttpClient: func() (*http.Client, error) { return &http.Client{Transport: reg}, nil }, Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.FromFullName("owner/repo") }, IO: ios, VariableName: "cool_variable", Body: "a variable", } err := setRun(opts) if tt.wantErr { assert.Error(t, err) return } else { assert.NoError(t, err) } data, err := io.ReadAll(reg.Requests[len(reg.Requests)-1].Body) assert.NoError(t, err) var payload setPayload err = json.Unmarshal(data, &payload) assert.NoError(t, err) assert.Equal(t, payload.Value, "a variable") }) } } func Test_setRun_env(t *testing.T) { tests := []struct { name string opts *SetOptions httpStubs func(*httpmock.Registry) wantErr bool }{ { name: "create env variable", opts: &SetOptions{}, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.GraphQL(`query MapRepositoryNames\b`), httpmock.StringResponse(`{"data":{"repo_0001":{"databaseId":1}}}`)) reg.Register(httpmock.REST("POST", "repositories/1/environments/release/variables"), httpmock.StatusStringResponse(201, `{}`)) }, }, { name: "update env variable", opts: &SetOptions{}, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.GraphQL(`query MapRepositoryNames\b`), httpmock.StringResponse(`{"data":{"repo_0001":{"databaseId":1}}}`)) reg.Register(httpmock.REST("POST", "repositories/1/environments/release/variables"), httpmock.StatusStringResponse(409, `{}`)) reg.Register(httpmock.REST("PATCH", "repositories/1/environments/release/variables/cool_variable"), httpmock.StatusStringResponse(204, `{}`)) }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { reg := &httpmock.Registry{} defer reg.Verify(t) if tt.httpStubs != nil { tt.httpStubs(reg) } ios, _, _, _ := iostreams.Test() opts := &SetOptions{ HttpClient: func() (*http.Client, error) { return &http.Client{Transport: reg}, nil }, Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, BaseRepo: func() (ghrepo.Interface, error) { return ghrepo.FromFullName("owner/repo") }, IO: ios, VariableName: "cool_variable", Body: "a variable", EnvName: "release", } err := setRun(opts) if tt.wantErr { assert.Error(t, err) return } else { assert.NoError(t, err) } data, err := io.ReadAll(reg.Requests[len(reg.Requests)-1].Body) assert.NoError(t, err) var payload setPayload err = json.Unmarshal(data, &payload) assert.NoError(t, err) assert.Equal(t, payload.Value, "a variable") }) } } func Test_setRun_org(t *testing.T) { tests := []struct { name string opts *SetOptions httpStubs func(*httpmock.Registry) wantVisibility shared.Visibility wantRepositories []int64 }{ { name: "create org variable", opts: &SetOptions{ OrgName: "UmbrellaCorporation", Visibility: shared.All, }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("POST", "orgs/UmbrellaCorporation/actions/variables"), httpmock.StatusStringResponse(201, `{}`)) }, }, { name: "update org variable", opts: &SetOptions{ OrgName: "UmbrellaCorporation", Visibility: shared.All, }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("POST", "orgs/UmbrellaCorporation/actions/variables"), httpmock.StatusStringResponse(409, `{}`)) reg.Register(httpmock.REST("PATCH", "orgs/UmbrellaCorporation/actions/variables/cool_variable"), httpmock.StatusStringResponse(204, `{}`)) }, }, { name: "create org variable with selected visibility", opts: &SetOptions{ OrgName: "UmbrellaCorporation", Visibility: shared.Selected, RepositoryNames: []string{"birkin", "UmbrellaCorporation/wesker"}, }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.GraphQL(`query MapRepositoryNames\b`), httpmock.StringResponse(`{"data":{"repo_0001":{"databaseId":1},"repo_0002":{"databaseId":2}}}`)) reg.Register(httpmock.REST("POST", "orgs/UmbrellaCorporation/actions/variables"), httpmock.StatusStringResponse(201, `{}`)) }, wantRepositories: []int64{1, 2}, }, { name: "update org variable with selected visibility", opts: &SetOptions{ OrgName: "UmbrellaCorporation", Visibility: shared.Selected, RepositoryNames: []string{"birkin", "UmbrellaCorporation/wesker"}, }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.GraphQL(`query MapRepositoryNames\b`), httpmock.StringResponse(`{"data":{"repo_0001":{"databaseId":1},"repo_0002":{"databaseId":2}}}`)) reg.Register(httpmock.REST("POST", "orgs/UmbrellaCorporation/actions/variables"), httpmock.StatusStringResponse(409, `{}`)) reg.Register(httpmock.REST("PATCH", "orgs/UmbrellaCorporation/actions/variables/cool_variable"), httpmock.StatusStringResponse(204, `{}`)) }, wantRepositories: []int64{1, 2}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { reg := &httpmock.Registry{} defer reg.Verify(t) if tt.httpStubs != nil { tt.httpStubs(reg) } ios, _, _, _ := iostreams.Test() tt.opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.FromFullName("owner/repo") } tt.opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } tt.opts.Config = func() (gh.Config, error) { return config.NewBlankConfig(), nil } tt.opts.IO = ios tt.opts.VariableName = "cool_variable" tt.opts.Body = "a variable" err := setRun(tt.opts) assert.NoError(t, err) data, err := io.ReadAll(reg.Requests[len(reg.Requests)-1].Body) assert.NoError(t, err) var payload setPayload err = json.Unmarshal(data, &payload) assert.NoError(t, err) assert.Equal(t, payload.Value, "a variable") assert.Equal(t, payload.Visibility, tt.opts.Visibility) assert.ElementsMatch(t, payload.Repositories, tt.wantRepositories) }) } } func Test_getBody_prompt(t *testing.T) { ios, _, _, _ := iostreams.Test() ios.SetStdinTTY(true) ios.SetStdoutTTY(true) prompterMock := &prompter.PrompterMock{} prompterMock.InputFunc = func(message, defaultValue string) (string, error) { return "a variable", nil } opts := &SetOptions{ IO: ios, Prompter: prompterMock, } body, err := getBody(opts) assert.NoError(t, err) assert.Equal(t, "a variable", body) } func Test_getBody(t *testing.T) { tests := []struct { name string bodyArg string want string stdin string }{ { name: "literal value", bodyArg: "a variable", want: "a variable", }, { name: "from stdin", want: "a variable", stdin: "a variable", }, { name: "from stdin with trailing newline character", want: "a variable", stdin: "a variable\n", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, stdin, _, _ := iostreams.Test() ios.SetStdinTTY(false) _, err := stdin.WriteString(tt.stdin) assert.NoError(t, err) opts := &SetOptions{ IO: ios, Body: tt.bodyArg, } body, err := getBody(opts) assert.NoError(t, err) assert.Equal(t, tt.want, body) }) } } func Test_getVariablesFromOptions(t *testing.T) { genFile := func(s string) string { f, err := os.CreateTemp("", "gh-env.*") if err != nil { t.Fatal(err) return "" } defer f.Close() t.Cleanup(func() { _ = os.Remove(f.Name()) }) _, err = f.WriteString(s) if err != nil { t.Fatal(err) } return f.Name() } tests := []struct { name string opts SetOptions isTTY bool stdin string want map[string]string wantErr bool }{ { name: "variable from arg", opts: SetOptions{ VariableName: "FOO", Body: "bar", }, want: map[string]string{"FOO": "bar"}, }, { name: "variable from stdin", opts: SetOptions{ Body: "", EnvFile: "-", }, stdin: `FOO=bar`, want: map[string]string{"FOO": "bar"}, }, { name: "variables from file", opts: SetOptions{ Body: "", EnvFile: genFile(heredoc.Doc(` FOO=bar QUOTED="my value" #IGNORED=true export SHELL=bash `)), }, stdin: `FOO=bar`, want: map[string]string{ "FOO": "bar", "SHELL": "bash", "QUOTED": "my value", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, stdin, _, _ := iostreams.Test() ios.SetStdinTTY(tt.isTTY) ios.SetStdoutTTY(tt.isTTY) stdin.WriteString(tt.stdin) opts := tt.opts opts.IO = ios gotVariables, err := getVariablesFromOptions(&opts) if tt.wantErr { assert.Error(t, err) } else { assert.NoError(t, err) } assert.Equal(t, len(tt.want), len(gotVariables)) for k, v := range gotVariables { assert.Equal(t, tt.want[k], v) } }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/variable/set/http.go
pkg/cmd/variable/set/http.go
package set import ( "bytes" "encoding/json" "errors" "fmt" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/variable/shared" ) const ( createdOperation = "Created" updatedOperation = "Updated" ) type setPayload struct { Name string `json:"name,omitempty"` Repositories []int64 `json:"selected_repository_ids,omitempty"` Value string `json:"value,omitempty"` Visibility string `json:"visibility,omitempty"` } type setOptions struct { Entity shared.VariableEntity Environment string Key string Organization string Repository ghrepo.Interface RepositoryIDs []int64 Value string Visibility string } type setResult struct { Err error Key string Operation string } func setVariable(client *api.Client, host string, opts setOptions) setResult { var err error var postErr api.HTTPError result := setResult{Operation: createdOperation, Key: opts.Key} switch opts.Entity { case shared.Organization: if err = postOrgVariable(client, host, opts.Organization, opts.Visibility, opts.Key, opts.Value, opts.RepositoryIDs); err == nil { return result } else if errors.As(err, &postErr) && postErr.StatusCode == 409 { // Server will return a 409 if variable already exists result.Operation = updatedOperation err = patchOrgVariable(client, host, opts.Organization, opts.Visibility, opts.Key, opts.Value, opts.RepositoryIDs) } case shared.Environment: var ids []int64 ids, err = api.GetRepoIDs(client, opts.Repository.RepoHost(), []ghrepo.Interface{opts.Repository}) if err != nil || len(ids) != 1 { err = fmt.Errorf("failed to look up repository %s: %w", ghrepo.FullName(opts.Repository), err) break } if err = postEnvVariable(client, opts.Repository.RepoHost(), ids[0], opts.Environment, opts.Key, opts.Value); err == nil { return result } else if errors.As(err, &postErr) && postErr.StatusCode == 409 { // Server will return a 409 if variable already exists result.Operation = updatedOperation err = patchEnvVariable(client, opts.Repository.RepoHost(), ids[0], opts.Environment, opts.Key, opts.Value) } default: if err = postRepoVariable(client, opts.Repository, opts.Key, opts.Value); err == nil { return result } else if errors.As(err, &postErr) && postErr.StatusCode == 409 { // Server will return a 409 if variable already exists result.Operation = updatedOperation err = patchRepoVariable(client, opts.Repository, opts.Key, opts.Value) } } if err != nil { result.Err = fmt.Errorf("failed to set variable %q: %w", opts.Key, err) } return result } func postVariable(client *api.Client, host, path string, payload interface{}) error { payloadBytes, err := json.Marshal(payload) if err != nil { return fmt.Errorf("failed to serialize: %w", err) } requestBody := bytes.NewReader(payloadBytes) return client.REST(host, "POST", path, requestBody, nil) } func postOrgVariable(client *api.Client, host, orgName, visibility, variableName, value string, repositoryIDs []int64) error { payload := setPayload{ Name: variableName, Value: value, Visibility: visibility, Repositories: repositoryIDs, } path := fmt.Sprintf(`orgs/%s/actions/variables`, orgName) return postVariable(client, host, path, payload) } func postEnvVariable(client *api.Client, host string, repoID int64, envName, variableName, value string) error { payload := setPayload{ Name: variableName, Value: value, } path := fmt.Sprintf(`repositories/%d/environments/%s/variables`, repoID, envName) return postVariable(client, host, path, payload) } func postRepoVariable(client *api.Client, repo ghrepo.Interface, variableName, value string) error { payload := setPayload{ Name: variableName, Value: value, } path := fmt.Sprintf(`repos/%s/actions/variables`, ghrepo.FullName(repo)) return postVariable(client, repo.RepoHost(), path, payload) } func patchVariable(client *api.Client, host, path string, payload interface{}) error { payloadBytes, err := json.Marshal(payload) if err != nil { return fmt.Errorf("failed to serialize: %w", err) } requestBody := bytes.NewReader(payloadBytes) return client.REST(host, "PATCH", path, requestBody, nil) } func patchOrgVariable(client *api.Client, host, orgName, visibility, variableName, value string, repositoryIDs []int64) error { payload := setPayload{ Value: value, Visibility: visibility, Repositories: repositoryIDs, } path := fmt.Sprintf(`orgs/%s/actions/variables/%s`, orgName, variableName) return patchVariable(client, host, path, payload) } func patchEnvVariable(client *api.Client, host string, repoID int64, envName, variableName, value string) error { payload := setPayload{ Value: value, } path := fmt.Sprintf(`repositories/%d/environments/%s/variables/%s`, repoID, envName, variableName) return patchVariable(client, host, path, payload) } func patchRepoVariable(client *api.Client, repo ghrepo.Interface, variableName, value string) error { payload := setPayload{ Value: value, } path := fmt.Sprintf(`repos/%s/actions/variables/%s`, ghrepo.FullName(repo), variableName) return patchVariable(client, repo.RepoHost(), path, payload) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/variable/set/set.go
pkg/cmd/variable/set/set.go
package set import ( "bytes" "errors" "fmt" "io" "net/http" "os" "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/variable/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/joho/godotenv" "github.com/spf13/cobra" ) type iprompter interface { Input(string, string) (string, error) } type SetOptions struct { HttpClient func() (*http.Client, error) IO *iostreams.IOStreams Config func() (gh.Config, error) BaseRepo func() (ghrepo.Interface, error) Prompter iprompter VariableName string OrgName string EnvName string Body string Visibility string RepositoryNames []string EnvFile string } func NewCmdSet(f *cmdutil.Factory, runF func(*SetOptions) error) *cobra.Command { opts := &SetOptions{ IO: f.IOStreams, Config: f.Config, HttpClient: f.HttpClient, Prompter: f.Prompter, } cmd := &cobra.Command{ Use: "set <variable-name>", Short: "Create or update variables", Long: heredoc.Doc(` Set a value for a variable on one of the following levels: - repository (default): available to GitHub Actions runs or Dependabot in a repository - environment: available to GitHub Actions runs for a deployment environment in a repository - organization: available to GitHub Actions runs or Dependabot within an organization Organization variable can optionally be restricted to only be available to specific repositories. `), Example: heredoc.Doc(` # Add variable value for the current repository in an interactive prompt $ gh variable set MYVARIABLE # Read variable value from an environment variable $ gh variable set MYVARIABLE --body "$ENV_VALUE" # Read variable value from a file $ gh variable set MYVARIABLE < myfile.txt # Set variable for a deployment environment in the current repository $ gh variable set MYVARIABLE --env myenvironment # Set organization-level variable visible to both public and private repositories $ gh variable set MYVARIABLE --org myOrg --visibility all # Set organization-level variable visible to specific repositories $ gh variable set MYVARIABLE --org myOrg --repos repo1,repo2,repo3 # Set multiple variables imported from the ".env" file $ gh variable set -f .env `), Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { // support `-R, --repo` override opts.BaseRepo = f.BaseRepo if err := cmdutil.MutuallyExclusive("specify only one of `--org` or `--env`", opts.OrgName != "", opts.EnvName != ""); err != nil { return err } if err := cmdutil.MutuallyExclusive("specify only one of `--body` or `--env-file`", opts.Body != "", opts.EnvFile != ""); err != nil { return err } if len(args) == 0 { if opts.EnvFile == "" { return cmdutil.FlagErrorf("must pass name argument") } } else { opts.VariableName = args[0] } if cmd.Flags().Changed("visibility") { if opts.OrgName == "" { return cmdutil.FlagErrorf("`--visibility` is only supported with `--org`") } if opts.Visibility != shared.Selected && len(opts.RepositoryNames) > 0 { return cmdutil.FlagErrorf("`--repos` is only supported with `--visibility=selected`") } if opts.Visibility == shared.Selected && len(opts.RepositoryNames) == 0 { return cmdutil.FlagErrorf("`--repos` list required with `--visibility=selected`") } } else { if len(opts.RepositoryNames) > 0 { opts.Visibility = shared.Selected } } if runF != nil { return runF(opts) } return setRun(opts) }, } cmd.Flags().StringVarP(&opts.OrgName, "org", "o", "", "Set `organization` variable") cmd.Flags().StringVarP(&opts.EnvName, "env", "e", "", "Set deployment `environment` variable") cmdutil.StringEnumFlag(cmd, &opts.Visibility, "visibility", "v", shared.Private, []string{shared.All, shared.Private, shared.Selected}, "Set visibility for an organization variable") cmd.Flags().StringSliceVarP(&opts.RepositoryNames, "repos", "r", []string{}, "List of `repositories` that can access an organization variable") cmd.Flags().StringVarP(&opts.Body, "body", "b", "", "The value for the variable (reads from standard input if not specified)") cmd.Flags().StringVarP(&opts.EnvFile, "env-file", "f", "", "Load variable names and values from a dotenv-formatted `file`") return cmd } func setRun(opts *SetOptions) error { variables, err := getVariablesFromOptions(opts) if err != nil { return err } c, err := opts.HttpClient() if err != nil { return fmt.Errorf("could not set http client: %w", err) } client := api.NewClientFromHTTP(c) orgName := opts.OrgName envName := opts.EnvName var host string var baseRepo ghrepo.Interface if orgName == "" { baseRepo, err = opts.BaseRepo() if err != nil { return err } host = baseRepo.RepoHost() } else { cfg, err := opts.Config() if err != nil { return err } host, _ = cfg.Authentication().DefaultHost() } entity, err := shared.GetVariableEntity(orgName, envName) if err != nil { return err } opts.IO.StartProgressIndicator() repositoryIDs, err := getRepoIds(client, host, opts.OrgName, opts.RepositoryNames) opts.IO.StopProgressIndicator() if err != nil { return err } setc := make(chan setResult) for key, value := range variables { k := key v := value go func() { setOpts := setOptions{ Entity: entity, Environment: envName, Key: k, Organization: orgName, Repository: baseRepo, RepositoryIDs: repositoryIDs, Value: v, Visibility: opts.Visibility, } setc <- setVariable(client, host, setOpts) }() } var errs []error cs := opts.IO.ColorScheme() for i := 0; i < len(variables); i++ { result := <-setc if result.Err != nil { errs = append(errs, result.Err) continue } if !opts.IO.IsStdoutTTY() { continue } target := orgName if orgName == "" { target = ghrepo.FullName(baseRepo) } if envName != "" { target += " environment " + envName } fmt.Fprintf(opts.IO.Out, "%s %s variable %s for %s\n", cs.SuccessIcon(), result.Operation, result.Key, target) } return errors.Join(errs...) } func getVariablesFromOptions(opts *SetOptions) (map[string]string, error) { variables := make(map[string]string) if opts.EnvFile != "" { var r io.Reader if opts.EnvFile == "-" { defer opts.IO.In.Close() r = opts.IO.In } else { f, err := os.Open(opts.EnvFile) if err != nil { return nil, fmt.Errorf("failed to open env file: %w", err) } defer f.Close() r = f } envs, err := godotenv.Parse(r) if err != nil { return nil, fmt.Errorf("error parsing env file: %w", err) } if len(envs) == 0 { return nil, fmt.Errorf("no variables found in file") } for key, value := range envs { variables[key] = value } return variables, nil } body, err := getBody(opts) if err != nil { return nil, fmt.Errorf("did not understand variable body: %w", err) } variables[opts.VariableName] = body return variables, nil } func getBody(opts *SetOptions) (string, error) { if opts.Body != "" { return opts.Body, nil } if opts.IO.CanPrompt() { bodyInput, err := opts.Prompter.Input("Paste your variable", "") if err != nil { return "", err } fmt.Fprintln(opts.IO.Out) return bodyInput, nil } body, err := io.ReadAll(opts.IO.In) if err != nil { return "", fmt.Errorf("failed to read from standard input: %w", err) } return string(bytes.TrimRight(body, "\r\n")), nil } func getRepoIds(client *api.Client, host, owner string, repositoryNames []string) ([]int64, error) { if len(repositoryNames) == 0 { return nil, nil } repos := make([]ghrepo.Interface, 0, len(repositoryNames)) for _, repositoryName := range repositoryNames { if repositoryName == "" { continue } var repo ghrepo.Interface if strings.Contains(repositoryName, "/") || owner == "" { var err error repo, err = ghrepo.FromFullNameWithHost(repositoryName, host) if err != nil { return nil, fmt.Errorf("invalid repository name") } } else { repo = ghrepo.NewWithHost(owner, repositoryName, host) } repos = append(repos, repo) } if len(repos) == 0 { return nil, fmt.Errorf("resetting repositories selected to zero is not supported") } repositoryIDs, err := api.GetRepoIDs(client, host, repos) if err != nil { return nil, fmt.Errorf("failed to look up IDs for repositories %v: %w", repositoryNames, err) } return repositoryIDs, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/search/search.go
pkg/cmd/search/search.go
package search import ( "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/spf13/cobra" searchCodeCmd "github.com/cli/cli/v2/pkg/cmd/search/code" searchCommitsCmd "github.com/cli/cli/v2/pkg/cmd/search/commits" searchIssuesCmd "github.com/cli/cli/v2/pkg/cmd/search/issues" searchPrsCmd "github.com/cli/cli/v2/pkg/cmd/search/prs" searchReposCmd "github.com/cli/cli/v2/pkg/cmd/search/repos" ) func NewCmdSearch(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "search <command>", Short: "Search for repositories, issues, and pull requests", Long: heredoc.Docf(` Search across all of GitHub. Excluding search results that match a qualifier In a browser, the GitHub search syntax supports excluding results that match a search qualifier by prefixing the qualifier with a hyphen. For example, to search for issues that do not have the label "bug", you would use %[1]s-label:bug%[1]s as a search qualifier. %[1]sgh%[1]s supports this syntax in %[1]sgh search%[1]s as well, but it requires extra command line arguments to avoid the hyphen being interpreted as a command line flag because it begins with a hyphen. On Unix-like systems, you can use the %[1]s--%[1]s argument to indicate that the arguments that follow are not a flag, but rather a query string. For example: $ gh search issues -- "my-search-query -label:bug" On PowerShell, you must use both the %[1]s--%[2]s%[1]s argument and the %[1]s--%[1]s argument to produce the same effect. For example: $ gh --%[2]s search issues -- "my search query -label:bug" See the following for more information: - GitHub search syntax: <https://docs.github.com/en/search-github/getting-started-with-searching-on-github/understanding-the-search-syntax#exclude-results-that-match-a-qualifier> - The PowerShell stop parse flag %[1]s--%[2]s%[1]s: <https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_parsing?view=powershell-7.5#the-stop-parsing-token> - The Unix-like %[1]s--%[1]s argument: <https://www.gnu.org/software/bash/manual/bash.html#Shell-Builtin-Commands-1> `, "`", "%"), } cmd.AddCommand(searchCodeCmd.NewCmdCode(f, nil)) cmd.AddCommand(searchCommitsCmd.NewCmdCommits(f, nil)) cmd.AddCommand(searchIssuesCmd.NewCmdIssues(f, nil)) cmd.AddCommand(searchPrsCmd.NewCmdPrs(f, nil)) cmd.AddCommand(searchReposCmd.NewCmdRepos(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/search/issues/issues_test.go
pkg/cmd/search/issues/issues_test.go
package issues import ( "bytes" "testing" "github.com/cli/cli/v2/pkg/cmd/search/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/pkg/search" "github.com/google/shlex" "github.com/stretchr/testify/assert" ) func TestNewCmdIssues(t *testing.T) { var trueBool = true tests := []struct { name string input string output shared.IssuesOptions wantErr bool errMsg string }{ { name: "no arguments", input: "", wantErr: true, errMsg: "specify search keywords or flags", }, { name: "keyword arguments", input: "some search terms", output: shared.IssuesOptions{ Query: search.Query{ Keywords: []string{"some", "search", "terms"}, Kind: "issues", Limit: 30, Qualifiers: search.Qualifiers{Type: "issue"}, }, }, }, { name: "web flag", input: "--web", output: shared.IssuesOptions{ Query: search.Query{ Keywords: []string{}, Kind: "issues", Limit: 30, Qualifiers: search.Qualifiers{Type: "issue"}, }, WebMode: true, }, }, { name: "limit flag", input: "--limit 10", output: shared.IssuesOptions{ Query: search.Query{ Keywords: []string{}, Kind: "issues", Limit: 10, Qualifiers: search.Qualifiers{Type: "issue"}, }, }, }, { name: "invalid limit flag", input: "--limit 1001", wantErr: true, errMsg: "`--limit` must be between 1 and 1000", }, { name: "order flag", input: "--order asc", output: shared.IssuesOptions{ Query: search.Query{ Keywords: []string{}, Kind: "issues", Limit: 30, Order: "asc", Qualifiers: search.Qualifiers{Type: "issue"}, }, }, }, { name: "invalid order flag", input: "--order invalid", wantErr: true, errMsg: "invalid argument \"invalid\" for \"--order\" flag: valid values are {asc|desc}", }, { name: "include-prs flag", input: "--include-prs", output: shared.IssuesOptions{ Query: search.Query{ Keywords: []string{}, Kind: "issues", Limit: 30, Qualifiers: search.Qualifiers{Type: ""}, }, }, }, { name: "app flag", input: "--app dependabot", output: shared.IssuesOptions{ Query: search.Query{ Keywords: []string{}, Kind: "issues", Limit: 30, Qualifiers: search.Qualifiers{Type: "issue", Author: "app/dependabot"}, }, }, }, { name: "invalid author and app flags", input: "--author test --app dependabot", wantErr: true, errMsg: "specify only `--author` or `--app`", }, { name: "qualifier flags", input: ` --archived --assignee=assignee --author=author --closed=closed --commenter=commenter --created=created --match=title,body --language=language --locked --mentions=mentions --no-label --repo=owner/repo --updated=updated --visibility=public `, output: shared.IssuesOptions{ Query: search.Query{ Keywords: []string{}, Kind: "issues", Limit: 30, Qualifiers: search.Qualifiers{ Archived: &trueBool, Assignee: "assignee", Author: "author", Closed: "closed", Commenter: "commenter", Created: "created", In: []string{"title", "body"}, Is: []string{"public", "locked"}, Language: "language", Mentions: "mentions", No: []string{"label"}, Repo: []string{"owner/repo"}, Type: "issue", Updated: "updated", }, }, }, }, } 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 *shared.IssuesOptions cmd := NewCmdIssues(f, func(opts *shared.IssuesOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err = cmd.ExecuteC() if tt.wantErr { assert.EqualError(t, err, tt.errMsg) return } assert.NoError(t, err) assert.Equal(t, tt.output.Query, gotOpts.Query) assert.Equal(t, tt.output.WebMode, gotOpts.WebMode) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/search/issues/issues.go
pkg/cmd/search/issues/issues.go
package issues import ( "fmt" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/pkg/cmd/search/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/search" "github.com/spf13/cobra" ) func NewCmdIssues(f *cmdutil.Factory, runF func(*shared.IssuesOptions) error) *cobra.Command { var locked, includePrs bool var noAssignee, noLabel, noMilestone, noProject bool var order, sort string var appAuthor string opts := &shared.IssuesOptions{ Browser: f.Browser, Entity: shared.Issues, IO: f.IOStreams, Query: search.Query{Kind: search.KindIssues, Qualifiers: search.Qualifiers{Type: "issue"}}, } cmd := &cobra.Command{ Use: "issues [<query>]", Short: "Search for issues", // TODO advancedIssueSearchCleanup // Update the links and remove the mention at GHES 3.17 version. Long: heredoc.Docf(` Search for issues on GitHub. The command supports constructing queries using the GitHub search syntax, using the parameter and qualifier flags, or a combination of the two. GitHub search syntax is documented at: <https://docs.github.com/search-github/searching-on-github/searching-issues-and-pull-requests> On supported GitHub hosts, advanced issue search syntax can be used in the %[1]s--search%[1]s query. For more information about advanced issue search, see: <https://docs.github.com/en/issues/tracking-your-work-with-issues/using-issues/filtering-and-searching-issues-and-pull-requests#building-advanced-filters-for-issues> For more information on handling search queries containing a hyphen, run %[1]sgh search --help%[1]s. `, "`"), Example: heredoc.Doc(` # Search issues matching set of keywords "readme" and "typo" $ gh search issues readme typo # Search issues matching phrase "broken feature" $ gh search issues "broken feature" # Search issues and pull requests in cli organization $ gh search issues --include-prs --owner=cli # Search open issues assigned to yourself $ gh search issues --assignee=@me --state=open # Search issues with numerous comments $ gh search issues --comments=">100" # Search issues without label "bug" $ gh search issues -- -label:bug # Search issues only from un-archived repositories (default is all repositories) $ gh search issues --owner github --archived=false `), RunE: func(c *cobra.Command, args []string) error { if len(args) == 0 && c.Flags().NFlag() == 0 { return cmdutil.FlagErrorf("specify search keywords or flags") } if opts.Query.Limit < 1 || opts.Query.Limit > shared.SearchMaxResults { return cmdutil.FlagErrorf("`--limit` must be between 1 and 1000") } if c.Flags().Changed("author") && c.Flags().Changed("app") { return cmdutil.FlagErrorf("specify only `--author` or `--app`") } if c.Flags().Changed("app") { opts.Query.Qualifiers.Author = fmt.Sprintf("app/%s", appAuthor) } if includePrs { opts.Entity = shared.Both opts.Query.Qualifiers.Type = "" } if c.Flags().Changed("order") { opts.Query.Order = order } if c.Flags().Changed("sort") { opts.Query.Sort = sort } if c.Flags().Changed("locked") { if locked { opts.Query.Qualifiers.Is = append(opts.Query.Qualifiers.Is, "locked") } else { opts.Query.Qualifiers.Is = append(opts.Query.Qualifiers.Is, "unlocked") } } if c.Flags().Changed("no-assignee") && noAssignee { opts.Query.Qualifiers.No = append(opts.Query.Qualifiers.No, "assignee") } if c.Flags().Changed("no-label") && noLabel { opts.Query.Qualifiers.No = append(opts.Query.Qualifiers.No, "label") } if c.Flags().Changed("no-milestone") && noMilestone { opts.Query.Qualifiers.No = append(opts.Query.Qualifiers.No, "milestone") } if c.Flags().Changed("no-project") && noProject { opts.Query.Qualifiers.No = append(opts.Query.Qualifiers.No, "project") } opts.Query.Keywords = args if runF != nil { return runF(opts) } var err error opts.Searcher, err = shared.Searcher(f) if err != nil { return err } return shared.SearchIssues(opts) }, } // Output flags cmdutil.AddJSONFlags(cmd, &opts.Exporter, search.IssueFields) cmd.Flags().BoolVarP(&opts.WebMode, "web", "w", false, "Open the search query in the web browser") // Query parameter flags cmd.Flags().IntVarP(&opts.Query.Limit, "limit", "L", 30, "Maximum number of results to fetch") cmdutil.StringEnumFlag(cmd, &order, "order", "", "desc", []string{"asc", "desc"}, "Order of results returned, ignored unless '--sort' flag is specified") cmdutil.StringEnumFlag(cmd, &sort, "sort", "", "best-match", []string{ "comments", "created", "interactions", "reactions", "reactions-+1", "reactions--1", "reactions-heart", "reactions-smile", "reactions-tada", "reactions-thinking_face", "updated", }, "Sort fetched results") // Query qualifier flags cmd.Flags().BoolVar(&includePrs, "include-prs", false, "Include pull requests in results") cmd.Flags().StringVar(&appAuthor, "app", "", "Filter by GitHub App author") cmdutil.NilBoolFlag(cmd, &opts.Query.Qualifiers.Archived, "archived", "", "Filter based on the repository archived state {true|false}") cmd.Flags().StringVar(&opts.Query.Qualifiers.Assignee, "assignee", "", "Filter by assignee") cmd.Flags().StringVar(&opts.Query.Qualifiers.Author, "author", "", "Filter by author") cmd.Flags().StringVar(&opts.Query.Qualifiers.Closed, "closed", "", "Filter on closed at `date`") cmd.Flags().StringVar(&opts.Query.Qualifiers.Commenter, "commenter", "", "Filter based on comments by `user`") cmd.Flags().StringVar(&opts.Query.Qualifiers.Comments, "comments", "", "Filter on `number` of comments") cmd.Flags().StringVar(&opts.Query.Qualifiers.Created, "created", "", "Filter based on created at `date`") cmdutil.StringSliceEnumFlag(cmd, &opts.Query.Qualifiers.In, "match", "", nil, []string{"title", "body", "comments"}, "Restrict search to specific field of issue") cmd.Flags().StringVar(&opts.Query.Qualifiers.Interactions, "interactions", "", "Filter on `number` of reactions and comments") cmd.Flags().StringVar(&opts.Query.Qualifiers.Involves, "involves", "", "Filter based on involvement of `user`") cmdutil.StringSliceEnumFlag(cmd, &opts.Query.Qualifiers.Is, "visibility", "", nil, []string{"public", "private", "internal"}, "Filter based on repository visibility") cmd.Flags().StringSliceVar(&opts.Query.Qualifiers.Label, "label", nil, "Filter on label") cmd.Flags().StringVar(&opts.Query.Qualifiers.Language, "language", "", "Filter based on the coding language") cmd.Flags().BoolVar(&locked, "locked", false, "Filter on locked conversation status") cmd.Flags().StringVar(&opts.Query.Qualifiers.Mentions, "mentions", "", "Filter based on `user` mentions") cmd.Flags().StringVar(&opts.Query.Qualifiers.Milestone, "milestone", "", "Filter by milestone `title`") cmd.Flags().BoolVar(&noAssignee, "no-assignee", false, "Filter on missing assignee") cmd.Flags().BoolVar(&noLabel, "no-label", false, "Filter on missing label") cmd.Flags().BoolVar(&noMilestone, "no-milestone", false, "Filter on missing milestone") cmd.Flags().BoolVar(&noProject, "no-project", false, "Filter on missing project") cmd.Flags().StringVar(&opts.Query.Qualifiers.Project, "project", "", "Filter on project board `owner/number`") cmd.Flags().StringVar(&opts.Query.Qualifiers.Reactions, "reactions", "", "Filter on `number` of reactions") cmd.Flags().StringSliceVarP(&opts.Query.Qualifiers.Repo, "repo", "R", nil, "Filter on repository") cmdutil.StringEnumFlag(cmd, &opts.Query.Qualifiers.State, "state", "", "", []string{"open", "closed"}, "Filter based on state") cmd.Flags().StringVar(&opts.Query.Qualifiers.Team, "team-mentions", "", "Filter based on team mentions") cmd.Flags().StringVar(&opts.Query.Qualifiers.Updated, "updated", "", "Filter on last updated at `date`") cmd.Flags().StringSliceVar(&opts.Query.Qualifiers.User, "owner", nil, "Filter on repository owner") return cmd }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/search/commits/commits_test.go
pkg/cmd/search/commits/commits_test.go
package commits import ( "bytes" "fmt" "testing" "time" "github.com/cli/cli/v2/internal/browser" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/pkg/search" "github.com/google/shlex" "github.com/stretchr/testify/assert" ) func TestNewCmdCommits(t *testing.T) { var trueBool = true tests := []struct { name string input string output CommitsOptions wantErr bool errMsg string }{ { name: "no arguments", input: "", wantErr: true, errMsg: "specify search keywords or flags", }, { name: "keyword arguments", input: "some search terms", output: CommitsOptions{ Query: search.Query{Keywords: []string{"some", "search", "terms"}, Kind: "commits", Limit: 30}, }, }, { name: "web flag", input: "--web", output: CommitsOptions{ Query: search.Query{Keywords: []string{}, Kind: "commits", Limit: 30}, WebMode: true, }, }, { name: "limit flag", input: "--limit 10", output: CommitsOptions{Query: search.Query{Keywords: []string{}, Kind: "commits", Limit: 10}}, }, { name: "invalid limit flag", input: "--limit 1001", wantErr: true, errMsg: "`--limit` must be between 1 and 1000", }, { name: "order flag", input: "--order asc", output: CommitsOptions{ Query: search.Query{Keywords: []string{}, Kind: "commits", Limit: 30, Order: "asc"}, }, }, { name: "invalid order flag", input: "--order invalid", wantErr: true, errMsg: "invalid argument \"invalid\" for \"--order\" flag: valid values are {asc|desc}", }, { name: "qualifier flags", input: ` --author=foo --author-date=01-01-2000 --author-email=foo@example.com --author-name=Foo --committer=bar --committer-date=01-02-2000 --committer-email=bar@example.com --committer-name=Bar --hash=aaa --merge --parent=bbb --repo=owner/repo --tree=ccc --owner=owner --visibility=public `, output: CommitsOptions{ Query: search.Query{ Keywords: []string{}, Kind: "commits", Limit: 30, Qualifiers: search.Qualifiers{ Author: "foo", AuthorDate: "01-01-2000", AuthorEmail: "foo@example.com", AuthorName: "Foo", Committer: "bar", CommitterDate: "01-02-2000", CommitterEmail: "bar@example.com", CommitterName: "Bar", Hash: "aaa", Merge: &trueBool, Parent: "bbb", Repo: []string{"owner/repo"}, Tree: "ccc", User: []string{"owner"}, Is: []string{"public"}, }, }, }, }, } 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 *CommitsOptions cmd := NewCmdCommits(f, func(opts *CommitsOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err = cmd.ExecuteC() if tt.wantErr { assert.EqualError(t, err, tt.errMsg) return } assert.NoError(t, err) assert.Equal(t, tt.output.Query, gotOpts.Query) assert.Equal(t, tt.output.WebMode, gotOpts.WebMode) }) } } func TestCommitsRun(t *testing.T) { var now = time.Date(2023, 1, 17, 12, 30, 0, 0, time.UTC) var author = search.CommitUser{Date: time.Date(2022, 12, 27, 11, 30, 0, 0, time.UTC)} var committer = search.CommitUser{Date: time.Date(2022, 12, 28, 12, 30, 0, 0, time.UTC)} var query = search.Query{ Keywords: []string{"cli"}, Kind: "commits", Limit: 30, Qualifiers: search.Qualifiers{}, } tests := []struct { errMsg string name string opts *CommitsOptions tty bool wantErr bool wantStderr string wantStdout string }{ { name: "displays results tty", opts: &CommitsOptions{ Query: query, Searcher: &search.SearcherMock{ CommitsFunc: func(query search.Query) (search.CommitsResult, error) { return search.CommitsResult{ IncompleteResults: false, Items: []search.Commit{ { Author: search.User{Login: "monalisa"}, Info: search.CommitInfo{Author: author, Committer: committer, Message: "hello"}, Repo: search.Repository{FullName: "test/cli"}, Sha: "aaaaaaaa", }, { Author: search.User{Login: "johnnytest"}, Info: search.CommitInfo{Author: author, Committer: committer, Message: "hi"}, Repo: search.Repository{FullName: "test/cliing", IsPrivate: true}, Sha: "bbbbbbbb", }, { Author: search.User{Login: "hubot"}, Info: search.CommitInfo{Author: author, Committer: committer, Message: "greetings"}, Repo: search.Repository{FullName: "cli/cli"}, Sha: "cccccccc", }, }, Total: 300, }, nil }, }, }, tty: true, wantStdout: "\nShowing 3 of 300 commits\n\nREPO SHA MESSAGE AUTHOR CREATED\ntest/cli aaaaaaaa hello monalisa about 21 days ago\ntest/cliing bbbbbbbb hi johnnytest about 21 days ago\ncli/cli cccccccc greetings hubot about 21 days ago\n", }, { name: "displays results notty", opts: &CommitsOptions{ Query: query, Searcher: &search.SearcherMock{ CommitsFunc: func(query search.Query) (search.CommitsResult, error) { return search.CommitsResult{ IncompleteResults: false, Items: []search.Commit{ { Author: search.User{Login: "monalisa"}, Info: search.CommitInfo{Author: author, Committer: committer, Message: "hello"}, Repo: search.Repository{FullName: "test/cli"}, Sha: "aaaaaaaa", }, { Author: search.User{Login: "johnnytest"}, Info: search.CommitInfo{Author: author, Committer: committer, Message: "hi"}, Repo: search.Repository{FullName: "test/cliing", IsPrivate: true}, Sha: "bbbbbbbb", }, { Author: search.User{Login: "hubot"}, Info: search.CommitInfo{Author: author, Committer: committer, Message: "greetings"}, Repo: search.Repository{FullName: "cli/cli"}, Sha: "cccccccc", }, }, Total: 300, }, nil }, }, }, wantStdout: "test/cli\taaaaaaaa\thello\tmonalisa\t2022-12-27T11:30:00Z\ntest/cliing\tbbbbbbbb\thi\tjohnnytest\t2022-12-27T11:30:00Z\ncli/cli\tcccccccc\tgreetings\thubot\t2022-12-27T11:30:00Z\n", }, { name: "displays no results", opts: &CommitsOptions{ Query: query, Searcher: &search.SearcherMock{ CommitsFunc: func(query search.Query) (search.CommitsResult, error) { return search.CommitsResult{}, nil }, }, }, wantErr: true, errMsg: "no commits matched your search", }, { name: "displays search error", opts: &CommitsOptions{ Query: query, Searcher: &search.SearcherMock{ CommitsFunc: func(query search.Query) (search.CommitsResult, error) { return search.CommitsResult{}, fmt.Errorf("error with query") }, }, }, errMsg: "error with query", wantErr: true, }, { name: "opens browser for web mode tty", opts: &CommitsOptions{ Browser: &browser.Stub{}, Query: query, Searcher: &search.SearcherMock{ URLFunc: func(query search.Query) string { return "https://github.com/search?type=commits&q=cli" }, }, WebMode: true, }, tty: true, wantStderr: "Opening https://github.com/search in your browser.\n", }, { name: "opens browser for web mode notty", opts: &CommitsOptions{ Browser: &browser.Stub{}, Query: query, Searcher: &search.SearcherMock{ URLFunc: func(query search.Query) string { return "https://github.com/search?type=commits&q=cli" }, }, WebMode: true, }, }, } for _, tt := range tests { ios, _, stdout, stderr := iostreams.Test() ios.SetStdinTTY(tt.tty) ios.SetStdoutTTY(tt.tty) ios.SetStderrTTY(tt.tty) tt.opts.IO = ios tt.opts.Now = now t.Run(tt.name, func(t *testing.T) { err := commitsRun(tt.opts) if tt.wantErr { assert.EqualError(t, err, tt.errMsg) return } else if err != nil { t.Fatalf("commitsRun unexpected error: %v", 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/search/commits/commits.go
pkg/cmd/search/commits/commits.go
package commits import ( "fmt" "time" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/browser" "github.com/cli/cli/v2/internal/tableprinter" "github.com/cli/cli/v2/internal/text" "github.com/cli/cli/v2/pkg/cmd/search/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/pkg/search" "github.com/spf13/cobra" ) type CommitsOptions struct { Browser browser.Browser Exporter cmdutil.Exporter IO *iostreams.IOStreams Now time.Time Query search.Query Searcher search.Searcher WebMode bool } func NewCmdCommits(f *cmdutil.Factory, runF func(*CommitsOptions) error) *cobra.Command { var order string var sort string opts := &CommitsOptions{ Browser: f.Browser, IO: f.IOStreams, Query: search.Query{Kind: search.KindCommits}, } cmd := &cobra.Command{ Use: "commits [<query>]", Short: "Search for commits", Long: heredoc.Docf(` Search for commits on GitHub. The command supports constructing queries using the GitHub search syntax, using the parameter and qualifier flags, or a combination of the two. GitHub search syntax is documented at: <https://docs.github.com/search-github/searching-on-github/searching-commits> For more information on handling search queries containing a hyphen, run %[1]sgh search --help%[1]s. `, "`"), Example: heredoc.Doc(` # Search commits matching set of keywords "readme" and "typo" $ gh search commits readme typo # Search commits matching phrase "bug fix" $ gh search commits "bug fix" # Search commits committed by user "monalisa" $ gh search commits --committer=monalisa # Search commits authored by users with name "Jane Doe" $ gh search commits --author-name="Jane Doe" # Search commits matching hash "8dd03144ffdc6c0d486d6b705f9c7fba871ee7c3" $ gh search commits --hash=8dd03144ffdc6c0d486d6b705f9c7fba871ee7c3 # Search commits authored before February 1st, 2022 $ gh search commits --author-date="<2022-02-01" `), RunE: func(c *cobra.Command, args []string) error { if len(args) == 0 && c.Flags().NFlag() == 0 { return cmdutil.FlagErrorf("specify search keywords or flags") } if opts.Query.Limit < 1 || opts.Query.Limit > shared.SearchMaxResults { return cmdutil.FlagErrorf("`--limit` must be between 1 and 1000") } if c.Flags().Changed("order") { opts.Query.Order = order } if c.Flags().Changed("sort") { opts.Query.Sort = sort } opts.Query.Keywords = args if runF != nil { return runF(opts) } var err error opts.Searcher, err = shared.Searcher(f) if err != nil { return err } return commitsRun(opts) }, } // Output flags cmdutil.AddJSONFlags(cmd, &opts.Exporter, search.CommitFields) cmd.Flags().BoolVarP(&opts.WebMode, "web", "w", false, "Open the search query in the web browser") // Query parameter flags cmd.Flags().IntVarP(&opts.Query.Limit, "limit", "L", 30, "Maximum number of commits to fetch") cmdutil.StringEnumFlag(cmd, &order, "order", "", "desc", []string{"asc", "desc"}, "Order of commits returned, ignored unless '--sort' flag is specified") cmdutil.StringEnumFlag(cmd, &sort, "sort", "", "best-match", []string{"author-date", "committer-date"}, "Sort fetched commits") // Query qualifier flags cmd.Flags().StringVar(&opts.Query.Qualifiers.Author, "author", "", "Filter by author") cmd.Flags().StringVar(&opts.Query.Qualifiers.AuthorDate, "author-date", "", "Filter based on authored `date`") cmd.Flags().StringVar(&opts.Query.Qualifiers.AuthorEmail, "author-email", "", "Filter on author email") cmd.Flags().StringVar(&opts.Query.Qualifiers.AuthorName, "author-name", "", "Filter on author name") cmd.Flags().StringVar(&opts.Query.Qualifiers.Committer, "committer", "", "Filter by committer") cmd.Flags().StringVar(&opts.Query.Qualifiers.CommitterDate, "committer-date", "", "Filter based on committed `date`") cmd.Flags().StringVar(&opts.Query.Qualifiers.CommitterEmail, "committer-email", "", "Filter on committer email") cmd.Flags().StringVar(&opts.Query.Qualifiers.CommitterName, "committer-name", "", "Filter on committer name") cmd.Flags().StringVar(&opts.Query.Qualifiers.Hash, "hash", "", "Filter by commit hash") cmdutil.NilBoolFlag(cmd, &opts.Query.Qualifiers.Merge, "merge", "", "Filter on merge commits") cmd.Flags().StringVar(&opts.Query.Qualifiers.Parent, "parent", "", "Filter by parent hash") cmd.Flags().StringSliceVarP(&opts.Query.Qualifiers.Repo, "repo", "R", nil, "Filter on repository") cmd.Flags().StringVar(&opts.Query.Qualifiers.Tree, "tree", "", "Filter by tree hash") cmd.Flags().StringSliceVar(&opts.Query.Qualifiers.User, "owner", nil, "Filter on repository owner") cmdutil.StringSliceEnumFlag(cmd, &opts.Query.Qualifiers.Is, "visibility", "", nil, []string{"public", "private", "internal"}, "Filter based on repository visibility") return cmd } func commitsRun(opts *CommitsOptions) error { io := opts.IO if opts.WebMode { url := opts.Searcher.URL(opts.Query) if io.IsStdoutTTY() { fmt.Fprintf(io.ErrOut, "Opening %s in your browser.\n", text.DisplayURL(url)) } return opts.Browser.Browse(url) } io.StartProgressIndicator() result, err := opts.Searcher.Commits(opts.Query) io.StopProgressIndicator() if err != nil { return err } if len(result.Items) == 0 && opts.Exporter == nil { return cmdutil.NewNoResultsError("no commits matched your search") } if err := io.StartPager(); err == nil { defer io.StopPager() } else { fmt.Fprintf(io.ErrOut, "failed to start pager: %v\n", err) } if opts.Exporter != nil { return opts.Exporter.Write(io, result.Items) } return displayResults(io, opts.Now, result) } func displayResults(io *iostreams.IOStreams, now time.Time, results search.CommitsResult) error { if now.IsZero() { now = time.Now() } cs := io.ColorScheme() tp := tableprinter.New(io, tableprinter.WithHeader("Repo", "SHA", "Message", "Author", "Created")) for _, commit := range results.Items { tp.AddField(commit.Repo.FullName) tp.AddField(commit.Sha) tp.AddField(text.RemoveExcessiveWhitespace(commit.Info.Message)) tp.AddField(commit.Author.Login) tp.AddTimeField(now, commit.Info.Author.Date, cs.Muted) tp.EndRow() } if io.IsStdoutTTY() { header := fmt.Sprintf("Showing %d of %d commits\n\n", len(results.Items), results.Total) fmt.Fprintf(io.Out, "\n%s", header) } return tp.Render() }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/search/code/code_test.go
pkg/cmd/search/code/code_test.go
package code import ( "bytes" "fmt" "testing" "github.com/cli/cli/v2/internal/browser" "github.com/cli/cli/v2/internal/config" fd "github.com/cli/cli/v2/internal/featuredetection" "github.com/cli/cli/v2/internal/gh" ghmock "github.com/cli/cli/v2/internal/gh/mock" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/pkg/search" "github.com/google/shlex" "github.com/stretchr/testify/assert" ) func TestNewCmdCode(t *testing.T) { tests := []struct { name string input string output CodeOptions wantErr bool errMsg string }{ { name: "no arguments", input: "", wantErr: true, errMsg: "specify search keywords or flags", }, { name: "keyword arguments", input: "react lifecycle", output: CodeOptions{ Query: search.Query{ Keywords: []string{"react", "lifecycle"}, Kind: "code", Limit: 30, }, }, }, { name: "web flag", input: "--web", output: CodeOptions{ Query: search.Query{ Keywords: []string{}, Kind: "code", Limit: 30, }, WebMode: true, }, }, { name: "limit flag", input: "--limit 10", output: CodeOptions{ Query: search.Query{ Keywords: []string{}, Kind: "code", Limit: 10, }, }, }, { name: "invalid limit flag", input: "--limit 1001", wantErr: true, errMsg: "`--limit` must be between 1 and 1000", }, { name: "qualifier flags", input: ` --extension=extension --filename=filename --match=path,file --language=language --repo=owner/repo --size=5 --owner=owner `, output: CodeOptions{ Query: search.Query{ Keywords: []string{}, Kind: "code", Limit: 30, Qualifiers: search.Qualifiers{ Extension: "extension", Filename: "filename", In: []string{"path", "file"}, Language: "language", Repo: []string{"owner/repo"}, Size: "5", User: []string{"owner"}, }, }, }, }, } 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 *CodeOptions cmd := NewCmdCode(f, func(opts *CodeOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err = cmd.ExecuteC() if tt.wantErr { assert.EqualError(t, err, tt.errMsg) return } assert.NoError(t, err) assert.Equal(t, tt.output.Query, gotOpts.Query) assert.Equal(t, tt.output.WebMode, gotOpts.WebMode) }) } } func TestCodeRun(t *testing.T) { var query = search.Query{ Keywords: []string{"map"}, Kind: "code", Limit: 30, Qualifiers: search.Qualifiers{ Language: "go", Repo: []string{"cli/cli"}, }, } tests := []struct { errMsg string name string opts *CodeOptions tty bool wantErr bool wantStderr string wantStdout string wantBrowse string }{ { name: "displays results tty", opts: &CodeOptions{ Query: query, Searcher: &search.SearcherMock{ CodeFunc: func(query search.Query) (search.CodeResult, error) { return search.CodeResult{ IncompleteResults: false, Items: []search.Code{ { Name: "context.go", Path: "context/context.go", Repository: search.Repository{ FullName: "cli/cli", }, TextMatches: []search.TextMatch{ { Fragment: "\t}\n\n\tvar repos []*api.Repository\n\trepoMap := map[string]bool{}\n\n\tadd := func(r *api.Repository) {\n\t\tfn := ghrepo.FullName(r)", Matches: []search.Match{ { Text: "Map", Indices: []int{38, 41}, }, { Text: "map", Indices: []int{45, 48}, }, }, }, }, }, { Name: "pr.go", Path: "pkg/cmd/pr/pr.go", Repository: search.Repository{ FullName: "cli/cli", }, TextMatches: []search.TextMatch{ { Fragment: "\t\t\t$ gh pr create --fill\n\t\t\t$ gh pr view --web\n\t\t`),\n\t\tAnnotations: map[string]string{\n\t\t\t\"help:arguments\": heredoc.Doc(`\n\t\t\t\tA pull request can be supplied as argument in any of the following formats:\n\t\t\t\t- by number, e.g. \"123\";", Matches: []search.Match{ { Text: "map", Indices: []int{68, 71}, }, }, }, }, }, }, Total: 2, }, nil }, }, }, tty: true, wantStdout: "\nShowing 2 of 2 results\n\ncli/cli context/context.go\n\trepoMap := map[string]bool{}\n\ncli/cli pkg/cmd/pr/pr.go\n\tAnnotations: map[string]string{\n", }, { name: "displays results notty", opts: &CodeOptions{ Query: query, Searcher: &search.SearcherMock{ CodeFunc: func(query search.Query) (search.CodeResult, error) { return search.CodeResult{ IncompleteResults: false, Items: []search.Code{ { Name: "context.go", Path: "context/context.go", Repository: search.Repository{ FullName: "cli/cli", }, TextMatches: []search.TextMatch{ { Fragment: "\t}\n\n\tvar repos []*api.Repository\n\trepoMap := map[string]bool{}\n\n\tadd := func(r *api.Repository) {\n\t\tfn := ghrepo.FullName(r)", Matches: []search.Match{ { Text: "Map", Indices: []int{38, 41}, }, { Text: "map", Indices: []int{45, 48}, }, }, }, }, }, { Name: "pr.go", Path: "pkg/cmd/pr/pr.go", Repository: search.Repository{ FullName: "cli/cli", }, TextMatches: []search.TextMatch{ { Fragment: "\t\t\t$ gh pr create --fill\n\t\t\t$ gh pr view --web\n\t\t`),\n\t\tAnnotations: map[string]string{\n\t\t\t\"help:arguments\": heredoc.Doc(`\n\t\t\t\tA pull request can be supplied as argument in any of the following formats:\n\t\t\t\t- by number, e.g. \"123\";", Matches: []search.Match{ { Text: "map", Indices: []int{68, 71}, }, }, }, }, }, }, Total: 2, }, nil }, }, }, tty: false, wantStdout: "cli/cli:context/context.go: repoMap := map[string]bool{}\ncli/cli:pkg/cmd/pr/pr.go: Annotations: map[string]string{\n", }, { name: "displays no results", opts: &CodeOptions{ Query: query, Searcher: &search.SearcherMock{ CodeFunc: func(query search.Query) (search.CodeResult, error) { return search.CodeResult{}, nil }, }, }, wantErr: true, errMsg: "no code results matched your search", }, { name: "displays search error", opts: &CodeOptions{ Query: query, Searcher: &search.SearcherMock{ CodeFunc: func(query search.Query) (search.CodeResult, error) { return search.CodeResult{}, fmt.Errorf("error with query") }, }, }, wantErr: true, errMsg: "error with query", }, { name: "opens browser for web mode tty", opts: &CodeOptions{ Query: query, Searcher: &search.SearcherMock{ URLFunc: func(query search.Query) string { return "https://github.com/search?type=code&q=map+repo%3Acli%2Fcli" }, }, WebMode: true, }, tty: true, wantStderr: "Opening https://github.com/search in your browser.\n", wantBrowse: "https://github.com/search?type=code&q=map+repo%3Acli%2Fcli", }, { name: "opens browser for web mode notty", opts: &CodeOptions{ Query: query, Searcher: &search.SearcherMock{ URLFunc: func(query search.Query) string { return "https://github.com/search?type=code&q=map+repo%3Acli%2Fcli" }, }, WebMode: true, }, wantBrowse: "https://github.com/search?type=code&q=map+repo%3Acli%2Fcli", }, { name: "converts filename and extension qualifiers for github.com web search", opts: &CodeOptions{ Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, Query: search.Query{ Keywords: []string{"map"}, Kind: "code", Limit: 30, Qualifiers: search.Qualifiers{ Filename: "testing", Extension: "go", }, }, Searcher: search.NewSearcher(nil, "github.com", &fd.DisabledDetectorMock{}), WebMode: true, }, wantBrowse: "https://github.com/search?q=map+path%3Atesting.go&type=code", }, { name: "properly handles extension with dot prefix when converting to path qualifier", opts: &CodeOptions{ Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, Query: search.Query{ Keywords: []string{"map"}, Kind: "code", Limit: 30, Qualifiers: search.Qualifiers{ Filename: "testing", Extension: ".cpp", }, }, Searcher: search.NewSearcher(nil, "github.com", &fd.DisabledDetectorMock{}), WebMode: true, }, wantBrowse: "https://github.com/search?q=map+path%3Atesting.cpp&type=code", }, { name: "does not convert filename and extension qualifiers for GHES web search", opts: &CodeOptions{ Config: func() (gh.Config, error) { cfg := &ghmock.ConfigMock{ AuthenticationFunc: func() gh.AuthConfig { authCfg := &config.AuthConfig{} authCfg.SetDefaultHost("example.com", "GH_HOST") return authCfg }, } return cfg, nil }, Query: search.Query{ Keywords: []string{"map"}, Kind: "code", Limit: 30, Qualifiers: search.Qualifiers{ Filename: "testing", Extension: "go", }, }, Searcher: search.NewSearcher(nil, "example.com", &fd.DisabledDetectorMock{}), WebMode: true, }, wantBrowse: "https://example.com/search?q=map+extension%3Ago+filename%3Atesting&type=code", }, } for _, tt := range tests { ios, _, stdout, stderr := iostreams.Test() ios.SetStdinTTY(tt.tty) ios.SetStdoutTTY(tt.tty) ios.SetStderrTTY(tt.tty) tt.opts.IO = ios browser := &browser.Stub{} tt.opts.Browser = browser t.Run(tt.name, func(t *testing.T) { err := codeRun(tt.opts) if tt.wantErr { assert.EqualError(t, err, tt.errMsg) return } else if err != nil { t.Fatalf("codeRun unexpected error: %v", err) } assert.Equal(t, tt.wantStdout, stdout.String()) assert.Equal(t, tt.wantStderr, stderr.String()) browser.Verify(t, tt.wantBrowse) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/search/code/code.go
pkg/cmd/search/code/code.go
package code import ( "fmt" "strings" "github.com/MakeNowJust/heredoc" "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/cmd/search/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/pkg/search" ghauth "github.com/cli/go-gh/v2/pkg/auth" "github.com/spf13/cobra" ) type CodeOptions struct { Browser browser.Browser Config func() (gh.Config, error) Exporter cmdutil.Exporter IO *iostreams.IOStreams Query search.Query Searcher search.Searcher WebMode bool } func NewCmdCode(f *cmdutil.Factory, runF func(*CodeOptions) error) *cobra.Command { opts := &CodeOptions{ Browser: f.Browser, Config: f.Config, IO: f.IOStreams, Query: search.Query{Kind: search.KindCode}, } cmd := &cobra.Command{ Use: "code <query>", Short: "Search within code", Long: heredoc.Docf(` Search within code in GitHub repositories. The search syntax is documented at: <https://docs.github.com/search-github/searching-on-github/searching-code> Note that these search results are powered by what is now a legacy GitHub code search engine. The results might not match what is seen on %[1]sgithub.com%[1]s, and new features like regex search are not yet available via the GitHub API. For more information on handling search queries containing a hyphen, run %[1]sgh search --help%[1]s. `, "`"), Example: heredoc.Doc(` # Search code matching "react" and "lifecycle" $ gh search code react lifecycle # Search code matching "error handling" $ gh search code "error handling" # Search code matching "deque" in Python files $ gh search code deque --language=python # Search code matching "cli" in repositories owned by microsoft organization $ gh search code cli --owner=microsoft # Search code matching "panic" in the GitHub CLI repository $ gh search code panic --repo cli/cli # Search code matching keyword "lint" in package.json files $ gh search code lint --filename package.json `), RunE: func(c *cobra.Command, args []string) error { if len(args) == 0 && c.Flags().NFlag() == 0 { return cmdutil.FlagErrorf("specify search keywords or flags") } if opts.Query.Limit < 1 || opts.Query.Limit > shared.SearchMaxResults { return cmdutil.FlagErrorf("`--limit` must be between 1 and 1000") } opts.Query.Keywords = args if runF != nil { return runF(opts) } var err error opts.Searcher, err = shared.Searcher(f) if err != nil { return err } return codeRun(opts) }, } // Output flags cmdutil.AddJSONFlags(cmd, &opts.Exporter, search.CodeFields) cmd.Flags().BoolVarP(&opts.WebMode, "web", "w", false, "Open the search query in the web browser") // Query parameter flags cmd.Flags().IntVarP(&opts.Query.Limit, "limit", "L", 30, "Maximum number of code results to fetch") // Query qualifier flags cmd.Flags().StringVar(&opts.Query.Qualifiers.Extension, "extension", "", "Filter on file extension") cmd.Flags().StringVar(&opts.Query.Qualifiers.Filename, "filename", "", "Filter on filename") cmdutil.StringSliceEnumFlag(cmd, &opts.Query.Qualifiers.In, "match", "", nil, []string{"file", "path"}, "Restrict search to file contents or file path") cmd.Flags().StringVarP(&opts.Query.Qualifiers.Language, "language", "", "", "Filter results by language") cmd.Flags().StringSliceVarP(&opts.Query.Qualifiers.Repo, "repo", "R", nil, "Filter on repository") cmd.Flags().StringVar(&opts.Query.Qualifiers.Size, "size", "", "Filter on size range, in kilobytes") cmd.Flags().StringSliceVar(&opts.Query.Qualifiers.User, "owner", nil, "Filter on owner") return cmd } func codeRun(opts *CodeOptions) error { io := opts.IO if opts.WebMode { // Convert `filename` and `extension` legacy search qualifiers to the new code search's `path` // qualifier when used with `--web` because they are incompatible. if opts.Query.Qualifiers.Filename != "" || opts.Query.Qualifiers.Extension != "" { cfg, err := opts.Config() if err != nil { return err } host, _ := cfg.Authentication().DefaultHost() // FIXME: Remove this check once GHES supports the new `path` search qualifier. if !ghauth.IsEnterprise(host) { filename := opts.Query.Qualifiers.Filename extension := opts.Query.Qualifiers.Extension if extension != "" && !strings.HasPrefix(extension, ".") { extension = "." + extension } opts.Query.Qualifiers.Filename = "" opts.Query.Qualifiers.Extension = "" opts.Query.Qualifiers.Path = fmt.Sprintf("%s%s", filename, extension) } } url := opts.Searcher.URL(opts.Query) if io.IsStdoutTTY() { fmt.Fprintf(io.ErrOut, "Opening %s in your browser.\n", text.DisplayURL(url)) } return opts.Browser.Browse(url) } io.StartProgressIndicator() results, err := opts.Searcher.Code(opts.Query) io.StopProgressIndicator() if err != nil { return err } if len(results.Items) == 0 && opts.Exporter == nil { return cmdutil.NewNoResultsError("no code results matched your search") } if err := io.StartPager(); err == nil { defer io.StopPager() } else { fmt.Fprintf(io.ErrOut, "failed to start pager: %v\n", err) } if opts.Exporter != nil { return opts.Exporter.Write(io, results.Items) } return displayResults(io, results) } func displayResults(io *iostreams.IOStreams, results search.CodeResult) error { cs := io.ColorScheme() if io.IsStdoutTTY() { fmt.Fprintf(io.Out, "\nShowing %d of %d results\n\n", len(results.Items), results.Total) for i, code := range results.Items { if i > 0 { fmt.Fprint(io.Out, "\n") } fmt.Fprintf(io.Out, "%s %s\n", cs.Blue(code.Repository.FullName), cs.GreenBold(code.Path)) for _, match := range code.TextMatches { lines := formatMatch(match.Fragment, match.Matches, io) for _, line := range lines { fmt.Fprintf(io.Out, "\t%s\n", strings.TrimSpace(line)) } } } return nil } for _, code := range results.Items { for _, match := range code.TextMatches { lines := formatMatch(match.Fragment, match.Matches, io) for _, line := range lines { fmt.Fprintf(io.Out, "%s:%s: %s\n", cs.Blue(code.Repository.FullName), cs.GreenBold(code.Path), strings.TrimSpace(line)) } } } return nil } func formatMatch(t string, matches []search.Match, io *iostreams.IOStreams) []string { cs := io.ColorScheme() startIndices := map[int]struct{}{} endIndices := map[int]struct{}{} for _, m := range matches { if len(m.Indices) < 2 { continue } startIndices[m.Indices[0]] = struct{}{} endIndices[m.Indices[1]] = struct{}{} } var lines []string var b strings.Builder var found bool for i, c := range t { if c == '\n' { if found { lines = append(lines, b.String()) } found = false b.Reset() continue } if _, ok := startIndices[i]; ok { b.WriteString(cs.HighlightStart()) found = true } else if _, ok := endIndices[i]; ok { b.WriteString(cs.Reset()) } b.WriteRune(c) } if found { lines = append(lines, b.String()) } return lines }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/search/repos/repos_test.go
pkg/cmd/search/repos/repos_test.go
package repos import ( "bytes" "fmt" "testing" "time" "github.com/cli/cli/v2/internal/browser" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/pkg/search" "github.com/google/shlex" "github.com/stretchr/testify/assert" ) func TestNewCmdRepos(t *testing.T) { var trueBool = true tests := []struct { name string input string output ReposOptions wantErr bool errMsg string }{ { name: "no arguments", input: "", wantErr: true, errMsg: "specify search keywords or flags", }, { name: "keyword arguments", input: "some search terms", output: ReposOptions{ Query: search.Query{Keywords: []string{"some", "search", "terms"}, Kind: "repositories", Limit: 30}, }, }, { name: "web flag", input: "--web", output: ReposOptions{ Query: search.Query{Keywords: []string{}, Kind: "repositories", Limit: 30}, WebMode: true, }, }, { name: "limit flag", input: "--limit 10", output: ReposOptions{Query: search.Query{Keywords: []string{}, Kind: "repositories", Limit: 10}}, }, { name: "invalid limit flag", input: "--limit 1001", wantErr: true, errMsg: "`--limit` must be between 1 and 1000", }, { name: "order flag", input: "--order asc", output: ReposOptions{ Query: search.Query{Keywords: []string{}, Kind: "repositories", Limit: 30, Order: "asc"}, }, }, { name: "invalid order flag", input: "--order invalid", wantErr: true, errMsg: "invalid argument \"invalid\" for \"--order\" flag: valid values are {asc|desc}", }, { name: "qualifier flags", input: ` --archived --created=created --followers=1 --include-forks=true --forks=2 --good-first-issues=3 --help-wanted-issues=4 --match=description,readme --language=language --license=license --owner=owner --updated=updated --size=5 --stars=6 --topic=topic --number-topics=7 --visibility=public `, output: ReposOptions{ Query: search.Query{ Keywords: []string{}, Kind: "repositories", Limit: 30, Qualifiers: search.Qualifiers{ Archived: &trueBool, Created: "created", Followers: "1", Fork: "true", Forks: "2", GoodFirstIssues: "3", HelpWantedIssues: "4", In: []string{"description", "readme"}, Language: "language", License: []string{"license"}, Pushed: "updated", Size: "5", Stars: "6", Topic: []string{"topic"}, Topics: "7", User: []string{"owner"}, Is: []string{"public"}, }, }, }, }, } 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 *ReposOptions cmd := NewCmdRepos(f, func(opts *ReposOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err = cmd.ExecuteC() if tt.wantErr { assert.EqualError(t, err, tt.errMsg) return } assert.NoError(t, err) assert.Equal(t, tt.output.Query, gotOpts.Query) assert.Equal(t, tt.output.WebMode, gotOpts.WebMode) }) } } func TestReposRun(t *testing.T) { var now = time.Date(2022, 2, 28, 12, 30, 0, 0, time.UTC) var updatedAt = time.Date(2021, 2, 28, 12, 30, 0, 0, time.UTC) var query = search.Query{ Keywords: []string{"cli"}, Kind: "repositories", Limit: 30, Qualifiers: search.Qualifiers{ Stars: ">50", Topic: []string{"golang"}, }, } tests := []struct { errMsg string name string opts *ReposOptions tty bool wantErr bool wantStderr string wantStdout string }{ { name: "displays results tty", opts: &ReposOptions{ Query: query, Searcher: &search.SearcherMock{ RepositoriesFunc: func(query search.Query) (search.RepositoriesResult, error) { return search.RepositoriesResult{ IncompleteResults: false, Items: []search.Repository{ {FullName: "test/cli", Description: "of course", IsPrivate: true, IsArchived: true, UpdatedAt: updatedAt, Visibility: "private"}, {FullName: "test/cliing", Description: "wow", IsFork: true, UpdatedAt: updatedAt, Visibility: "public"}, {FullName: "cli/cli", Description: "so much", IsArchived: false, UpdatedAt: updatedAt, Visibility: "internal"}, }, Total: 300, }, nil }, }, }, tty: true, wantStdout: "\nShowing 3 of 300 repositories\n\nNAME DESCRIPTION VISIBILITY UPDATED\ntest/cli of course private, archived about 1 year ago\ntest/cliing wow public, fork about 1 year ago\ncli/cli so much internal about 1 year ago\n", }, { name: "displays results notty", opts: &ReposOptions{ Query: query, Searcher: &search.SearcherMock{ RepositoriesFunc: func(query search.Query) (search.RepositoriesResult, error) { return search.RepositoriesResult{ IncompleteResults: false, Items: []search.Repository{ {FullName: "test/cli", Description: "of course", IsPrivate: true, IsArchived: true, UpdatedAt: updatedAt, Visibility: "private"}, {FullName: "test/cliing", Description: "wow", IsFork: true, UpdatedAt: updatedAt, Visibility: "public"}, {FullName: "cli/cli", Description: "so much", IsArchived: false, UpdatedAt: updatedAt, Visibility: "internal"}, }, Total: 300, }, nil }, }, }, wantStdout: "test/cli\tof course\tprivate, archived\t2021-02-28T12:30:00Z\ntest/cliing\twow\tpublic, fork\t2021-02-28T12:30:00Z\ncli/cli\tso much\tinternal\t2021-02-28T12:30:00Z\n", }, { name: "displays no results", opts: &ReposOptions{ Query: query, Searcher: &search.SearcherMock{ RepositoriesFunc: func(query search.Query) (search.RepositoriesResult, error) { return search.RepositoriesResult{}, nil }, }, }, wantErr: true, errMsg: "no repositories matched your search", }, { name: "displays search error", opts: &ReposOptions{ Query: query, Searcher: &search.SearcherMock{ RepositoriesFunc: func(query search.Query) (search.RepositoriesResult, error) { return search.RepositoriesResult{}, fmt.Errorf("error with query") }, }, }, errMsg: "error with query", wantErr: true, }, { name: "opens browser for web mode tty", opts: &ReposOptions{ Browser: &browser.Stub{}, Query: query, Searcher: &search.SearcherMock{ URLFunc: func(query search.Query) string { return "https://github.com/search?type=repositories&q=cli" }, }, WebMode: true, }, tty: true, wantStderr: "Opening https://github.com/search in your browser.\n", }, { name: "opens browser for web mode notty", opts: &ReposOptions{ Browser: &browser.Stub{}, Query: query, Searcher: &search.SearcherMock{ URLFunc: func(query search.Query) string { return "https://github.com/search?type=repositories&q=cli" }, }, WebMode: true, }, }, } for _, tt := range tests { ios, _, stdout, stderr := iostreams.Test() ios.SetStdinTTY(tt.tty) ios.SetStdoutTTY(tt.tty) ios.SetStderrTTY(tt.tty) tt.opts.IO = ios tt.opts.Now = now t.Run(tt.name, func(t *testing.T) { err := reposRun(tt.opts) if tt.wantErr { assert.EqualError(t, err, tt.errMsg) return } else if err != nil { t.Fatalf("reposRun unexpected error: %v", 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/search/repos/repos.go
pkg/cmd/search/repos/repos.go
package repos import ( "fmt" "strings" "time" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/browser" "github.com/cli/cli/v2/internal/tableprinter" "github.com/cli/cli/v2/internal/text" "github.com/cli/cli/v2/pkg/cmd/search/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/pkg/search" "github.com/spf13/cobra" ) type ReposOptions struct { Browser browser.Browser Exporter cmdutil.Exporter IO *iostreams.IOStreams Now time.Time Query search.Query Searcher search.Searcher WebMode bool } func NewCmdRepos(f *cmdutil.Factory, runF func(*ReposOptions) error) *cobra.Command { var order string var sort string opts := &ReposOptions{ Browser: f.Browser, IO: f.IOStreams, Query: search.Query{Kind: search.KindRepositories}, } cmd := &cobra.Command{ Use: "repos [<query>]", Short: "Search for repositories", Long: heredoc.Docf(` Search for repositories on GitHub. The command supports constructing queries using the GitHub search syntax, using the parameter and qualifier flags, or a combination of the two. GitHub search syntax is documented at: <https://docs.github.com/search-github/searching-on-github/searching-for-repositories> For more information on handling search queries containing a hyphen, run %[1]sgh search --help%[1]s. `, "`"), Example: heredoc.Doc(` # Search repositories matching set of keywords "cli" and "shell" $ gh search repos cli shell # Search repositories matching phrase "vim plugin" $ gh search repos "vim plugin" # Search repositories public repos in the microsoft organization $ gh search repos --owner=microsoft --visibility=public # Search repositories with a set of topics $ gh search repos --topic=unix,terminal # Search repositories by coding language and number of good first issues $ gh search repos --language=go --good-first-issues=">=10" # Search repositories without topic "linux" $ gh search repos -- -topic:linux # Search repositories excluding archived repositories $ gh search repos --archived=false `), RunE: func(c *cobra.Command, args []string) error { if len(args) == 0 && c.Flags().NFlag() == 0 { return cmdutil.FlagErrorf("specify search keywords or flags") } if opts.Query.Limit < 1 || opts.Query.Limit > shared.SearchMaxResults { return cmdutil.FlagErrorf("`--limit` must be between 1 and 1000") } if c.Flags().Changed("order") { opts.Query.Order = order } if c.Flags().Changed("sort") { opts.Query.Sort = sort } opts.Query.Keywords = args if runF != nil { return runF(opts) } var err error opts.Searcher, err = shared.Searcher(f) if err != nil { return err } return reposRun(opts) }, } // Output flags cmdutil.AddJSONFlags(cmd, &opts.Exporter, search.RepositoryFields) cmd.Flags().BoolVarP(&opts.WebMode, "web", "w", false, "Open the search query in the web browser") // Query parameter flags cmd.Flags().IntVarP(&opts.Query.Limit, "limit", "L", 30, "Maximum number of repositories to fetch") cmdutil.StringEnumFlag(cmd, &order, "order", "", "desc", []string{"asc", "desc"}, "Order of repositories returned, ignored unless '--sort' flag is specified") cmdutil.StringEnumFlag(cmd, &sort, "sort", "", "best-match", []string{"forks", "help-wanted-issues", "stars", "updated"}, "Sort fetched repositories") // Query qualifier flags cmdutil.NilBoolFlag(cmd, &opts.Query.Qualifiers.Archived, "archived", "", "Filter based on the repository archived state {true|false}") cmd.Flags().StringVar(&opts.Query.Qualifiers.Created, "created", "", "Filter based on created at `date`") cmd.Flags().StringVar(&opts.Query.Qualifiers.Followers, "followers", "", "Filter based on `number` of followers") cmdutil.StringEnumFlag(cmd, &opts.Query.Qualifiers.Fork, "include-forks", "", "", []string{"false", "true", "only"}, "Include forks in fetched repositories") cmd.Flags().StringVar(&opts.Query.Qualifiers.Forks, "forks", "", "Filter on `number` of forks") cmd.Flags().StringVar(&opts.Query.Qualifiers.GoodFirstIssues, "good-first-issues", "", "Filter on `number` of issues with the 'good first issue' label") cmd.Flags().StringVar(&opts.Query.Qualifiers.HelpWantedIssues, "help-wanted-issues", "", "Filter on `number` of issues with the 'help wanted' label") cmdutil.StringSliceEnumFlag(cmd, &opts.Query.Qualifiers.In, "match", "", nil, []string{"name", "description", "readme"}, "Restrict search to specific field of repository") cmdutil.StringSliceEnumFlag(cmd, &opts.Query.Qualifiers.Is, "visibility", "", nil, []string{"public", "private", "internal"}, "Filter based on visibility") cmd.Flags().StringVar(&opts.Query.Qualifiers.Language, "language", "", "Filter based on the coding language") cmd.Flags().StringSliceVar(&opts.Query.Qualifiers.License, "license", nil, "Filter based on license type") cmd.Flags().StringVar(&opts.Query.Qualifiers.Pushed, "updated", "", "Filter on last updated at `date`") cmd.Flags().StringVar(&opts.Query.Qualifiers.Size, "size", "", "Filter on a size range, in kilobytes") cmd.Flags().StringVar(&opts.Query.Qualifiers.Stars, "stars", "", "Filter on `number` of stars") cmd.Flags().StringSliceVar(&opts.Query.Qualifiers.Topic, "topic", nil, "Filter on topic") cmd.Flags().StringVar(&opts.Query.Qualifiers.Topics, "number-topics", "", "Filter on `number` of topics") cmd.Flags().StringSliceVar(&opts.Query.Qualifiers.User, "owner", nil, "Filter on owner") return cmd } func reposRun(opts *ReposOptions) error { io := opts.IO if opts.WebMode { url := opts.Searcher.URL(opts.Query) if io.IsStdoutTTY() { fmt.Fprintf(io.ErrOut, "Opening %s in your browser.\n", text.DisplayURL(url)) } return opts.Browser.Browse(url) } io.StartProgressIndicator() result, err := opts.Searcher.Repositories(opts.Query) io.StopProgressIndicator() if err != nil { return err } if len(result.Items) == 0 && opts.Exporter == nil { return cmdutil.NewNoResultsError("no repositories matched your search") } if err := io.StartPager(); err == nil { defer io.StopPager() } else { fmt.Fprintf(io.ErrOut, "failed to start pager: %v\n", err) } if opts.Exporter != nil { return opts.Exporter.Write(io, result.Items) } return displayResults(io, opts.Now, result) } func displayResults(io *iostreams.IOStreams, now time.Time, results search.RepositoriesResult) error { if now.IsZero() { now = time.Now() } cs := io.ColorScheme() tp := tableprinter.New(io, tableprinter.WithHeader("Name", "Description", "Visibility", "Updated")) for _, repo := range results.Items { tags := []string{visibilityLabel(repo)} if repo.IsFork { tags = append(tags, "fork") } if repo.IsArchived { tags = append(tags, "archived") } info := strings.Join(tags, ", ") infoColor := cs.Muted if repo.IsPrivate { infoColor = cs.Yellow } tp.AddField(repo.FullName, tableprinter.WithColor(cs.Bold)) tp.AddField(text.RemoveExcessiveWhitespace(repo.Description)) tp.AddField(info, tableprinter.WithColor(infoColor)) tp.AddTimeField(now, repo.UpdatedAt, cs.Muted) tp.EndRow() } if io.IsStdoutTTY() { header := fmt.Sprintf("Showing %d of %d repositories\n\n", len(results.Items), results.Total) fmt.Fprintf(io.Out, "\n%s", header) } return tp.Render() } func visibilityLabel(repo search.Repository) string { if repo.Visibility != "" { return 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/search/prs/prs_test.go
pkg/cmd/search/prs/prs_test.go
package prs import ( "bytes" "testing" "github.com/cli/cli/v2/pkg/cmd/search/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/pkg/search" "github.com/google/shlex" "github.com/stretchr/testify/assert" ) func TestNewCmdPrs(t *testing.T) { var trueBool = true tests := []struct { name string input string output shared.IssuesOptions wantErr bool errMsg string }{ { name: "no arguments", input: "", wantErr: true, errMsg: "specify search keywords or flags", }, { name: "keyword arguments", input: "some search terms", output: shared.IssuesOptions{ Query: search.Query{ Keywords: []string{"some", "search", "terms"}, Kind: "issues", Limit: 30, Qualifiers: search.Qualifiers{Type: "pr"}, }, }, }, { name: "web flag", input: "--web", output: shared.IssuesOptions{ Query: search.Query{ Keywords: []string{}, Kind: "issues", Limit: 30, Qualifiers: search.Qualifiers{Type: "pr"}, }, WebMode: true, }, }, { name: "limit flag", input: "--limit 10", output: shared.IssuesOptions{ Query: search.Query{ Keywords: []string{}, Kind: "issues", Limit: 10, Qualifiers: search.Qualifiers{Type: "pr"}, }, }, }, { name: "invalid limit flag", input: "--limit 1001", wantErr: true, errMsg: "`--limit` must be between 1 and 1000", }, { name: "order flag", input: "--order asc", output: shared.IssuesOptions{ Query: search.Query{ Keywords: []string{}, Kind: "issues", Limit: 30, Order: "asc", Qualifiers: search.Qualifiers{Type: "pr"}, }, }, }, { name: "invalid order flag", input: "--order invalid", wantErr: true, errMsg: "invalid argument \"invalid\" for \"--order\" flag: valid values are {asc|desc}", }, { name: "app flag", input: "--app dependabot", output: shared.IssuesOptions{ Query: search.Query{ Keywords: []string{}, Kind: "issues", Limit: 30, Qualifiers: search.Qualifiers{Type: "pr", Author: "app/dependabot"}, }, }, }, { name: "invalid author and app flags", input: "--author test --app dependabot", wantErr: true, errMsg: "specify only `--author` or `--app`", }, { name: "qualifier flags", input: ` --archived --assignee=assignee --author=author --closed=closed --commenter=commenter --created=created --match=title,body --language=language --locked --merged --no-milestone --updated=updated --visibility=public `, output: shared.IssuesOptions{ Query: search.Query{ Keywords: []string{}, Kind: "issues", Limit: 30, Qualifiers: search.Qualifiers{ Archived: &trueBool, Assignee: "assignee", Author: "author", Closed: "closed", Commenter: "commenter", Created: "created", In: []string{"title", "body"}, Is: []string{"public", "locked", "merged"}, Language: "language", No: []string{"milestone"}, Type: "pr", Updated: "updated", }, }, }, }, { name: "review requested flag with user", input: "--review-requested user", output: shared.IssuesOptions{ Query: search.Query{ Keywords: []string{}, Kind: "issues", Limit: 30, Qualifiers: search.Qualifiers{Type: "pr", ReviewRequested: "user"}, }, }, }, { name: "review requested flag with team", input: "--review-requested org/team", output: shared.IssuesOptions{ Query: search.Query{ Keywords: []string{}, Kind: "issues", Limit: 30, Qualifiers: search.Qualifiers{Type: "pr", TeamReviewRequested: "org/team"}, }, }, }, } 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 *shared.IssuesOptions cmd := NewCmdPrs(f, func(opts *shared.IssuesOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err = cmd.ExecuteC() if tt.wantErr { assert.EqualError(t, err, tt.errMsg) return } assert.NoError(t, err) assert.Equal(t, tt.output.Query, gotOpts.Query) assert.Equal(t, tt.output.WebMode, gotOpts.WebMode) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/search/prs/prs.go
pkg/cmd/search/prs/prs.go
package prs import ( "fmt" "strings" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/pkg/cmd/search/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/search" "github.com/spf13/cobra" ) func NewCmdPrs(f *cmdutil.Factory, runF func(*shared.IssuesOptions) error) *cobra.Command { var locked, merged bool var noAssignee, noLabel, noMilestone, noProject bool var order, sort string var appAuthor string var requestedReviewer string opts := &shared.IssuesOptions{ Browser: f.Browser, Entity: shared.PullRequests, IO: f.IOStreams, Query: search.Query{Kind: search.KindIssues, Qualifiers: search.Qualifiers{Type: "pr"}}, } cmd := &cobra.Command{ Use: "prs [<query>]", Short: "Search for pull requests", // TODO advancedIssueSearchCleanup // Update the links and remove the mention at GHES 3.17 version. Long: heredoc.Docf(` Search for pull requests on GitHub. The command supports constructing queries using the GitHub search syntax, using the parameter and qualifier flags, or a combination of the two. GitHub search syntax is documented at: <https://docs.github.com/search-github/searching-on-github/searching-issues-and-pull-requests> On supported GitHub hosts, advanced issue search syntax can be used in the %[1]s--search%[1]s query. For more information about advanced issue search, see: <https://docs.github.com/en/issues/tracking-your-work-with-issues/using-issues/filtering-and-searching-issues-and-pull-requests#building-advanced-filters-for-issues> For more information on handling search queries containing a hyphen, run %[1]sgh search --help%[1]s. `, "`"), Example: heredoc.Doc(` # Search pull requests matching set of keywords "fix" and "bug" $ gh search prs fix bug # Search draft pull requests in cli repository $ gh search prs --repo=cli/cli --draft # Search open pull requests requesting your review $ gh search prs --review-requested=@me --state=open # Search merged pull requests assigned to yourself $ gh search prs --assignee=@me --merged # Search pull requests with numerous reactions $ gh search prs --reactions=">100" # Search pull requests without label "bug" $ gh search prs -- -label:bug # Search pull requests only from un-archived repositories (default is all repositories) $ gh search prs --owner github --archived=false `), RunE: func(c *cobra.Command, args []string) error { if len(args) == 0 && c.Flags().NFlag() == 0 { return cmdutil.FlagErrorf("specify search keywords or flags") } if opts.Query.Limit < 1 || opts.Query.Limit > shared.SearchMaxResults { return cmdutil.FlagErrorf("`--limit` must be between 1 and 1000") } if c.Flags().Changed("author") && c.Flags().Changed("app") { return cmdutil.FlagErrorf("specify only `--author` or `--app`") } if c.Flags().Changed("app") { opts.Query.Qualifiers.Author = fmt.Sprintf("app/%s", appAuthor) } if c.Flags().Changed("order") { opts.Query.Order = order } if c.Flags().Changed("sort") { opts.Query.Sort = sort } if c.Flags().Changed("locked") && locked { if locked { opts.Query.Qualifiers.Is = append(opts.Query.Qualifiers.Is, "locked") } else { opts.Query.Qualifiers.Is = append(opts.Query.Qualifiers.Is, "unlocked") } } if c.Flags().Changed("merged") { if merged { opts.Query.Qualifiers.Is = append(opts.Query.Qualifiers.Is, "merged") } else { opts.Query.Qualifiers.Is = append(opts.Query.Qualifiers.Is, "unmerged") } } if c.Flags().Changed("no-assignee") && noAssignee { opts.Query.Qualifiers.No = append(opts.Query.Qualifiers.No, "assignee") } if c.Flags().Changed("no-label") && noLabel { opts.Query.Qualifiers.No = append(opts.Query.Qualifiers.No, "label") } if c.Flags().Changed("no-milestone") && noMilestone { opts.Query.Qualifiers.No = append(opts.Query.Qualifiers.No, "milestone") } if c.Flags().Changed("no-project") && noProject { opts.Query.Qualifiers.No = append(opts.Query.Qualifiers.No, "project") } if c.Flags().Changed("review-requested") { if strings.Contains(requestedReviewer, "/") { opts.Query.Qualifiers.TeamReviewRequested = requestedReviewer } else { opts.Query.Qualifiers.ReviewRequested = requestedReviewer } } opts.Query.Keywords = args if runF != nil { return runF(opts) } var err error opts.Searcher, err = shared.Searcher(f) if err != nil { return err } return shared.SearchIssues(opts) }, } // Output flags cmdutil.AddJSONFlags(cmd, &opts.Exporter, search.PullRequestFields) cmd.Flags().BoolVarP(&opts.WebMode, "web", "w", false, "Open the search query in the web browser") // Query parameter flags cmd.Flags().IntVarP(&opts.Query.Limit, "limit", "L", 30, "Maximum number of results to fetch") cmdutil.StringEnumFlag(cmd, &order, "order", "", "desc", []string{"asc", "desc"}, "Order of results returned, ignored unless '--sort' flag is specified") cmdutil.StringEnumFlag(cmd, &sort, "sort", "", "best-match", []string{ "comments", "reactions", "reactions-+1", "reactions--1", "reactions-smile", "reactions-thinking_face", "reactions-heart", "reactions-tada", "interactions", "created", "updated", }, "Sort fetched results") // Issue query qualifier flags cmd.Flags().StringVar(&appAuthor, "app", "", "Filter by GitHub App author") cmdutil.NilBoolFlag(cmd, &opts.Query.Qualifiers.Archived, "archived", "", "Filter based on the repository archived state {true|false}") cmd.Flags().StringVar(&opts.Query.Qualifiers.Assignee, "assignee", "", "Filter by assignee") cmd.Flags().StringVar(&opts.Query.Qualifiers.Author, "author", "", "Filter by author") cmd.Flags().StringVar(&opts.Query.Qualifiers.Closed, "closed", "", "Filter on closed at `date`") cmd.Flags().StringVar(&opts.Query.Qualifiers.Commenter, "commenter", "", "Filter based on comments by `user`") cmd.Flags().StringVar(&opts.Query.Qualifiers.Comments, "comments", "", "Filter on `number` of comments") cmd.Flags().StringVar(&opts.Query.Qualifiers.Created, "created", "", "Filter based on created at `date`") cmdutil.StringSliceEnumFlag(cmd, &opts.Query.Qualifiers.In, "match", "", nil, []string{"title", "body", "comments"}, "Restrict search to specific field of issue") cmd.Flags().StringVar(&opts.Query.Qualifiers.Interactions, "interactions", "", "Filter on `number` of reactions and comments") cmd.Flags().StringVar(&opts.Query.Qualifiers.Involves, "involves", "", "Filter based on involvement of `user`") cmdutil.StringSliceEnumFlag(cmd, &opts.Query.Qualifiers.Is, "visibility", "", nil, []string{"public", "private", "internal"}, "Filter based on repository visibility") cmd.Flags().StringSliceVar(&opts.Query.Qualifiers.Label, "label", nil, "Filter on label") cmd.Flags().StringVar(&opts.Query.Qualifiers.Language, "language", "", "Filter based on the coding language") cmd.Flags().BoolVar(&locked, "locked", false, "Filter on locked conversation status") cmd.Flags().StringVar(&opts.Query.Qualifiers.Mentions, "mentions", "", "Filter based on `user` mentions") cmd.Flags().StringVar(&opts.Query.Qualifiers.Milestone, "milestone", "", "Filter by milestone `title`") cmd.Flags().BoolVar(&noAssignee, "no-assignee", false, "Filter on missing assignee") cmd.Flags().BoolVar(&noLabel, "no-label", false, "Filter on missing label") cmd.Flags().BoolVar(&noMilestone, "no-milestone", false, "Filter on missing milestone") cmd.Flags().BoolVar(&noProject, "no-project", false, "Filter on missing project") cmd.Flags().StringVar(&opts.Query.Qualifiers.Project, "project", "", "Filter on project board `owner/number`") cmd.Flags().StringVar(&opts.Query.Qualifiers.Reactions, "reactions", "", "Filter on `number` of reactions") cmd.Flags().StringSliceVarP(&opts.Query.Qualifiers.Repo, "repo", "R", nil, "Filter on repository") cmdutil.StringEnumFlag(cmd, &opts.Query.Qualifiers.State, "state", "", "", []string{"open", "closed"}, "Filter based on state") cmd.Flags().StringVar(&opts.Query.Qualifiers.Team, "team-mentions", "", "Filter based on team mentions") cmd.Flags().StringVar(&opts.Query.Qualifiers.Updated, "updated", "", "Filter on last updated at `date`") cmd.Flags().StringSliceVar(&opts.Query.Qualifiers.User, "owner", nil, "Filter on repository owner") // Pull request query qualifier flags cmd.Flags().StringVarP(&opts.Query.Qualifiers.Base, "base", "B", "", "Filter on base branch name") cmdutil.NilBoolFlag(cmd, &opts.Query.Qualifiers.Draft, "draft", "", "Filter based on draft state") cmd.Flags().StringVarP(&opts.Query.Qualifiers.Head, "head", "H", "", "Filter on head branch name") cmd.Flags().StringVar(&opts.Query.Qualifiers.Merged, "merged-at", "", "Filter on merged at `date`") cmd.Flags().BoolVar(&merged, "merged", false, "Filter based on merged state") cmdutil.StringEnumFlag(cmd, &opts.Query.Qualifiers.Review, "review", "", "", []string{"none", "required", "approved", "changes_requested"}, "Filter based on review status") cmd.Flags().StringVar(&requestedReviewer, "review-requested", "", "Filter on `user` or team requested to review") cmd.Flags().StringVar(&opts.Query.Qualifiers.ReviewedBy, "reviewed-by", "", "Filter on `user` who reviewed") cmdutil.StringEnumFlag(cmd, &opts.Query.Qualifiers.Status, "checks", "", "", []string{"pending", "success", "failure"}, "Filter based on status of the checks") _ = cmdutil.RegisterBranchCompletionFlags(f.GitClient, cmd, "base", "head") return cmd }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/search/shared/shared_test.go
pkg/cmd/search/shared/shared_test.go
package shared import ( "fmt" "testing" "time" "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/cmd/factory" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/pkg/search" "github.com/stretchr/testify/assert" ) func TestSearcher(t *testing.T) { f := factory.New("1") f.Config = func() (gh.Config, error) { return config.NewBlankConfig(), nil } _, err := Searcher(f) assert.NoError(t, err) } func TestSearchIssues(t *testing.T) { var now = time.Date(2022, 2, 28, 12, 30, 0, 0, time.UTC) var updatedAt = time.Date(2021, 2, 28, 12, 30, 0, 0, time.UTC) var query = search.Query{ Keywords: []string{"keyword"}, Kind: "issues", Limit: 30, Qualifiers: search.Qualifiers{ Language: "go", Type: "issue", Is: []string{"public", "locked"}, }, } tests := []struct { errMsg string name string opts *IssuesOptions tty bool wantErr bool wantStderr string wantStdout string }{ { name: "displays results tty", opts: &IssuesOptions{ Entity: Issues, Query: query, Searcher: &search.SearcherMock{ IssuesFunc: func(query search.Query) (search.IssuesResult, error) { return search.IssuesResult{ IncompleteResults: false, Items: []search.Issue{ {RepositoryURL: "github.com/test/cli", Number: 123, StateInternal: "open", Title: "something broken", Labels: []search.Label{{Name: "bug"}, {Name: "p1"}}, UpdatedAt: updatedAt}, {RepositoryURL: "github.com/what/what", Number: 456, StateInternal: "closed", Title: "feature request", Labels: []search.Label{{Name: "enhancement"}}, UpdatedAt: updatedAt}, {RepositoryURL: "github.com/blah/test", Number: 789, StateInternal: "open", Title: "some title", UpdatedAt: updatedAt}, }, Total: 300, }, nil }, }, }, tty: true, wantStdout: "\nShowing 3 of 300 issues\n\nREPO ID TITLE LABELS UPDATED\ntest/cli #123 something broken bug, p1 about 1 year ago\nwhat/what #456 feature request enhancement about 1 year ago\nblah/test #789 some title about 1 year ago\n", }, { name: "displays issues and pull requests tty", opts: &IssuesOptions{ Entity: Both, Query: query, Searcher: &search.SearcherMock{ IssuesFunc: func(query search.Query) (search.IssuesResult, error) { return search.IssuesResult{ IncompleteResults: false, Items: []search.Issue{ {RepositoryURL: "github.com/test/cli", Number: 123, StateInternal: "open", Title: "bug", Labels: []search.Label{{Name: "bug"}, {Name: "p1"}}, UpdatedAt: updatedAt}, {RepositoryURL: "github.com/what/what", Number: 456, StateInternal: "open", Title: "fix bug", Labels: []search.Label{{Name: "fix"}}, PullRequest: search.PullRequest{URL: "someurl"}, UpdatedAt: updatedAt}, }, Total: 300, }, nil }, }, }, tty: true, wantStdout: "\nShowing 2 of 300 issues and pull requests\n\nKIND REPO ID TITLE LABELS UPDATED\nissue test/cli #123 bug bug, p1 about 1 year ago\npr what/what #456 fix bug fix about 1 year ago\n", }, { name: "displays results notty", opts: &IssuesOptions{ Entity: Issues, Query: query, Searcher: &search.SearcherMock{ IssuesFunc: func(query search.Query) (search.IssuesResult, error) { return search.IssuesResult{ IncompleteResults: false, Items: []search.Issue{ {RepositoryURL: "github.com/test/cli", Number: 123, StateInternal: "open", Title: "something broken", Labels: []search.Label{{Name: "bug"}, {Name: "p1"}}, UpdatedAt: updatedAt}, {RepositoryURL: "github.com/what/what", Number: 456, StateInternal: "closed", Title: "feature request", Labels: []search.Label{{Name: "enhancement"}}, UpdatedAt: updatedAt}, {RepositoryURL: "github.com/blah/test", Number: 789, StateInternal: "open", Title: "some title", UpdatedAt: updatedAt}, }, Total: 300, }, nil }, }, }, wantStdout: "test/cli\t123\topen\tsomething broken\tbug, p1\t2021-02-28T12:30:00Z\nwhat/what\t456\tclosed\tfeature request\tenhancement\t2021-02-28T12:30:00Z\nblah/test\t789\topen\tsome title\t\t2021-02-28T12:30:00Z\n", }, { name: "displays issues and pull requests notty", opts: &IssuesOptions{ Entity: Both, Query: query, Searcher: &search.SearcherMock{ IssuesFunc: func(query search.Query) (search.IssuesResult, error) { return search.IssuesResult{ IncompleteResults: false, Items: []search.Issue{ {RepositoryURL: "github.com/test/cli", Number: 123, StateInternal: "open", Title: "bug", Labels: []search.Label{{Name: "bug"}, {Name: "p1"}}, UpdatedAt: updatedAt}, {RepositoryURL: "github.com/what/what", Number: 456, StateInternal: "open", Title: "fix bug", Labels: []search.Label{{Name: "fix"}}, PullRequest: search.PullRequest{URL: "someurl"}, UpdatedAt: updatedAt}, }, Total: 300, }, nil }, }, }, wantStdout: "issue\ttest/cli\t123\topen\tbug\tbug, p1\t2021-02-28T12:30:00Z\npr\twhat/what\t456\topen\tfix bug\tfix\t2021-02-28T12:30:00Z\n", }, { name: "displays no results", opts: &IssuesOptions{ Entity: Issues, Query: query, Searcher: &search.SearcherMock{ IssuesFunc: func(query search.Query) (search.IssuesResult, error) { return search.IssuesResult{}, nil }, }, }, wantErr: true, errMsg: "no issues matched your search", }, { name: "displays search error", opts: &IssuesOptions{ Entity: Issues, Query: query, Searcher: &search.SearcherMock{ IssuesFunc: func(query search.Query) (search.IssuesResult, error) { return search.IssuesResult{}, fmt.Errorf("error with query") }, }, }, errMsg: "error with query", wantErr: true, }, { name: "opens browser for web mode tty", opts: &IssuesOptions{ Browser: &browser.Stub{}, Entity: Issues, Query: query, Searcher: &search.SearcherMock{ URLFunc: func(query search.Query) string { return "https://github.com/search?type=issues&q=cli" }, }, WebMode: true, }, tty: true, wantStderr: "Opening https://github.com/search in your browser.\n", }, { name: "opens browser for web mode notty", opts: &IssuesOptions{ Browser: &browser.Stub{}, Entity: Issues, Query: query, Searcher: &search.SearcherMock{ URLFunc: func(query search.Query) string { return "https://github.com/search?type=issues&q=cli" }, }, WebMode: true, }, }, } for _, tt := range tests { ios, _, stdout, stderr := iostreams.Test() ios.SetStdinTTY(tt.tty) ios.SetStdoutTTY(tt.tty) ios.SetStderrTTY(tt.tty) tt.opts.IO = ios tt.opts.Now = now t.Run(tt.name, func(t *testing.T) { err := SearchIssues(tt.opts) if tt.wantErr { assert.EqualError(t, err, tt.errMsg) return } else if err != nil { t.Fatalf("SearchIssues unexpected error: %v", 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/search/shared/shared.go
pkg/cmd/search/shared/shared.go
package shared import ( "fmt" "strconv" "strings" "time" "github.com/cli/cli/v2/internal/browser" fd "github.com/cli/cli/v2/internal/featuredetection" "github.com/cli/cli/v2/internal/tableprinter" "github.com/cli/cli/v2/internal/text" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/pkg/search" ) type EntityType int const ( // Limitation of GitHub search see: // https://docs.github.com/en/rest/reference/search SearchMaxResults = 1000 Both EntityType = iota Issues PullRequests ) type IssuesOptions struct { Browser browser.Browser Entity EntityType Exporter cmdutil.Exporter IO *iostreams.IOStreams Now time.Time Query search.Query Searcher search.Searcher WebMode bool } func Searcher(f *cmdutil.Factory) (search.Searcher, error) { cfg, err := f.Config() if err != nil { return nil, err } host, _ := cfg.Authentication().DefaultHost() client, err := f.HttpClient() if err != nil { return nil, err } detector := fd.NewDetector(client, host) return search.NewSearcher(client, host, detector), nil } func SearchIssues(opts *IssuesOptions) error { io := opts.IO if opts.WebMode { url := opts.Searcher.URL(opts.Query) if io.IsStdoutTTY() { fmt.Fprintf(io.ErrOut, "Opening %s in your browser.\n", text.DisplayURL(url)) } return opts.Browser.Browse(url) } io.StartProgressIndicator() result, err := opts.Searcher.Issues(opts.Query) io.StopProgressIndicator() if err != nil { return err } if len(result.Items) == 0 && opts.Exporter == nil { var msg string switch opts.Entity { case Both: msg = "no issues or pull requests matched your search" case Issues: msg = "no issues matched your search" case PullRequests: msg = "no pull requests matched your search" } return cmdutil.NewNoResultsError(msg) } if err := io.StartPager(); err == nil { defer io.StopPager() } else { fmt.Fprintf(io.ErrOut, "failed to start pager: %v\n", err) } if opts.Exporter != nil { return opts.Exporter.Write(io, result.Items) } return displayIssueResults(io, opts.Now, opts.Entity, result) } func displayIssueResults(io *iostreams.IOStreams, now time.Time, et EntityType, results search.IssuesResult) error { if now.IsZero() { now = time.Now() } var headers []string if et == Both { headers = []string{"Kind", "Repo", "ID", "Title", "Labels", "Updated"} } else { headers = []string{"Repo", "ID", "Title", "Labels", "Updated"} } cs := io.ColorScheme() tp := tableprinter.New(io, tableprinter.WithHeader(headers...)) for _, issue := range results.Items { if et == Both { kind := "issue" if issue.IsPullRequest() { kind = "pr" } tp.AddField(kind) } comp := strings.Split(issue.RepositoryURL, "/") name := comp[len(comp)-2:] tp.AddField(strings.Join(name, "/")) issueNum := strconv.Itoa(issue.Number) if tp.IsTTY() { issueNum = "#" + issueNum } if issue.IsPullRequest() { color := tableprinter.WithColor(cs.ColorFromString(colorForPRState(issue.State()))) tp.AddField(issueNum, color) } else { color := tableprinter.WithColor(cs.ColorFromString(colorForIssueState(issue.State(), issue.StateReason))) tp.AddField(issueNum, color) } if !tp.IsTTY() { tp.AddField(issue.State()) } tp.AddField(text.RemoveExcessiveWhitespace(issue.Title)) tp.AddField(listIssueLabels(&issue, cs, tp.IsTTY())) tp.AddTimeField(now, issue.UpdatedAt, cs.Muted) tp.EndRow() } if tp.IsTTY() { var header string switch et { case Both: header = fmt.Sprintf("Showing %d of %d issues and pull requests\n\n", len(results.Items), results.Total) case Issues: header = fmt.Sprintf("Showing %d of %d issues\n\n", len(results.Items), results.Total) case PullRequests: header = fmt.Sprintf("Showing %d of %d pull requests\n\n", len(results.Items), results.Total) } fmt.Fprintf(io.Out, "\n%s", header) } return tp.Render() } func listIssueLabels(issue *search.Issue, cs *iostreams.ColorScheme, colorize bool) string { if len(issue.Labels) == 0 { return "" } labelNames := make([]string, 0, len(issue.Labels)) for _, label := range issue.Labels { if colorize { labelNames = append(labelNames, cs.Label(label.Color, label.Name)) } else { labelNames = append(labelNames, label.Name) } } return strings.Join(labelNames, ", ") } func colorForIssueState(state, reason string) string { switch state { case "open": return "green" case "closed": if reason == "not_planned" { return "gray" } return "magenta" default: return "" } } func colorForPRState(state string) string { switch state { case "open": return "green" case "closed": return "red" case "merged": return "magenta" default: return "" } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/status/status.go
pkg/cmd/status/status.go
package status import ( "bytes" "context" "errors" "fmt" "net/http" "net/url" "sort" "strings" "sync" "time" "github.com/MakeNowJust/heredoc" "github.com/charmbracelet/lipgloss" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/tableprinter" "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/set" ghAPI "github.com/cli/go-gh/v2/pkg/api" "github.com/spf13/cobra" "golang.org/x/sync/errgroup" ) type hostConfig interface { DefaultHost() (string, string) } type StatusOptions struct { HttpClient func() (*http.Client, error) HostConfig hostConfig CachedClient func(*http.Client, time.Duration) *http.Client IO *iostreams.IOStreams Org string Exclude []string } func NewCmdStatus(f *cmdutil.Factory, runF func(*StatusOptions) error) *cobra.Command { opts := &StatusOptions{ CachedClient: func(c *http.Client, ttl time.Duration) *http.Client { return api.NewCachedHTTPClient(c, ttl) }, } opts.HttpClient = f.HttpClient opts.IO = f.IOStreams cmd := &cobra.Command{ Use: "status", Short: "Print information about relevant issues, pull requests, and notifications across repositories", Long: heredoc.Doc(` The status command prints information about your work on GitHub across all the repositories you're subscribed to, including: - Assigned Issues - Assigned Pull Requests - Review Requests - Mentions - Repository Activity (new issues/pull requests, comments) `), Example: heredoc.Doc(` $ gh status -e cli/cli -e cli/go-gh # Exclude multiple repositories $ gh status -o cli # Limit results to a single organization `), RunE: func(cmd *cobra.Command, args []string) error { cfg, err := f.Config() if err != nil { return err } opts.HostConfig = cfg.Authentication() if runF != nil { return runF(opts) } return statusRun(opts) }, } cmd.Flags().StringVarP(&opts.Org, "org", "o", "", "Report status within an organization") cmd.Flags().StringSliceVarP(&opts.Exclude, "exclude", "e", []string{}, "Comma separated list of repos to exclude in owner/name format") return cmd } type Notification struct { Reason string Subject struct { Title string LatestCommentURL string `json:"latest_comment_url"` URL string Type string } Repository struct { Owner struct { Login string } FullName string `json:"full_name"` } index int } type StatusItem struct { Repository string // owner/repo Identifier string // eg cli/cli#1234 or just 1234 preview string // eg This is the truncated body of something... Reason string // only used in repo activity index int } func (s StatusItem) Preview() string { return strings.ReplaceAll(strings.ReplaceAll(s.preview, "\r", ""), "\n", " ") } type IssueOrPR struct { Number int Title string } type Event struct { Type string Org struct { Login string } CreatedAt time.Time `json:"created_at"` Repo struct { Name string // owner/repo } Payload struct { Action string Issue IssueOrPR PullRequest IssueOrPR `json:"pull_request"` Comment struct { Body string HTMLURL string `json:"html_url"` } } } type SearchResult struct { Type string `json:"__typename"` UpdatedAt time.Time Title string Number int Repository struct { NameWithOwner string } } type Results []SearchResult func (rs Results) Len() int { return len(rs) } func (rs Results) Less(i, j int) bool { return rs[i].UpdatedAt.After(rs[j].UpdatedAt) } func (rs Results) Swap(i, j int) { rs[i], rs[j] = rs[j], rs[i] } type stringSet interface { Len() int Add(string) ToSlice() []string } type StatusGetter struct { Client *http.Client cachedClient func(*http.Client, time.Duration) *http.Client host string Org string Exclude []string AssignedPRs []StatusItem AssignedIssues []StatusItem Mentions []StatusItem ReviewRequests []StatusItem RepoActivity []StatusItem authErrors stringSet authErrorsMu sync.Mutex currentUsername string usernameMu sync.Mutex } func NewStatusGetter(client *http.Client, hostname string, opts *StatusOptions) *StatusGetter { return &StatusGetter{ Client: client, Org: opts.Org, Exclude: opts.Exclude, cachedClient: opts.CachedClient, host: hostname, } } func (s *StatusGetter) hostname() string { return s.host } func (s *StatusGetter) CachedClient(ttl time.Duration) *http.Client { return s.cachedClient(s.Client, ttl) } func (s *StatusGetter) ShouldExclude(repo string) bool { for _, exclude := range s.Exclude { if repo == exclude { return true } } return false } func (s *StatusGetter) CurrentUsername() (string, error) { s.usernameMu.Lock() defer s.usernameMu.Unlock() if s.currentUsername != "" { return s.currentUsername, nil } cachedClient := s.CachedClient(time.Hour * 48) cachingAPIClient := api.NewClientFromHTTP(cachedClient) currentUsername, err := api.CurrentLoginName(cachingAPIClient, s.hostname()) if err != nil { return "", fmt.Errorf("failed to get current username: %w", err) } s.currentUsername = currentUsername return currentUsername, nil } func (s *StatusGetter) ActualMention(commentURL string) (string, error) { currentUsername, err := s.CurrentUsername() if err != nil { return "", err } // long cache period since once a comment is looked up, it never needs to be // consulted again. cachedClient := s.CachedClient(time.Hour * 24 * 30) c := api.NewClientFromHTTP(cachedClient) resp := struct { Body string }{} if err := c.REST(s.hostname(), "GET", commentURL, nil, &resp); err != nil { return "", err } if strings.Contains(resp.Body, "@"+currentUsername) { return resp.Body, nil } return "", nil } // These are split up by endpoint since it is along that boundary we parallelize // work // Populate .Mentions func (s *StatusGetter) LoadNotifications() error { perPage := 100 c := api.NewClientFromHTTP(s.Client) query := url.Values{} query.Add("per_page", fmt.Sprintf("%d", perPage)) query.Add("participating", "true") query.Add("all", "true") fetchWorkers := 10 ctx, abortFetching := context.WithCancel(context.Background()) defer abortFetching() toFetch := make(chan Notification) fetched := make(chan StatusItem) wg := new(errgroup.Group) for i := 0; i < fetchWorkers; i++ { wg.Go(func() error { for { select { case <-ctx.Done(): return nil case n, ok := <-toFetch: if !ok { return nil } actual, err := s.ActualMention(n.Subject.LatestCommentURL) if err != nil { var httpErr api.HTTPError httpStatusCode := -1 if errors.As(err, &httpErr) { httpStatusCode = httpErr.StatusCode } switch httpStatusCode { case 403: s.addAuthError(httpErr.Message, factory.SSOURL()) case 404: return nil default: abortFetching() return fmt.Errorf("could not fetch comment: %w", err) } } if actual != "" { // I'm so sorry split := strings.Split(n.Subject.URL, "/") fetched <- StatusItem{ Repository: n.Repository.FullName, Identifier: fmt.Sprintf("%s#%s", n.Repository.FullName, split[len(split)-1]), preview: actual, index: n.index, } } } } }) } doneCh := make(chan struct{}) go func() { for item := range fetched { s.Mentions = append(s.Mentions, item) } close(doneCh) }() // this sucks, having to fetch so much :/ but it was the only way in my // testing to really get enough mentions. I would love to be able to just // filter for mentions but it does not seem like the notifications API can // do that. I'd switch to the GraphQL version, but to my knowledge that does // not work with PATs right now. nIndex := 0 p := fmt.Sprintf("notifications?%s", query.Encode()) for pages := 0; pages < 3; pages++ { var resp []Notification next, err := c.RESTWithNext(s.hostname(), "GET", p, nil, &resp) if err != nil { var httpErr api.HTTPError if !errors.As(err, &httpErr) || httpErr.StatusCode != 404 { return fmt.Errorf("could not get notifications: %w", err) } } for _, n := range resp { if n.Reason != "mention" { continue } if s.Org != "" && n.Repository.Owner.Login != s.Org { continue } if s.ShouldExclude(n.Repository.FullName) { continue } n.index = nIndex nIndex++ toFetch <- n } if next == "" || len(resp) < perPage { break } p = next } close(toFetch) err := wg.Wait() close(fetched) <-doneCh sort.Slice(s.Mentions, func(i, j int) bool { return s.Mentions[i].index < s.Mentions[j].index }) return err } const searchQuery = ` fragment issue on Issue { __typename updatedAt title number repository { nameWithOwner } } fragment pr on PullRequest { __typename updatedAt title number repository { nameWithOwner } } query AssignedSearch($searchAssigns: String!, $searchReviews: String!, $limit: Int = 25) { assignments: search(first: $limit, type: ISSUE, query: $searchAssigns) { nodes { ...issue ...pr } } reviewRequested: search(first: $limit, type: ISSUE, query: $searchReviews) { nodes { ...pr } } }` // Populate .AssignedPRs, .AssignedIssues, .ReviewRequests func (s *StatusGetter) LoadSearchResults() error { c := api.NewClientFromHTTP(s.Client) searchAssigns := `assignee:@me state:open archived:false` searchReviews := `review-requested:@me state:open archived:false` if s.Org != "" { searchAssigns += " org:" + s.Org searchReviews += " org:" + s.Org } for _, repo := range s.Exclude { searchAssigns += " -repo:" + repo searchReviews += " -repo:" + repo } variables := map[string]interface{}{ "searchAssigns": searchAssigns, "searchReviews": searchReviews, } var resp struct { Assignments struct { Nodes []*SearchResult } ReviewRequested struct { Nodes []*SearchResult } } err := c.GraphQL(s.hostname(), searchQuery, variables, &resp) if err != nil { var gqlErrResponse api.GraphQLError if errors.As(err, &gqlErrResponse) { gqlErrors := make([]ghAPI.GraphQLErrorItem, 0, len(gqlErrResponse.Errors)) // Exclude any FORBIDDEN errors and show status for what we can. for _, gqlErr := range gqlErrResponse.Errors { if gqlErr.Type == "FORBIDDEN" { s.addAuthError(gqlErr.Message, factory.SSOURL()) } else { gqlErrors = append(gqlErrors, gqlErr) } } if len(gqlErrors) == 0 { err = nil } else { err = api.GraphQLError{ GraphQLError: &ghAPI.GraphQLError{ Errors: gqlErrors, }, } } } if err != nil { return fmt.Errorf("could not search for assignments: %w", err) } } prs := []SearchResult{} issues := []SearchResult{} reviewRequested := []SearchResult{} for _, node := range resp.Assignments.Nodes { if node == nil { continue // likely due to FORBIDDEN results } switch node.Type { case "Issue": issues = append(issues, *node) case "PullRequest": prs = append(prs, *node) default: return fmt.Errorf("unknown Assignments type: %q", node.Type) } } for _, node := range resp.ReviewRequested.Nodes { if node == nil { continue // likely due to FORBIDDEN results } reviewRequested = append(reviewRequested, *node) } sort.Sort(Results(issues)) sort.Sort(Results(prs)) sort.Sort(Results(reviewRequested)) s.AssignedIssues = []StatusItem{} s.AssignedPRs = []StatusItem{} s.ReviewRequests = []StatusItem{} for _, i := range issues { s.AssignedIssues = append(s.AssignedIssues, StatusItem{ Repository: i.Repository.NameWithOwner, Identifier: fmt.Sprintf("%s#%d", i.Repository.NameWithOwner, i.Number), preview: i.Title, }) } for _, pr := range prs { s.AssignedPRs = append(s.AssignedPRs, StatusItem{ Repository: pr.Repository.NameWithOwner, Identifier: fmt.Sprintf("%s#%d", pr.Repository.NameWithOwner, pr.Number), preview: pr.Title, }) } for _, r := range reviewRequested { s.ReviewRequests = append(s.ReviewRequests, StatusItem{ Repository: r.Repository.NameWithOwner, Identifier: fmt.Sprintf("%s#%d", r.Repository.NameWithOwner, r.Number), preview: r.Title, }) } return nil } // Populate .RepoActivity func (s *StatusGetter) LoadEvents() error { perPage := 100 c := api.NewClientFromHTTP(s.Client) query := url.Values{} query.Add("per_page", fmt.Sprintf("%d", perPage)) currentUsername, err := s.CurrentUsername() if err != nil { return err } var events []Event var resp []Event pages := 0 p := fmt.Sprintf("users/%s/received_events?%s", currentUsername, query.Encode()) for pages < 2 { next, err := c.RESTWithNext(s.hostname(), "GET", p, nil, &resp) if err != nil { var httpErr api.HTTPError if !errors.As(err, &httpErr) || httpErr.StatusCode != 404 { return fmt.Errorf("could not get events: %w", err) } } events = append(events, resp...) if next == "" || len(resp) < perPage { break } pages++ p = next } s.RepoActivity = []StatusItem{} for _, e := range events { if s.Org != "" && e.Org.Login != s.Org { continue } if s.ShouldExclude(e.Repo.Name) { continue } si := StatusItem{} var number int switch e.Type { case "IssuesEvent": if e.Payload.Action != "opened" { continue } si.Reason = "new issue" si.preview = e.Payload.Issue.Title number = e.Payload.Issue.Number case "PullRequestEvent": if e.Payload.Action != "opened" { continue } si.Reason = "new PR" si.preview = e.Payload.PullRequest.Title number = e.Payload.PullRequest.Number case "PullRequestReviewCommentEvent": si.Reason = "comment on " + e.Payload.PullRequest.Title si.preview = e.Payload.Comment.Body number = e.Payload.PullRequest.Number case "IssueCommentEvent": si.Reason = "comment on " + e.Payload.Issue.Title si.preview = e.Payload.Comment.Body number = e.Payload.Issue.Number default: continue } si.Repository = e.Repo.Name si.Identifier = fmt.Sprintf("%s#%d", e.Repo.Name, number) s.RepoActivity = append(s.RepoActivity, si) } return nil } func (s *StatusGetter) addAuthError(msg, ssoURL string) { s.authErrorsMu.Lock() defer s.authErrorsMu.Unlock() if s.authErrors == nil { s.authErrors = set.NewStringSet() } if ssoURL != "" { s.authErrors.Add(fmt.Sprintf("%s\nAuthorize in your web browser: %s", msg, ssoURL)) } else { s.authErrors.Add(msg) } } func (s *StatusGetter) HasAuthErrors() bool { s.authErrorsMu.Lock() defer s.authErrorsMu.Unlock() return s.authErrors != nil && s.authErrors.Len() > 0 } func statusRun(opts *StatusOptions) error { client, err := opts.HttpClient() if err != nil { return fmt.Errorf("could not create client: %w", err) } hostname, _ := opts.HostConfig.DefaultHost() sg := NewStatusGetter(client, hostname, opts) // TODO break out sections into individual subcommands g := new(errgroup.Group) g.Go(func() error { if err := sg.LoadNotifications(); err != nil { return fmt.Errorf("could not load notifications: %w", err) } return nil }) g.Go(func() error { if err := sg.LoadEvents(); err != nil { return fmt.Errorf("could not load events: %w", err) } return nil }) g.Go(func() error { if err := sg.LoadSearchResults(); err != nil { return fmt.Errorf("failed to search: %w", err) } return nil }) opts.IO.StartProgressIndicator() err = g.Wait() opts.IO.StopProgressIndicator() if err != nil { return err } cs := opts.IO.ColorScheme() out := opts.IO.Out fullWidth := opts.IO.TerminalWidth() halfWidth := (fullWidth / 2) - 2 idStyle := cs.Cyan leftHalfStyle := lipgloss.NewStyle().Width(halfWidth).Padding(0).MarginRight(1).BorderRight(true).BorderStyle(lipgloss.NormalBorder()) rightHalfStyle := lipgloss.NewStyle().Width(halfWidth).Padding(0) section := func(header string, items []StatusItem, width, rowLimit int) (string, error) { tableOut := &bytes.Buffer{} fmt.Fprintln(tableOut, cs.Bold(header)) if len(items) == 0 { fmt.Fprintln(tableOut, "Nothing here ^_^") } else { //nolint:staticcheck // SA1019: Headers distract from numerous nested tables. tp := tableprinter.NewWithWriter(tableOut, opts.IO.IsStdoutTTY(), width, cs, tableprinter.NoHeader) for i, si := range items { if i == rowLimit { break } tp.AddField(si.Identifier, tableprinter.WithColor(idStyle), tableprinter.WithTruncate(nil)) if si.Reason != "" { tp.AddField(si.Reason) } tp.AddField(si.Preview()) tp.EndRow() } err := tp.Render() if err != nil { return "", err } } return tableOut.String(), nil } mSection, err := section("Mentions", sg.Mentions, halfWidth, 5) if err != nil { return fmt.Errorf("failed to render 'Mentions': %w", err) } mSection = rightHalfStyle.Render(mSection) rrSection, err := section("Review Requests", sg.ReviewRequests, halfWidth, 5) if err != nil { return fmt.Errorf("failed to render 'Review Requests': %w", err) } rrSection = leftHalfStyle.Render(rrSection) prSection, err := section("Assigned Pull Requests", sg.AssignedPRs, halfWidth, 5) if err != nil { return fmt.Errorf("failed to render 'Assigned Pull Requests': %w", err) } prSection = rightHalfStyle.Render(prSection) issueSection, err := section("Assigned Issues", sg.AssignedIssues, halfWidth, 5) if err != nil { return fmt.Errorf("failed to render 'Assigned Issues': %w", err) } issueSection = leftHalfStyle.Render(issueSection) raSection, err := section("Repository Activity", sg.RepoActivity, fullWidth, 10) if err != nil { return fmt.Errorf("failed to render 'Repository Activity': %w", err) } fmt.Fprintln(out, lipgloss.JoinHorizontal(lipgloss.Top, issueSection, prSection)) fmt.Fprintln(out, lipgloss.JoinHorizontal(lipgloss.Top, rrSection, mSection)) fmt.Fprintln(out, raSection) if sg.HasAuthErrors() { errs := sg.authErrors.ToSlice() sort.Strings(errs) for _, msg := range errs { fmt.Fprintln(out, cs.Mutedf("warning: %s", msg)) } } return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/status/status_test.go
pkg/cmd/status/status_test.go
package status import ( "bytes" "io" "net/http" "strings" "testing" "time" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/config" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" ) type testHostConfig string func (c testHostConfig) DefaultHost() (string, string) { return string(c), "" } func TestNewCmdStatus(t *testing.T) { tests := []struct { name string cli string wants StatusOptions }{ { name: "defaults", }, { name: "org", cli: "-o cli", wants: StatusOptions{ Org: "cli", }, }, { name: "exclude", cli: "-e cli/cli,cli/go-gh", wants: StatusOptions{ Exclude: []string{"cli/cli", "cli/go-gh"}, }, }, } for _, tt := range tests { ios, _, _, _ := iostreams.Test() ios.SetStdinTTY(true) ios.SetStdoutTTY(true) if tt.wants.Exclude == nil { tt.wants.Exclude = []string{} } f := &cmdutil.Factory{ IOStreams: ios, Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, } t.Run(tt.name, func(t *testing.T) { argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts *StatusOptions cmd := NewCmdStatus(f, func(opts *StatusOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) _, err = cmd.ExecuteC() assert.NoError(t, err) assert.Equal(t, tt.wants.Org, gotOpts.Org) assert.Equal(t, tt.wants.Exclude, gotOpts.Exclude) }) } } func TestStatusRun(t *testing.T) { tests := []struct { name string httpStubs func(*httpmock.Registry) opts *StatusOptions wantOut string wantErrMsg string }{ { name: "nothing", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL("UserCurrent"), httpmock.StringResponse(`{"data": {"viewer": {"login": "jillvalentine"}}}`)) reg.Register( httpmock.GraphQL("AssignedSearch"), httpmock.StringResponse(`{"data": { "assignments": {"nodes": [] }, "reviewRequested": {"nodes": []}}}`)) reg.Register( httpmock.REST("GET", "notifications"), httpmock.StringResponse(`[]`)) reg.Register( httpmock.REST("GET", "users/jillvalentine/received_events"), httpmock.StringResponse(`[]`)) }, opts: &StatusOptions{}, wantOut: "Assigned Issues │ Assigned Pull Requests \nNothing here ^_^ │ Nothing here ^_^ \n │ \nReview Requests │ Mentions \nNothing here ^_^ │ Nothing here ^_^ \n │ \nRepository Activity\nNothing here ^_^\n\n", }, { name: "something", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL("UserCurrent"), httpmock.StringResponse(`{"data": {"viewer": {"login": "jillvalentine"}}}`)) reg.Register( httpmock.REST("GET", "repos/rpd/todo/issues/110"), httpmock.StringResponse(`{"body":"hello @jillvalentine how are you"}`)) reg.Register( httpmock.REST("GET", "repos/rpd/todo/issues/4113"), httpmock.StringResponse(`{"body":"this is a comment"}`)) reg.Register( httpmock.REST("GET", "repos/cli/cli/issues/1096"), httpmock.StringResponse(`{"body":"@jillvalentine hi"}`)) reg.Register( httpmock.REST("GET", "repos/rpd/todo/issues/comments/1065"), httpmock.StringResponse(`{"body":"not a real mention"}`)) reg.Register( httpmock.REST("GET", "repos/vilmibm/gh-screensaver/issues/comments/10"), httpmock.StringResponse(`{"body":"a message for @jillvalentine"}`)) reg.Register( httpmock.GraphQL("AssignedSearch"), httpmock.FileResponse("./fixtures/search.json")) reg.Register( httpmock.REST("GET", "notifications"), httpmock.FileResponse("./fixtures/notifications.json")) reg.Register( httpmock.REST("GET", "users/jillvalentine/received_events"), httpmock.FileResponse("./fixtures/events.json")) }, opts: &StatusOptions{}, wantOut: "Assigned Issues │ Assigned Pull Requests \nvilmibm/testing#157 yolo │ cli/cli#5272 Pin extensions \ncli/cli#3223 Repo garden...│ rpd/todo#73 Board up RPD windows \nrpd/todo#514 Reducing zo...│ cli/cli#4768 Issue Frecency \nvilmibm/testing#74 welp │ \nadreyer/arkestrator#22 complete mo...│ \n │ \nReview Requests │ Mentions \ncli/cli#5272 Pin extensions │ rpd/todo#110 hello @j...\nvilmibm/testing#1234 Foobar │ cli/cli#1096 @jillval...\nrpd/todo#50 Welcome party...│ vilmibm/gh-screensaver#15 a messag...\ncli/cli#4671 This pull req...│ \nrpd/todo#49 Haircut for Leon│ \n │ \nRepository Activity\nrpd/todo#5326 new PR Only write UTF-8 BOM on W...\nvilmibm/testing#5325 comment on Ability to sea... We are working on dedicat...\ncli/cli#5319 comment on [Codespaces] D... Wondering if we shouldn't...\ncli/cli#5300 new issue Terminal bell when a runn...\n\n", }, { name: "exclude a repository", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL("UserCurrent"), httpmock.StringResponse(`{"data": {"viewer": {"login": "jillvalentine"}}}`)) reg.Register( httpmock.REST("GET", "repos/rpd/todo/issues/110"), httpmock.StringResponse(`{"body":"hello @jillvalentine how are you"}`)) reg.Register( httpmock.REST("GET", "repos/rpd/todo/issues/4113"), httpmock.StringResponse(`{"body":"this is a comment"}`)) reg.Register( httpmock.REST("GET", "repos/rpd/todo/issues/comments/1065"), httpmock.StringResponse(`{"body":"not a real mention"}`)) reg.Register( httpmock.REST("GET", "repos/vilmibm/gh-screensaver/issues/comments/10"), httpmock.StringResponse(`{"body":"a message for @jillvalentine"}`)) reg.Register( httpmock.GraphQL("AssignedSearch"), httpmock.FileResponse("./fixtures/search.json")) reg.Register( httpmock.REST("GET", "notifications"), httpmock.FileResponse("./fixtures/notifications.json")) reg.Register( httpmock.REST("GET", "users/jillvalentine/received_events"), httpmock.FileResponse("./fixtures/events.json")) }, opts: &StatusOptions{ Exclude: []string{"cli/cli"}, }, // NOTA BENE: you'll see cli/cli in search results because that happens // server side and the fixture doesn't account for that wantOut: "Assigned Issues │ Assigned Pull Requests \nvilmibm/testing#157 yolo │ cli/cli#5272 Pin extensions \ncli/cli#3223 Repo garden...│ rpd/todo#73 Board up RPD windows \nrpd/todo#514 Reducing zo...│ cli/cli#4768 Issue Frecency \nvilmibm/testing#74 welp │ \nadreyer/arkestrator#22 complete mo...│ \n │ \nReview Requests │ Mentions \ncli/cli#5272 Pin extensions │ rpd/todo#110 hello @j...\nvilmibm/testing#1234 Foobar │ vilmibm/gh-screensaver#15 a messag...\nrpd/todo#50 Welcome party...│ \ncli/cli#4671 This pull req...│ \nrpd/todo#49 Haircut for Leon│ \n │ \nRepository Activity\nrpd/todo#5326 new PR Only write UTF-8 BOM on W...\nvilmibm/testing#5325 comment on Ability to sea... We are working on dedicat...\n\n", }, { name: "exclude repositories", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL("UserCurrent"), httpmock.StringResponse(`{"data": {"viewer": {"login": "jillvalentine"}}}`)) reg.Register( httpmock.REST("GET", "repos/vilmibm/gh-screensaver/issues/comments/10"), httpmock.StringResponse(`{"body":"a message for @jillvalentine"}`)) reg.Register( httpmock.GraphQL("AssignedSearch"), httpmock.FileResponse("./fixtures/search.json")) reg.Register( httpmock.REST("GET", "notifications"), httpmock.FileResponse("./fixtures/notifications.json")) reg.Register( httpmock.REST("GET", "users/jillvalentine/received_events"), httpmock.FileResponse("./fixtures/events.json")) }, opts: &StatusOptions{ Exclude: []string{"cli/cli", "rpd/todo"}, }, // NOTA BENE: you'll see cli/cli in search results because that happens // server side and the fixture doesn't account for that wantOut: "Assigned Issues │ Assigned Pull Requests \nvilmibm/testing#157 yolo │ cli/cli#5272 Pin extensions \ncli/cli#3223 Repo garden...│ rpd/todo#73 Board up RPD windows \nrpd/todo#514 Reducing zo...│ cli/cli#4768 Issue Frecency \nvilmibm/testing#74 welp │ \nadreyer/arkestrator#22 complete mo...│ \n │ \nReview Requests │ Mentions \ncli/cli#5272 Pin extensions │ vilmibm/gh-screensaver#15 a messag...\nvilmibm/testing#1234 Foobar │ \nrpd/todo#50 Welcome party...│ \ncli/cli#4671 This pull req...│ \nrpd/todo#49 Haircut for Leon│ \n │ \nRepository Activity\nvilmibm/testing#5325 comment on Ability to sea... We are working on dedicat...\n\n", }, { name: "filter to an org", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL("UserCurrent"), httpmock.StringResponse(`{"data": {"viewer": {"login": "jillvalentine"}}}`)) reg.Register( httpmock.REST("GET", "repos/rpd/todo/issues/110"), httpmock.StringResponse(`{"body":"hello @jillvalentine how are you"}`)) reg.Register( httpmock.REST("GET", "repos/rpd/todo/issues/4113"), httpmock.StringResponse(`{"body":"this is a comment"}`)) reg.Register( httpmock.REST("GET", "repos/rpd/todo/issues/comments/1065"), httpmock.StringResponse(`{"body":"not a real mention"}`)) reg.Register( httpmock.GraphQL("AssignedSearch"), httpmock.FileResponse("./fixtures/search.json")) reg.Register( httpmock.REST("GET", "notifications"), httpmock.FileResponse("./fixtures/notifications.json")) reg.Register( httpmock.REST("GET", "users/jillvalentine/received_events"), httpmock.FileResponse("./fixtures/events.json")) }, opts: &StatusOptions{ Org: "rpd", }, wantOut: "Assigned Issues │ Assigned Pull Requests \nvilmibm/testing#157 yolo │ cli/cli#5272 Pin extensions \ncli/cli#3223 Repo garden...│ rpd/todo#73 Board up RPD windows \nrpd/todo#514 Reducing zo...│ cli/cli#4768 Issue Frecency \nvilmibm/testing#74 welp │ \nadreyer/arkestrator#22 complete mo...│ \n │ \nReview Requests │ Mentions \ncli/cli#5272 Pin extensions │ rpd/todo#110 hello @jillvalentine ...\nvilmibm/testing#1234 Foobar │ \nrpd/todo#50 Welcome party...│ \ncli/cli#4671 This pull req...│ \nrpd/todo#49 Haircut for Leon│ \n │ \nRepository Activity\nrpd/todo#5326 new PR Only write UTF-8 BOM on Windows where it is needed\n\n", }, { name: "forbidden errors", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL("UserCurrent"), httpmock.StringResponse(`{"data": {"viewer": {"login": "jillvalentine"}}}`)) reg.Register( httpmock.REST("GET", "repos/rpd/todo/issues/110"), func(req *http.Request) (*http.Response, error) { return &http.Response{ Request: req, StatusCode: 403, Body: io.NopCloser(strings.NewReader(`{"message": "You don't have permission to access this resource."}`)), Header: http.Header{ "Content-Type": []string{"application/json"}, "X-Github-Sso": []string{"required; url=http://click.me/auth"}, }, }, nil }) reg.Register( httpmock.REST("GET", "repos/rpd/todo/issues/4113"), httpmock.StringResponse(`{"body":"this is a comment"}`)) reg.Register( httpmock.REST("GET", "repos/cli/cli/issues/1096"), httpmock.StringResponse(`{"body":"@jillvalentine hi"}`)) reg.Register( httpmock.REST("GET", "repos/rpd/todo/issues/comments/1065"), httpmock.StringResponse(`{"body":"not a real mention"}`)) reg.Register( httpmock.REST("GET", "repos/vilmibm/gh-screensaver/issues/comments/10"), httpmock.StringResponse(`{"body":"a message for @jillvalentine"}`)) reg.Register( httpmock.GraphQL("AssignedSearch"), httpmock.FileResponse("./fixtures/search_forbidden.json")) reg.Register( httpmock.REST("GET", "notifications"), httpmock.FileResponse("./fixtures/notifications.json")) reg.Register( httpmock.REST("GET", "users/jillvalentine/received_events"), httpmock.FileResponse("./fixtures/events.json")) }, opts: &StatusOptions{}, wantOut: heredoc.Doc(` Assigned Issues │ Assigned Pull Requests vilmibm/testing#157 yolo │ cli/cli#5272 Pin extensions │ Review Requests │ Mentions cli/cli#5272 Pin extensions │ cli/cli#1096 @jillval... │ vilmibm/gh-screensaver#15 a messag... Repository Activity rpd/todo#5326 new PR Only write UTF-8 BOM on W... vilmibm/testing#5325 comment on Ability to sea... We are working on dedicat... cli/cli#5319 comment on [Codespaces] D... Wondering if we shouldn't... cli/cli#5300 new issue Terminal bell when a runn... warning: Resource protected by organization SAML enforcement. You must grant your OAuth token access to this organization. warning: You don't have permission to access this resource. `), }, { name: "not found errors", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL("UserCurrent"), httpmock.StringResponse(`{"data": {"viewer": {"login": "jillvalentine"}}}`)) reg.Register( httpmock.REST("GET", "repos/rpd/todo/issues/110"), httpmock.StringResponse(`{"body":"hello @jillvalentine how are you"}`)) reg.Register( httpmock.REST("GET", "repos/rpd/todo/issues/4113"), httpmock.StringResponse(`{"body":"this is a comment"}`)) reg.Register( httpmock.REST("GET", "repos/cli/cli/issues/1096"), httpmock.StringResponse(`{"body":"@jillvalentine hi"}`)) reg.Register( httpmock.REST("GET", "repos/rpd/todo/issues/comments/1065"), httpmock.StatusStringResponse(404, `{ "message": "Not Found." }`)) reg.Register( httpmock.REST("GET", "repos/vilmibm/gh-screensaver/issues/comments/10"), httpmock.StringResponse(`{"body":"a message for @jillvalentine"}`)) reg.Register( httpmock.GraphQL("AssignedSearch"), httpmock.FileResponse("./fixtures/search.json")) reg.Register( httpmock.REST("GET", "notifications"), httpmock.FileResponse("./fixtures/notifications.json")) reg.Register( httpmock.REST("GET", "users/jillvalentine/received_events"), httpmock.FileResponse("./fixtures/events.json")) }, opts: &StatusOptions{}, wantOut: heredoc.Doc(` Assigned Issues │ Assigned Pull Requests vilmibm/testing#157 yolo │ cli/cli#5272 Pin extensions cli/cli#3223 Repo garden...│ rpd/todo#73 Board up RPD windows rpd/todo#514 Reducing zo...│ cli/cli#4768 Issue Frecency vilmibm/testing#74 welp │ adreyer/arkestrator#22 complete mo...│ │ Review Requests │ Mentions cli/cli#5272 Pin extensions │ rpd/todo#110 hello @j... vilmibm/testing#1234 Foobar │ cli/cli#1096 @jillval... rpd/todo#50 Welcome party...│ vilmibm/gh-screensaver#15 a messag... cli/cli#4671 This pull req...│ rpd/todo#49 Haircut for Leon│ │ Repository Activity rpd/todo#5326 new PR Only write UTF-8 BOM on W... vilmibm/testing#5325 comment on Ability to sea... We are working on dedicat... cli/cli#5319 comment on [Codespaces] D... Wondering if we shouldn't... cli/cli#5300 new issue Terminal bell when a runn... `), }, { name: "notification errors", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL("UserCurrent"), httpmock.StringResponse(`{"data": {"viewer": {"login": "jillvalentine"}}}`)) reg.Register( httpmock.REST("GET", "repos/rpd/todo/issues/110"), httpmock.StatusStringResponse(429, `{ "message": "Too many requests." }`)) reg.Register( httpmock.GraphQL("AssignedSearch"), httpmock.StringResponse(`{"data": { "assignments": {"nodes": [] }, "reviewRequested": {"nodes": []}}}`)) reg.Register( httpmock.REST("GET", "notifications"), httpmock.StringResponse(`[ { "reason": "mention", "subject": { "title": "Good", "url": "https://api.github.com/repos/rpd/todo/issues/110", "latest_comment_url": "https://api.github.com/repos/rpd/todo/issues/110", "type": "Issue" }, "repository": { "full_name": "rpd/todo", "owner": { "login": "rpd" } } } ]`)) reg.Register( httpmock.REST("GET", "users/jillvalentine/received_events"), httpmock.StringResponse(`[]`)) }, opts: &StatusOptions{}, wantErrMsg: "could not load notifications: could not fetch comment: HTTP 429 (https://api.github.com/repos/rpd/todo/issues/110)", }, { name: "search errors", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL("UserCurrent"), httpmock.StringResponse(`{"data": {"viewer": {"login": "jillvalentine"}}}`)) reg.Register( httpmock.GraphQL("AssignedSearch"), httpmock.StringResponse(`{ "data": { "assignments": { "nodes": [ null ] } }, "errors": [ { "type": "NOT FOUND", "path": [ "assignments", "nodes", 0 ], "message": "Not found." } ] }`)) reg.Register( httpmock.REST("GET", "notifications"), httpmock.StringResponse(`[]`)) reg.Register( httpmock.REST("GET", "users/jillvalentine/received_events"), httpmock.StringResponse(`[]`)) }, opts: &StatusOptions{}, wantErrMsg: "failed to search: could not search for assignments: GraphQL: Not found. (assignments.nodes.0)", }, } for _, tt := range tests { reg := &httpmock.Registry{} tt.httpStubs(reg) tt.opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } tt.opts.CachedClient = func(c *http.Client, _ time.Duration) *http.Client { return c } tt.opts.HostConfig = testHostConfig("github.com") ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(true) tt.opts.IO = ios t.Run(tt.name, func(t *testing.T) { err := statusRun(tt.opts) if tt.wantErrMsg != "" { assert.Equal(t, tt.wantErrMsg, err.Error()) return } assert.NoError(t, err) assert.Equal(t, tt.wantOut, stdout.String()) reg.Verify(t) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/gist/gist.go
pkg/cmd/gist/gist.go
package gist import ( "github.com/MakeNowJust/heredoc" gistCloneCmd "github.com/cli/cli/v2/pkg/cmd/gist/clone" gistCreateCmd "github.com/cli/cli/v2/pkg/cmd/gist/create" gistDeleteCmd "github.com/cli/cli/v2/pkg/cmd/gist/delete" gistEditCmd "github.com/cli/cli/v2/pkg/cmd/gist/edit" gistListCmd "github.com/cli/cli/v2/pkg/cmd/gist/list" gistRenameCmd "github.com/cli/cli/v2/pkg/cmd/gist/rename" gistViewCmd "github.com/cli/cli/v2/pkg/cmd/gist/view" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/spf13/cobra" ) func NewCmdGist(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "gist <command>", Short: "Manage gists", Long: `Work with GitHub gists.`, Annotations: map[string]string{ "help:arguments": heredoc.Doc(` A gist can be supplied as argument in either of the following formats: - by ID, e.g. 5b0e0062eb8e9654adad7bb1d81cc75f - by URL, e.g. "https://gist.github.com/OWNER/5b0e0062eb8e9654adad7bb1d81cc75f" `), }, GroupID: "core", } cmd.AddCommand(gistCloneCmd.NewCmdClone(f, nil)) cmd.AddCommand(gistCreateCmd.NewCmdCreate(f, nil)) cmd.AddCommand(gistListCmd.NewCmdList(f, nil)) cmd.AddCommand(gistViewCmd.NewCmdView(f, nil)) cmd.AddCommand(gistEditCmd.NewCmdEdit(f, nil)) cmd.AddCommand(gistDeleteCmd.NewCmdDelete(f, nil)) cmd.AddCommand(gistRenameCmd.NewCmdRename(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/gist/delete/delete.go
pkg/cmd/gist/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/gh" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/pkg/cmd/gist/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type DeleteOptions struct { IO *iostreams.IOStreams Config func() (gh.Config, error) HttpClient func() (*http.Client, error) Prompter prompter.Prompter Selector string Confirmed bool } func NewCmdDelete(f *cmdutil.Factory, runF func(*DeleteOptions) error) *cobra.Command { opts := DeleteOptions{ IO: f.IOStreams, Config: f.Config, HttpClient: f.HttpClient, Prompter: f.Prompter, } cmd := &cobra.Command{ Use: "delete {<id> | <url>}", Short: "Delete a gist", Long: heredoc.Docf(` Delete a GitHub gist. To delete a gist interactively, use %[1]sgh gist delete%[1]s with no arguments. To delete a gist non-interactively, supply the gist id or url. `, "`"), Example: heredoc.Doc(` # Delete a gist interactively $ gh gist delete # Delete a gist non-interactively $ gh gist delete 1234 `), Args: cobra.MaximumNArgs(1), RunE: func(c *cobra.Command, args []string) error { if !opts.IO.CanPrompt() && !opts.Confirmed { return cmdutil.FlagErrorf("--yes required when not running interactively") } if !opts.IO.CanPrompt() && len(args) == 0 { return cmdutil.FlagErrorf("id or url argument required in non-interactive mode") } if len(args) == 1 { opts.Selector = args[0] } 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 { client, err := opts.HttpClient() if err != nil { return err } cfg, err := opts.Config() if err != nil { return err } host, _ := cfg.Authentication().DefaultHost() gistID := opts.Selector if strings.Contains(gistID, "/") { id, err := shared.GistIDFromURL(gistID) if err != nil { return err } gistID = id } cs := opts.IO.ColorScheme() var gist *shared.Gist if gistID == "" { gist, err = shared.PromptGists(opts.Prompter, client, host, cs) } else { gist, err = shared.GetGist(client, host, gistID) } if err != nil { return err } if gist.ID == "" { fmt.Fprintln(opts.IO.Out, "No gists found.") return nil } if !opts.Confirmed { confirmed, err := opts.Prompter.Confirm(fmt.Sprintf("Delete %q gist?", gist.Filename()), false) if err != nil { return err } if !confirmed { return cmdutil.CancelError } } apiClient := api.NewClientFromHTTP(client) if err := deleteGist(apiClient, host, gist.ID); err != nil { if errors.Is(err, shared.NotFoundErr) { return fmt.Errorf("unable to delete gist %q: either the gist is not found or it is not owned by you", gist.Filename()) } return err } if opts.IO.IsStdoutTTY() { cs := opts.IO.ColorScheme() fmt.Fprintf(opts.IO.Out, "%s Gist %q deleted\n", cs.SuccessIcon(), gist.Filename()) } return nil } func deleteGist(apiClient *api.Client, hostname string, gistID string) error { path := "gists/" + gistID err := apiClient.REST(hostname, "DELETE", path, nil, nil) if err != nil { var httpErr api.HTTPError if errors.As(err, &httpErr) && httpErr.StatusCode == 404 { return shared.NotFoundErr } 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/gist/delete/delete_test.go
pkg/cmd/gist/delete/delete_test.go
package delete import ( "bytes" "fmt" "net/http" "testing" "time" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/config" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/pkg/cmd/gist/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" ghAPI "github.com/cli/go-gh/v2/pkg/api" "github.com/google/shlex" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNewCmdDelete(t *testing.T) { tests := []struct { name string cli string tty bool want DeleteOptions wantErr bool wantErrMsg string }{ { name: "valid selector", cli: "123", tty: true, want: DeleteOptions{ Selector: "123", }, }, { name: "valid selector, no ID supplied", cli: "", tty: true, want: DeleteOptions{ Selector: "", }, }, { name: "no ID supplied with --yes", cli: "--yes", tty: true, want: DeleteOptions{ Selector: "", }, }, { name: "selector with --yes, no tty", cli: "123 --yes", tty: false, want: DeleteOptions{ Selector: "123", }, }, { name: "ID arg without --yes, no tty", cli: "123", tty: false, want: DeleteOptions{ Selector: "", }, wantErr: true, wantErrMsg: "--yes required when not running interactively", }, { name: "no ID supplied with --yes, no tty", cli: "--yes", tty: false, want: DeleteOptions{ Selector: "", }, wantErr: true, wantErrMsg: "id or url argument required in non-interactive mode", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { io, _, _, _ := iostreams.Test() f := &cmdutil.Factory{ IOStreams: io, } io.SetStdinTTY(tt.tty) io.SetStdoutTTY(tt.tty) argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts *DeleteOptions cmd := NewCmdDelete(f, func(opts *DeleteOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err = cmd.ExecuteC() if tt.wantErr { assert.EqualError(t, err, tt.wantErrMsg) return } assert.NoError(t, err) assert.Equal(t, tt.want.Selector, gotOpts.Selector) }) } } func Test_deleteRun(t *testing.T) { tests := []struct { name string opts *DeleteOptions cancel bool httpStubs func(*httpmock.Registry) mockPromptGists bool noGists bool wantErr bool wantStdout string wantStderr string }{ { name: "successfully delete", opts: &DeleteOptions{ Selector: "1234", }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("GET", "gists/1234"), httpmock.JSONResponse(shared.Gist{ID: "1234", Files: map[string]*shared.GistFile{"cool.txt": {Filename: "cool.txt"}}})) reg.Register(httpmock.REST("DELETE", "gists/1234"), httpmock.StatusStringResponse(200, "{}")) }, wantStdout: "✓ Gist \"cool.txt\" deleted\n", }, { name: "successfully delete with prompt", opts: &DeleteOptions{ Selector: "", }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("DELETE", "gists/1234"), httpmock.StatusStringResponse(200, "{}")) }, mockPromptGists: true, wantStdout: "✓ Gist \"cool.txt\" deleted\n", }, { name: "successfully delete with --yes", opts: &DeleteOptions{ Selector: "1234", Confirmed: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("GET", "gists/1234"), httpmock.JSONResponse(shared.Gist{ID: "1234", Files: map[string]*shared.GistFile{"cool.txt": {Filename: "cool.txt"}}})) reg.Register(httpmock.REST("DELETE", "gists/1234"), httpmock.StatusStringResponse(200, "{}")) }, wantStdout: "✓ Gist \"cool.txt\" deleted\n", }, { name: "successfully delete with prompt and --yes", opts: &DeleteOptions{ Selector: "", Confirmed: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("DELETE", "gists/1234"), httpmock.StatusStringResponse(200, "{}")) }, mockPromptGists: true, wantStdout: "✓ Gist \"cool.txt\" deleted\n", }, { name: "cancel delete with id", opts: &DeleteOptions{ Selector: "1234", }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("GET", "gists/1234"), httpmock.JSONResponse(shared.Gist{ID: "1234", Files: map[string]*shared.GistFile{"cool.txt": {Filename: "cool.txt"}}})) }, cancel: true, wantErr: true, }, { name: "cancel delete with url", opts: &DeleteOptions{ Selector: "https://gist.github.com/myrepo/1234", }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("GET", "gists/1234"), httpmock.JSONResponse(shared.Gist{ID: "1234", Files: map[string]*shared.GistFile{"cool.txt": {Filename: "cool.txt"}}})) }, cancel: true, wantErr: true, }, { name: "cancel delete with prompt", opts: &DeleteOptions{ Selector: "", }, httpStubs: func(reg *httpmock.Registry) {}, mockPromptGists: true, cancel: true, wantErr: true, }, { name: "not owned by you", opts: &DeleteOptions{ Selector: "1234", }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("GET", "gists/1234"), httpmock.JSONResponse(shared.Gist{ID: "1234", Files: map[string]*shared.GistFile{"cool.txt": {Filename: "cool.txt"}}})) reg.Register(httpmock.REST("DELETE", "gists/1234"), httpmock.StatusStringResponse(404, "{}")) }, wantErr: true, wantStderr: "unable to delete gist \"cool.txt\": either the gist is not found or it is not owned by you", }, { name: "not found", opts: &DeleteOptions{ Selector: "1234", }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("GET", "gists/1234"), httpmock.StatusStringResponse(404, "{}")) }, wantErr: true, wantStderr: "not found", }, { name: "no gists", opts: &DeleteOptions{ Selector: "", }, httpStubs: func(reg *httpmock.Registry) {}, mockPromptGists: true, noGists: true, wantStdout: "No gists found.\n", }, } for _, tt := range tests { pm := prompter.NewMockPrompter(t) if !tt.opts.Confirmed { pm.RegisterConfirm("Delete \"cool.txt\" gist?", func(_ string, _ bool) (bool, error) { return !tt.cancel, nil }) } reg := &httpmock.Registry{} tt.httpStubs(reg) if tt.mockPromptGists { if tt.noGists { reg.Register( httpmock.GraphQL(`query GistList\b`), httpmock.StringResponse( `{ "data": { "viewer": { "gists": { "nodes": [] }} } }`), ) } else { sixHours, _ := time.ParseDuration("6h") sixHoursAgo := time.Now().Add(-sixHours) reg.Register( httpmock.GraphQL(`query GistList\b`), httpmock.StringResponse(fmt.Sprintf( `{ "data": { "viewer": { "gists": { "nodes": [ { "name": "1234", "files": [{ "name": "cool.txt" }], "updatedAt": "%s", "isPublic": true } ] } } } }`, sixHoursAgo.Format(time.RFC3339), )), ) pm.RegisterSelect("Select a gist", []string{"cool.txt about 6 hours ago"}, func(_, _ string, _ []string) (int, error) { return 0, nil }) } } tt.opts.Prompter = pm tt.opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } tt.opts.Config = func() (gh.Config, error) { return config.NewBlankConfig(), nil } ios, _, stdout, stderr := iostreams.Test() ios.SetStdoutTTY(true) ios.SetStdinTTY(false) tt.opts.IO = ios t.Run(tt.name, func(t *testing.T) { err := deleteRun(tt.opts) reg.Verify(t) if tt.wantErr { assert.Error(t, err) if tt.wantStderr != "" { assert.EqualError(t, err, tt.wantStderr) } return } assert.NoError(t, err) assert.Equal(t, tt.wantStdout, stdout.String()) assert.Equal(t, tt.wantStderr, stderr.String()) }) } } func Test_gistDelete(t *testing.T) { tests := []struct { name string httpStubs func(*httpmock.Registry) hostname string gistID string wantErr error wantErrString string }{ { name: "successful delete", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("DELETE", "gists/1234"), httpmock.StatusStringResponse(204, "{}"), ) }, hostname: "github.com", gistID: "1234", }, { name: "when a gist is not found, it returns a NotFoundError", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("DELETE", "gists/1234"), httpmock.StatusStringResponse(404, "{}"), ) }, hostname: "github.com", gistID: "1234", wantErr: shared.NotFoundErr, // To make sure we return the pre-defined error instance. wantErrString: "not found", }, { name: "when there is a non-404 error deleting the gist, that error is returned", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("DELETE", "gists/1234"), httpmock.JSONErrorResponse(500, ghAPI.HTTPError{ StatusCode: 500, Message: "arbitrary error", }), ) }, hostname: "github.com", gistID: "1234", wantErrString: "HTTP 500: arbitrary error (https://api.github.com/gists/1234)", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { reg := &httpmock.Registry{} tt.httpStubs(reg) client := api.NewClientFromHTTP(&http.Client{Transport: reg}) err := deleteGist(client, tt.hostname, tt.gistID) if tt.wantErrString == "" && tt.wantErr == nil { require.NoError(t, err) } else { if tt.wantErrString != "" { require.EqualError(t, err, tt.wantErrString) } if tt.wantErr != nil { require.ErrorIs(t, err, tt.wantErr) } } }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/gist/list/list_test.go
pkg/cmd/gist/list/list_test.go
package list import ( "bytes" "fmt" "net/http" "regexp" "testing" "time" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/config" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" ) func TestNewCmdList(t *testing.T) { tests := []struct { name string cli string wants ListOptions wantsErr bool }{ { name: "no arguments", wants: ListOptions{ Limit: 10, Visibility: "all", }, }, { name: "public", cli: "--public", wants: ListOptions{ Limit: 10, Visibility: "public", }, }, { name: "secret", cli: "--secret", wants: ListOptions{ Limit: 10, Visibility: "secret", }, }, { name: "secret with explicit false value", cli: "--secret=false", wants: ListOptions{ Limit: 10, Visibility: "all", }, }, { name: "public and secret", cli: "--secret --public", wants: ListOptions{ Limit: 10, Visibility: "secret", }, }, { name: "limit", cli: "--limit 30", wants: ListOptions{ Limit: 30, Visibility: "all", }, }, { name: "invalid limit", cli: "--limit 0", wantsErr: true, }, { name: "filter and include-content", cli: "--filter octo --include-content", wants: ListOptions{ Limit: 10, Filter: regexp.MustCompilePOSIX("octo"), IncludeContent: true, Visibility: "all", }, }, { name: "invalid filter", cli: "--filter octo(", wantsErr: true, }, { name: "include content without filter", cli: "--include-content", wantsErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { f := &cmdutil.Factory{} argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts *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.Error(t, err) return } assert.NoError(t, err) assert.Equal(t, tt.wants.Visibility, gotOpts.Visibility) assert.Equal(t, tt.wants.Limit, gotOpts.Limit) }) } } func Test_listRun(t *testing.T) { const query = `query GistList\b` sixHours, _ := time.ParseDuration("6h") sixHoursAgo := time.Now().Add(-sixHours) absTime, _ := time.Parse(time.RFC3339, "2020-07-30T15:24:28Z") tests := []struct { name string opts *ListOptions wantErr bool wantOut string stubs func(*httpmock.Registry) color bool nontty bool }{ { name: "no gists", opts: &ListOptions{}, stubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(query), httpmock.StringResponse(`{ "data": { "viewer": { "gists": { "nodes": [] } } } }`)) }, wantErr: true, }, { name: "default behavior", opts: &ListOptions{}, stubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(query), httpmock.StringResponse(fmt.Sprintf( `{ "data": { "viewer": { "gists": { "nodes": [ { "name": "1234567890", "files": [{ "name": "cool.txt" }], "description": "", "updatedAt": "%[1]v", "isPublic": true }, { "name": "4567890123", "files": [{ "name": "gistfile0.txt" }], "description": "", "updatedAt": "%[1]v", "isPublic": true }, { "name": "2345678901", "files": [ { "name": "gistfile0.txt" }, { "name": "gistfile1.txt" } ], "description": "tea leaves thwart those who court catastrophe", "updatedAt": "%[1]v", "isPublic": false }, { "name": "3456789012", "files": [ { "name": "gistfile0.txt" }, { "name": "gistfile1.txt" }, { "name": "gistfile2.txt" }, { "name": "gistfile3.txt" }, { "name": "gistfile4.txt" }, { "name": "gistfile5.txt" }, { "name": "gistfile6.txt" }, { "name": "gistfile7.txt" }, { "name": "gistfile9.txt" }, { "name": "gistfile10.txt" }, { "name": "gistfile11.txt" } ], "description": "short desc", "updatedAt": "%[1]v", "isPublic": false } ] } } } }`, sixHoursAgo.Format(time.RFC3339), )), ) }, wantOut: heredoc.Doc(` ID DESCRIPTION FILES VISIBILITY UPDATED 1234567890 cool.txt 1 file public about 6 hours ago 4567890123 1 file public about 6 hours ago 2345678901 tea leaves thwart those ... 2 files secret about 6 hours ago 3456789012 short desc 11 files secret about 6 hours ago `), }, { name: "with public filter", opts: &ListOptions{Visibility: "public"}, stubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(query), httpmock.StringResponse(fmt.Sprintf( `{ "data": { "viewer": { "gists": { "nodes": [ { "name": "1234567890", "files": [{ "name": "cool.txt" }], "description": "", "updatedAt": "%[1]v", "isPublic": true }, { "name": "4567890123", "files": [{ "name": "gistfile0.txt" }], "description": "", "updatedAt": "%[1]v", "isPublic": true } ] } } } }`, sixHoursAgo.Format(time.RFC3339), )), ) }, wantOut: heredoc.Doc(` ID DESCRIPTION FILES VISIBILITY UPDATED 1234567890 cool.txt 1 file public about 6 hours ago 4567890123 1 file public about 6 hours ago `), }, { name: "with secret filter", opts: &ListOptions{Visibility: "secret"}, stubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(query), httpmock.StringResponse(fmt.Sprintf( `{ "data": { "viewer": { "gists": { "nodes": [ { "name": "2345678901", "files": [ { "name": "gistfile0.txt" }, { "name": "gistfile1.txt" } ], "description": "tea leaves thwart those who court catastrophe", "updatedAt": "%[1]v", "isPublic": false }, { "name": "3456789012", "files": [ { "name": "gistfile0.txt" }, { "name": "gistfile1.txt" }, { "name": "gistfile2.txt" }, { "name": "gistfile3.txt" }, { "name": "gistfile4.txt" }, { "name": "gistfile5.txt" }, { "name": "gistfile6.txt" }, { "name": "gistfile7.txt" }, { "name": "gistfile9.txt" }, { "name": "gistfile10.txt" }, { "name": "gistfile11.txt" } ], "description": "short desc", "updatedAt": "%[1]v", "isPublic": false } ] } } } }`, sixHoursAgo.Format(time.RFC3339), )), ) }, wantOut: heredoc.Doc(` ID DESCRIPTION FILES VISIBILITY UPDATED 2345678901 tea leaves thwart those ... 2 files secret about 6 hours ago 3456789012 short desc 11 files secret about 6 hours ago `), }, { name: "with limit", opts: &ListOptions{Limit: 1}, stubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(query), httpmock.StringResponse(fmt.Sprintf( `{ "data": { "viewer": { "gists": { "nodes": [ { "name": "1234567890", "files": [{ "name": "cool.txt" }], "description": "", "updatedAt": "%v", "isPublic": true } ] } } } }`, sixHoursAgo.Format(time.RFC3339), )), ) }, wantOut: heredoc.Doc(` ID DESCRIPTION FILES VISIBILITY UPDATED 1234567890 cool.txt 1 file public about 6 hours ago `), }, { name: "nontty output", opts: &ListOptions{}, stubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(query), httpmock.StringResponse(fmt.Sprintf( `{ "data": { "viewer": { "gists": { "nodes": [ { "name": "1234567890", "files": [{ "name": "cool.txt" }], "description": "", "updatedAt": "%[1]v", "isPublic": true }, { "name": "4567890123", "files": [{ "name": "gistfile0.txt" }], "description": "", "updatedAt": "%[1]v", "isPublic": true }, { "name": "2345678901", "files": [ { "name": "gistfile0.txt" }, { "name": "gistfile1.txt" } ], "description": "tea leaves thwart those who court catastrophe", "updatedAt": "%[1]v", "isPublic": false }, { "name": "3456789012", "files": [ { "name": "gistfile0.txt" }, { "name": "gistfile1.txt" }, { "name": "gistfile2.txt" }, { "name": "gistfile3.txt" }, { "name": "gistfile4.txt" }, { "name": "gistfile5.txt" }, { "name": "gistfile6.txt" }, { "name": "gistfile7.txt" }, { "name": "gistfile9.txt" }, { "name": "gistfile10.txt" }, { "name": "gistfile11.txt" } ], "description": "short desc", "updatedAt": "%[1]v", "isPublic": false } ] } } } }`, absTime.Format(time.RFC3339), )), ) }, wantOut: heredoc.Doc(` 1234567890 cool.txt 1 file public 2020-07-30T15:24:28Z 4567890123 1 file public 2020-07-30T15:24:28Z 2345678901 tea leaves thwart those who court catastrophe 2 files secret 2020-07-30T15:24:28Z 3456789012 short desc 11 files secret 2020-07-30T15:24:28Z `), nontty: true, }, { name: "filtered", opts: &ListOptions{ Filter: regexp.MustCompile("octo"), Visibility: "all", }, nontty: true, stubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(query), httpmock.StringResponse(fmt.Sprintf( `{ "data": { "viewer": { "gists": { "nodes": [ { "name": "1234", "files": [ { "name": "main.txt", "text": "foo" } ], "description": "octo match in the description", "updatedAt": "%[1]v", "isPublic": true }, { "name": "2345", "files": [ { "name": "main.txt", "text": "foo" }, { "name": "octo.txt", "text": "bar" } ], "description": "match in the file name", "updatedAt": "%[1]v", "isPublic": false }, { "name": "3456", "files": [ { "name": "main.txt", "text": "octo in the text" } ], "description": "match in the file text", "updatedAt": "%[1]v", "isPublic": true } ] } } } }`, absTime.Format(time.RFC3339), )), ) }, wantOut: heredoc.Docf(` 1234%[1]socto match in the description%[1]s1 file%[1]spublic%[1]s2020-07-30T15:24:28Z 2345%[1]smatch in the file name%[1]s2 files%[1]ssecret%[1]s2020-07-30T15:24:28Z `, "\t"), }, { name: "filtered (tty)", opts: &ListOptions{ Filter: regexp.MustCompile("octo"), Visibility: "all", }, color: true, stubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(query), httpmock.StringResponse(fmt.Sprintf( `{ "data": { "viewer": { "gists": { "nodes": [ { "name": "1234", "files": [ { "name": "main.txt", "text": "foo" } ], "description": "octo match in the description", "updatedAt": "%[1]v", "isPublic": true }, { "name": "2345", "files": [ { "name": "main.txt", "text": "foo" }, { "name": "octo.txt", "text": "bar" } ], "description": "match in the file name", "updatedAt": "%[1]v", "isPublic": false }, { "name": "3456", "files": [ { "name": "main.txt", "text": "octo in the text" } ], "description": "match in the file text", "updatedAt": "%[1]v", "isPublic": true } ] } } } }`, sixHoursAgo.Format(time.RFC3339), )), ) }, wantOut: heredoc.Docf(` %[1]s[0;4;39mID %[1]s[0m %[1]s[0;4;39mDESCRIPTION %[1]s[0m %[1]s[0;4;39mFILES %[1]s[0m %[1]s[0;4;39mVISIBILITY%[1]s[0m %[1]s[0;4;39mUPDATED %[1]s[0m 1234 %[1]s[0;30;43mocto%[1]s[0m%[1]s[0;1;39m match in the description%[1]s[0m 1 file %[1]s[0;32mpublic %[1]s[0m %[1]s[38;5;242mabout 6 hours ago%[1]s[0m 2345 %[1]s[0;1;39mmatch in the file name %[1]s[0m %[1]s[0;30;43m2 files%[1]s[0m %[1]s[0;31msecret %[1]s[0m %[1]s[38;5;242mabout 6 hours ago%[1]s[0m `, "\x1b"), }, { name: "filtered with content", opts: &ListOptions{ Filter: regexp.MustCompile("octo"), IncludeContent: true, Visibility: "all", }, nontty: true, stubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(query), httpmock.StringResponse(fmt.Sprintf( `{ "data": { "viewer": { "gists": { "nodes": [ { "name": "1234", "files": [ { "name": "main.txt", "text": "foo" } ], "description": "octo match in the description", "updatedAt": "%[1]v", "isPublic": true }, { "name": "2345", "files": [ { "name": "main.txt", "text": "foo" }, { "name": "octo.txt", "text": "bar" } ], "description": "match in the file name", "updatedAt": "%[1]v", "isPublic": false }, { "name": "3456", "files": [ { "name": "main.txt", "text": "octo in the text" } ], "description": "match in the file text", "updatedAt": "%[1]v", "isPublic": true } ] } } } }`, absTime.Format(time.RFC3339), )), ) }, wantOut: heredoc.Doc(` 1234 main.txt octo match in the description 2345 octo.txt match in the file name 3456 main.txt match in the file text octo in the text `), }, { name: "filtered with content (tty)", opts: &ListOptions{ Filter: regexp.MustCompile("octo"), IncludeContent: true, Visibility: "all", }, color: true, stubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(query), httpmock.StringResponse(fmt.Sprintf( `{ "data": { "viewer": { "gists": { "nodes": [ { "name": "1234", "files": [ { "name": "main.txt", "text": "foo" } ], "description": "octo match in the description", "updatedAt": "%[1]v", "isPublic": true }, { "name": "2345", "files": [ { "name": "main.txt", "text": "foo" }, { "name": "octo.txt", "text": "bar" } ], "description": "match in the file name", "updatedAt": "%[1]v", "isPublic": false }, { "name": "3456", "files": [ { "name": "main.txt", "text": "octo in the text" } ], "description": "match in the file text", "updatedAt": "%[1]v", "isPublic": true } ] } } } }`, sixHoursAgo.Format(time.RFC3339), )), ) }, wantOut: heredoc.Docf(` %[1]s[0;34m1234%[1]s[0m %[1]s[0;32mmain.txt%[1]s[0m %[1]s[0;30;43mocto%[1]s[0m%[1]s[0;1;39m match in the description%[1]s[0m %[1]s[0;34m2345%[1]s[0m %[1]s[0;30;43mocto%[1]s[0m%[1]s[0;32m.txt%[1]s[0m %[1]s[0;1;39mmatch in the file name%[1]s[0m %[1]s[0;34m3456%[1]s[0m %[1]s[0;32mmain.txt%[1]s[0m %[1]s[0;1;39mmatch in the file text%[1]s[0m %[1]s[0;30;43mocto%[1]s[0m in the text `, "\x1b"), }, } for _, tt := range tests { reg := &httpmock.Registry{} tt.stubs(reg) tt.opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } tt.opts.Config = func() (gh.Config, error) { return config.NewBlankConfig(), nil } ios, _, stdout, _ := iostreams.Test() ios.SetColorEnabled(tt.color) ios.SetStdoutTTY(!tt.nontty) tt.opts.IO = ios if tt.opts.Limit == 0 { tt.opts.Limit = 10 } if tt.opts.Visibility == "" { tt.opts.Visibility = "all" } t.Run(tt.name, func(t *testing.T) { err := listRun(tt.opts) if tt.wantErr { assert.Error(t, err) } else { assert.NoError(t, err) } assert.Equal(t, tt.wantOut, stdout.String()) reg.Verify(t) }) } } func Test_highlightMatch(t *testing.T) { regex := regexp.MustCompilePOSIX(`[Oo]cto`) tests := []struct { name string input string cs *iostreams.ColorScheme want string }{ { name: "single match", input: "Octo", cs: &iostreams.ColorScheme{}, want: "Octo", }, { name: "single match (color)", input: "Octo", cs: &iostreams.ColorScheme{ Enabled: true, }, want: "\x1b[0;30;43mOcto\x1b[0m", }, { name: "single match with extra", input: "Hello, Octocat!", cs: &iostreams.ColorScheme{}, want: "Hello, Octocat!", }, { name: "single match with extra (color)", input: "Hello, Octocat!", cs: &iostreams.ColorScheme{ Enabled: true, }, want: "\x1b[0;34mHello, \x1b[0m\x1b[0;30;43mOcto\x1b[0m\x1b[0;34mcat!\x1b[0m", }, { name: "multiple matches", input: "Octocat/octo", cs: &iostreams.ColorScheme{}, want: "Octocat/octo", }, { name: "multiple matches (color)", input: "Octocat/octo", cs: &iostreams.ColorScheme{ Enabled: true, }, want: "\x1b[0;30;43mOcto\x1b[0m\x1b[0;34mcat/\x1b[0m\x1b[0;30;43mocto\x1b[0m", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { matched := false got, err := highlightMatch(tt.input, regex, &matched, tt.cs.Blue, tt.cs.Highlight) assert.NoError(t, err) assert.True(t, matched) 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/gist/list/list.go
pkg/cmd/gist/list/list.go
package list import ( "fmt" "net/http" "regexp" "strings" "time" "github.com/MakeNowJust/heredoc" "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/cmd/gist/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type ListOptions struct { IO *iostreams.IOStreams Config func() (gh.Config, error) HttpClient func() (*http.Client, error) Limit int Filter *regexp.Regexp IncludeContent bool Visibility string // all, secret, public } func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Command { opts := &ListOptions{ IO: f.IOStreams, Config: f.Config, HttpClient: f.HttpClient, } var flagPublic bool var flagSecret bool var flagFilter string cmd := &cobra.Command{ Use: "list", Short: "List your gists", Long: heredoc.Docf(` List gists from your user account. You can use a regular expression to filter the description, file names, or even the content of files in the gist using %[1]s--filter%[1]s. For supported regular expression syntax, see <https://pkg.go.dev/regexp/syntax>. Use %[1]s--include-content%[1]s to include content of files, noting that this will be slower and increase the rate limit used. Instead of printing a table, code will be printed with highlights similar to %[1]sgh search code%[1]s: {{gist ID}} {{file name}} {{description}} {{matching lines from content}} No highlights or other color is printed when output is redirected. `, "`"), Example: heredoc.Doc(` # List all secret gists from your user account $ gh gist list --secret # Find all gists from your user account mentioning "octo" anywhere $ gh gist list --filter octo --include-content `), Aliases: []string{"ls"}, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { if opts.Limit < 1 { return cmdutil.FlagErrorf("invalid limit: %v", opts.Limit) } if flagFilter == "" { if opts.IncludeContent { return cmdutil.FlagErrorf("cannot use --include-content without --filter") } } else { if filter, err := regexp.CompilePOSIX(flagFilter); err != nil { return err } else { opts.Filter = filter } } opts.Visibility = "all" if flagSecret { opts.Visibility = "secret" } else if flagPublic { opts.Visibility = "public" } if runF != nil { return runF(opts) } return listRun(opts) }, } cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 10, "Maximum number of gists to fetch") cmd.Flags().BoolVar(&flagPublic, "public", false, "Show only public gists") cmd.Flags().BoolVar(&flagSecret, "secret", false, "Show only secret gists") cmd.Flags().StringVar(&flagFilter, "filter", "", "Filter gists using a regular `expression`") cmd.Flags().BoolVar(&opts.IncludeContent, "include-content", false, "Include gists' file content when filtering") 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 } host, _ := cfg.Authentication().DefaultHost() // Filtering can take a while so start the progress indicator. StopProgressIndicator will no-op if not running. if opts.Filter != nil { opts.IO.StartProgressIndicator() } gists, err := shared.ListGists(client, host, opts.Limit, opts.Filter, opts.IncludeContent, opts.Visibility) opts.IO.StopProgressIndicator() if err != nil { return err } if len(gists) == 0 { return cmdutil.NewNoResultsError("no gists found") } if err := opts.IO.StartPager(); err == nil { defer opts.IO.StopPager() } else { fmt.Fprintf(opts.IO.ErrOut, "failed to start pager: %v\n", err) } if opts.Filter != nil && opts.IncludeContent { return printContent(opts.IO, gists, opts.Filter) } return printTable(opts.IO, gists, opts.Filter) } func printTable(io *iostreams.IOStreams, gists []shared.Gist, filter *regexp.Regexp) error { cs := io.ColorScheme() tp := tableprinter.New(io, tableprinter.WithHeader("ID", "DESCRIPTION", "FILES", "VISIBILITY", "UPDATED")) // Highlight filter matches in the description when printing the table. highlightDescription := func(s string) string { if filter != nil { if str, err := highlightMatch(s, filter, nil, cs.Bold, cs.Highlight); err == nil { return str } } return cs.Bold(s) } // Highlight the files column when any file name matches the filter. highlightFilesFunc := func(gist *shared.Gist) func(string) string { if filter != nil { for _, file := range gist.Files { if filter.MatchString(file.Filename) { return cs.Highlight } } } return normal } for _, gist := range gists { fileCount := len(gist.Files) visibility := "public" visColor := cs.Green if !gist.Public { visibility = "secret" visColor = cs.Red } description := gist.Description if description == "" { for filename := range gist.Files { if !strings.HasPrefix(filename, "gistfile") { description = filename break } } } tp.AddField(gist.ID) tp.AddField( text.RemoveExcessiveWhitespace(description), tableprinter.WithColor(highlightDescription), ) tp.AddField( text.Pluralize(fileCount, "file"), tableprinter.WithColor(highlightFilesFunc(&gist)), ) tp.AddField(visibility, tableprinter.WithColor(visColor)) tp.AddTimeField(time.Now(), gist.UpdatedAt, cs.Muted) tp.EndRow() } return tp.Render() } // printContent prints a gist with optional description and content similar to `gh search code` // including highlighted matches in the form: // // {{gist ID}} {{file name}} // {{description, if any}} // {{content lines with matches, if any}} // // If printing to a non-TTY stream the format will be the same but without highlights. func printContent(io *iostreams.IOStreams, gists []shared.Gist, filter *regexp.Regexp) error { const tab string = " " cs := io.ColorScheme() out := &strings.Builder{} var filename, description string var err error split := func(r rune) bool { return r == '\n' || r == '\r' } for _, gist := range gists { for _, file := range gist.Files { matched := false out.Reset() if filename, err = highlightMatch(file.Filename, filter, &matched, cs.Green, cs.Highlight); err != nil { return err } fmt.Fprintln(out, cs.Blue(gist.ID), filename) if gist.Description != "" { if description, err = highlightMatch(gist.Description, filter, &matched, cs.Bold, cs.Highlight); err != nil { return err } fmt.Fprintf(out, "%s%s\n", tab, description) } if file.Content != "" { for line := range strings.FieldsFuncSeq(file.Content, split) { if filter.MatchString(line) { if line, err = highlightMatch(line, filter, &matched, normal, cs.Highlight); err != nil { return err } fmt.Fprintf(out, "%[1]s%[1]s%[2]s\n", tab, line) } } } if matched { fmt.Fprintln(io.Out, out.String()) } } } return nil } func highlightMatch(s string, filter *regexp.Regexp, matched *bool, color, highlight func(string) string) (string, error) { matches := filter.FindAllStringIndex(s, -1) if matches == nil { return color(s), nil } out := strings.Builder{} // Color up to the first match. If an empty string, no ANSI color sequence is added. if _, err := out.WriteString(color(s[:matches[0][0]])); err != nil { return "", err } // Highlight each match, then color the remaining text which, if an empty string, no ANSI color sequence is added. for i, match := range matches { if _, err := out.WriteString(highlight(s[match[0]:match[1]])); err != nil { return "", err } text := s[match[1]:] if i+1 < len(matches) { text = s[match[1]:matches[i+1][0]] } if _, err := out.WriteString(color(text)); err != nil { return "", err } } if matched != nil { *matched = *matched || true } return out.String(), nil } func normal(s string) string { return s }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/gist/rename/rename_test.go
pkg/cmd/gist/rename/rename_test.go
package rename import ( "bytes" "net/http" "testing" "github.com/cli/cli/v2/internal/config" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/pkg/cmd/gist/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" ) func TestNewCmdRename(t *testing.T) { tests := []struct { name string input string output RenameOptions errMsg string tty bool wantErr bool }{ { name: "no arguments", input: "", errMsg: "accepts 3 arg(s), received 0", wantErr: true, }, { name: "missing old filename and new filename", input: "123", errMsg: "accepts 3 arg(s), received 1", wantErr: true, }, { name: "missing new filename", input: "123 old.txt", errMsg: "accepts 3 arg(s), received 2", wantErr: true, }, { name: "rename", input: "123 old.txt new.txt", output: RenameOptions{ Selector: "123", OldFileName: "old.txt", NewFileName: "new.txt", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() ios.SetStdinTTY(tt.tty) ios.SetStdoutTTY(tt.tty) f := &cmdutil.Factory{ IOStreams: ios, } argv, err := shlex.Split(tt.input) assert.NoError(t, err) var gotOpts *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.Selector, gotOpts.Selector) assert.Equal(t, tt.output.OldFileName, gotOpts.OldFileName) assert.Equal(t, tt.output.NewFileName, gotOpts.NewFileName) }) } } func TestRenameRun(t *testing.T) { tests := []struct { name string opts *RenameOptions gist *shared.Gist httpStubs func(*httpmock.Registry) nontty bool stdin string wantOut string wantParams map[string]interface{} }{ { name: "no such gist", wantOut: "gist not found: 1234", }, { name: "rename from old.txt to new.txt", opts: &RenameOptions{ Selector: "1234", OldFileName: "old.txt", NewFileName: "new.txt", }, gist: &shared.Gist{ ID: "1234", Files: map[string]*shared.GistFile{ "old.txt": { Filename: "old.txt", Type: "text/plain", }, }, Owner: &shared.GistOwner{Login: "octocat"}, }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("POST", "gists/1234"), httpmock.StatusStringResponse(201, "{}")) }, wantParams: map[string]interface{}{ "files": map[string]interface{}{ "new.txt": map[string]interface{}{ "filename": "new.txt", "type": "text/plain", }, }, }, }, } for _, tt := range tests { reg := &httpmock.Registry{} if tt.gist == nil { reg.Register(httpmock.REST("GET", "gists/1234"), httpmock.StatusStringResponse(404, "Not Found")) } else { reg.Register(httpmock.REST("GET", "gists/1234"), httpmock.JSONResponse(tt.gist)) reg.Register(httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data":{"viewer":{"login":"octocat"}}}`)) } if tt.httpStubs != nil { tt.httpStubs(reg) } if tt.opts == nil { tt.opts = &RenameOptions{} } tt.opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } ios, stdin, stdout, stderr := iostreams.Test() stdin.WriteString(tt.stdin) ios.SetStdoutTTY(!tt.nontty) ios.SetStdinTTY(!tt.nontty) tt.opts.Selector = "1234" tt.opts.OldFileName = "old.txt" tt.opts.NewFileName = "new.txt" tt.opts.IO = ios tt.opts.Config = func() (gh.Config, error) { return config.NewBlankConfig(), nil } t.Run(tt.name, func(t *testing.T) { err := renameRun(tt.opts) reg.Verify(t) if tt.wantOut != "" { assert.EqualError(t, err, tt.wantOut) return } assert.NoError(t, err) assert.Equal(t, "", stdout.String()) assert.Equal(t, "", stderr.String()) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/gist/rename/rename.go
pkg/cmd/gist/rename/rename.go
package rename import ( "bytes" "encoding/json" "errors" "fmt" "net/http" "strings" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/pkg/cmd/gist/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type RenameOptions struct { IO *iostreams.IOStreams Config func() (gh.Config, error) HttpClient func() (*http.Client, error) Selector string OldFileName string NewFileName string } func NewCmdRename(f *cmdutil.Factory, runf func(*RenameOptions) error) *cobra.Command { opts := &RenameOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, Config: f.Config, } cmd := &cobra.Command{ Use: "rename {<id> | <url>} <old-filename> <new-filename>", Short: "Rename a file in a gist", Long: heredoc.Doc(`Rename a file in the given gist ID / URL.`), Args: cobra.ExactArgs(3), RunE: func(cmd *cobra.Command, args []string) error { opts.Selector = args[0] opts.OldFileName = args[1] opts.NewFileName = args[2] if runf != nil { return runf(opts) } return renameRun(opts) }, } return cmd } func renameRun(opts *RenameOptions) error { gistID := opts.Selector if strings.Contains(gistID, "/") { id, err := shared.GistIDFromURL(gistID) if err != nil { return err } gistID = id } client, err := opts.HttpClient() if err != nil { return err } apiClient := api.NewClientFromHTTP(client) cfg, err := opts.Config() if err != nil { return err } host, _ := cfg.Authentication().DefaultHost() gist, err := shared.GetGist(client, host, gistID) if err != nil { if errors.Is(err, shared.NotFoundErr) { return fmt.Errorf("gist not found: %s", gistID) } return err } username, err := api.CurrentLoginName(apiClient, host) if err != nil { return err } if username != gist.Owner.Login { return errors.New("you do not own this gist") } _, ok := gist.Files[opts.OldFileName] if !ok { return fmt.Errorf("File %s not found in gist", opts.OldFileName) } _, ok = gist.Files[opts.NewFileName] if ok { return fmt.Errorf("File %s already exists in gist", opts.NewFileName) } gist.Files[opts.NewFileName] = gist.Files[opts.OldFileName] gist.Files[opts.NewFileName].Filename = opts.NewFileName gist.Files[opts.OldFileName] = &shared.GistFile{} return updateGist(apiClient, host, gist) } func updateGist(apiClient *api.Client, hostname string, gist *shared.Gist) error { body := shared.Gist{ Description: gist.Description, Files: gist.Files, } path := "gists/" + gist.ID requestByte, err := json.Marshal(body) if err != nil { return err } requestBody := bytes.NewReader(requestByte) result := shared.Gist{} err = apiClient.REST(hostname, "POST", path, requestBody, &result) 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/gist/edit/edit.go
pkg/cmd/gist/edit/edit.go
package edit import ( "bytes" "encoding/json" "errors" "fmt" "io" "net/http" "os" "path/filepath" "sort" "strings" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/pkg/cmd/gist/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/pkg/surveyext" "github.com/spf13/cobra" ) var editNextOptions = []string{"Edit another file", "Submit", "Cancel"} type EditOptions struct { IO *iostreams.IOStreams HttpClient func() (*http.Client, error) Config func() (gh.Config, error) Prompter prompter.Prompter Edit func(string, string, string, *iostreams.IOStreams) (string, error) Selector string EditFilename string AddFilename string RemoveFilename string SourceFile string Description string } func NewCmdEdit(f *cmdutil.Factory, runF func(*EditOptions) error) *cobra.Command { opts := EditOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, Config: f.Config, Prompter: f.Prompter, Edit: func(editorCmd, filename, defaultContent string, io *iostreams.IOStreams) (string, error) { return surveyext.Edit( editorCmd, "*."+filename, defaultContent, io.In, io.Out, io.ErrOut) }, } cmd := &cobra.Command{ Use: "edit {<id> | <url>} [<filename>]", Short: "Edit one of your gists", Args: func(cmd *cobra.Command, args []string) error { if len(args) > 2 { return cmdutil.FlagErrorf("too many arguments") } return nil }, RunE: func(c *cobra.Command, args []string) error { if len(args) > 0 { opts.Selector = args[0] } if len(args) > 1 { opts.SourceFile = args[1] } if runF != nil { return runF(&opts) } return editRun(&opts) }, } cmd.Flags().StringVarP(&opts.AddFilename, "add", "a", "", "Add a new file to the gist") cmd.Flags().StringVarP(&opts.Description, "desc", "d", "", "New description for the gist") cmd.Flags().StringVarP(&opts.EditFilename, "filename", "f", "", "Select a file to edit") cmd.Flags().StringVarP(&opts.RemoveFilename, "remove", "r", "", "Remove a file from the gist") cmd.MarkFlagsMutuallyExclusive("add", "remove") cmd.MarkFlagsMutuallyExclusive("remove", "filename") return cmd } func editRun(opts *EditOptions) error { client, err := opts.HttpClient() if err != nil { return err } cfg, err := opts.Config() if err != nil { return err } host, _ := cfg.Authentication().DefaultHost() gistID := opts.Selector if gistID == "" { cs := opts.IO.ColorScheme() if gistID == "" { if !opts.IO.CanPrompt() { return cmdutil.FlagErrorf("gist ID or URL required when not running interactively") } gist, err := shared.PromptGists(opts.Prompter, client, host, cs) if err != nil { return err } if gist.ID == "" { fmt.Fprintln(opts.IO.Out, "No gists found.") return nil } gistID = gist.ID } } if strings.Contains(gistID, "/") { id, err := shared.GistIDFromURL(gistID) if err != nil { return err } gistID = id } apiClient := api.NewClientFromHTTP(client) gist, err := shared.GetGist(client, host, gistID) if err != nil { if errors.Is(err, shared.NotFoundErr) { return fmt.Errorf("gist not found: %s", gistID) } return err } username, err := api.CurrentLoginName(apiClient, host) if err != nil { return err } if username != gist.Owner.Login { return errors.New("you do not own this gist") } // Transform our gist into the schema that the update endpoint expects filesToupdate := make(map[string]*gistFileToUpdate, len(gist.Files)) for filename, file := range gist.Files { filesToupdate[filename] = &gistFileToUpdate{ Content: file.Content, NewFilename: file.Filename, } } gistToUpdate := gistToUpdate{ id: gist.ID, Description: gist.Description, Files: filesToupdate, } shouldUpdate := false if opts.Description != "" { shouldUpdate = true gistToUpdate.Description = opts.Description } if opts.AddFilename != "" { var input io.Reader switch src := opts.SourceFile; { case src == "-": input = opts.IO.In case src != "": f, err := os.Open(src) if err != nil { return err } defer func() { _ = f.Close() }() input = f default: f, err := os.Open(opts.AddFilename) if err != nil { return err } defer func() { _ = f.Close() }() input = f } content, err := io.ReadAll(input) if err != nil { return fmt.Errorf("read content: %w", err) } files, err := getFilesToAdd(opts.AddFilename, content) if err != nil { return err } gistToUpdate.Files = files return updateGist(apiClient, host, gistToUpdate) } // Remove a file from the gist if opts.RemoveFilename != "" { files, err := getFilesToRemove(gistToUpdate, opts.RemoveFilename) if err != nil { return err } gistToUpdate.Files = files return updateGist(apiClient, host, gistToUpdate) } filesToUpdate := map[string]string{} for { filename := opts.EditFilename candidates := []string{} for filename := range gistToUpdate.Files { candidates = append(candidates, filename) } sort.Strings(candidates) if filename == "" { if len(candidates) == 1 { filename = candidates[0] } else if len(candidates) == 0 { return errors.New("no file in the gist") } else { if !opts.IO.CanPrompt() { return errors.New("unsure what file to edit; either specify --filename or run interactively") } result, err := opts.Prompter.Select("Edit which file?", "", candidates) if err != nil { return fmt.Errorf("could not prompt: %w", err) } filename = candidates[result] } } gistFile, found := gistToUpdate.Files[filename] if !found { return fmt.Errorf("gist has no file %q", filename) } if shared.IsBinaryContents([]byte(gistFile.Content)) { return fmt.Errorf("editing binary files not supported") } // If the file is truncated, fetch the full content // but only if it hasn't already been edited in this session file := gist.Files[filename] if file.Truncated { if _, alreadyEdited := filesToUpdate[filename]; !alreadyEdited { fullContent, err := shared.GetRawGistFile(client, file.RawURL) if err != nil { return err } gistFile.Content = fullContent } } var text string if src := opts.SourceFile; src != "" { if src == "-" { data, err := io.ReadAll(opts.IO.In) if err != nil { return fmt.Errorf("read from stdin: %w", err) } text = string(data) } else { data, err := os.ReadFile(src) if err != nil { return fmt.Errorf("read %s: %w", src, err) } text = string(data) } } else { editorCommand, err := cmdutil.DetermineEditor(opts.Config) if err != nil { return err } data, err := opts.Edit(editorCommand, filename, gistFile.Content, opts.IO) if err != nil { return err } text = data } if text != gistFile.Content { gistFile.Content = text // so it appears if they re-edit filesToUpdate[filename] = text } if !opts.IO.CanPrompt() || len(candidates) == 1 || opts.EditFilename != "" { break } choice := "" result, err := opts.Prompter.Select("What next?", "", editNextOptions) if err != nil { return fmt.Errorf("could not prompt: %w", err) } choice = editNextOptions[result] stop := false switch choice { case "Edit another file": continue case "Submit": stop = true case "Cancel": return cmdutil.CancelError } if stop { break } } if len(filesToUpdate) > 0 { shouldUpdate = true } if !shouldUpdate { return nil } updatedFiles := make(map[string]*gistFileToUpdate, len(filesToUpdate)) for filename := range filesToUpdate { updatedFiles[filename] = gistToUpdate.Files[filename] } gistToUpdate.Files = updatedFiles return updateGist(apiClient, host, gistToUpdate) } // https://docs.github.com/en/rest/gists/gists?apiVersion=2022-11-28#update-a-gist type gistToUpdate struct { // The id of the gist to update. Does not get marshalled to JSON. id string // The description of the gist Description string `json:"description"` // The gist files to be updated, renamed or deleted. The key must match the current // filename of the file to change. To delete a file, set the value to nil Files map[string]*gistFileToUpdate `json:"files"` } type gistFileToUpdate struct { // The new content of the file Content string `json:"content"` // The new name for the file NewFilename string `json:"filename,omitempty"` } func updateGist(apiClient *api.Client, hostname string, gist gistToUpdate) error { requestByte, err := json.Marshal(gist) if err != nil { return err } requestBody := bytes.NewReader(requestByte) result := shared.Gist{} path := "gists/" + gist.id err = apiClient.REST(hostname, "POST", path, requestBody, &result) if err != nil { return err } return nil } func getFilesToAdd(file string, content []byte) (map[string]*gistFileToUpdate, error) { if shared.IsBinaryContents(content) { return nil, fmt.Errorf("failed to upload %s: binary file not supported", file) } if len(content) == 0 { return nil, errors.New("file contents cannot be empty") } filename := filepath.Base(file) return map[string]*gistFileToUpdate{ filename: { NewFilename: filename, Content: string(content), }, }, nil } func getFilesToRemove(gist gistToUpdate, filename string) (map[string]*gistFileToUpdate, error) { if _, found := gist.Files[filename]; !found { return nil, fmt.Errorf("gist has no file %q", filename) } gist.Files[filename] = nil return map[string]*gistFileToUpdate{ filename: nil, }, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/gist/edit/edit_test.go
pkg/cmd/gist/edit/edit_test.go
package edit import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" "path/filepath" "testing" "time" "github.com/cli/cli/v2/internal/config" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/pkg/cmd/gist/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func Test_getFilesToAdd(t *testing.T) { filename := "gist-test.txt" gf, err := getFilesToAdd(filename, []byte("hello")) require.NoError(t, err) assert.Equal(t, map[string]*gistFileToUpdate{ filename: { NewFilename: filename, Content: "hello", }, }, gf) } func TestNewCmdEdit(t *testing.T) { tests := []struct { name string cli string wants EditOptions wantsErr bool }{ { name: "no flags", cli: "123", wants: EditOptions{ Selector: "123", }, }, { name: "filename", cli: "123 --filename cool.md", wants: EditOptions{ Selector: "123", EditFilename: "cool.md", }, }, { name: "add", cli: "123 --add cool.md", wants: EditOptions{ Selector: "123", AddFilename: "cool.md", }, }, { name: "add with source", cli: "123 --add cool.md -", wants: EditOptions{ Selector: "123", AddFilename: "cool.md", SourceFile: "-", }, }, { name: "description", cli: `123 --desc "my new description"`, wants: EditOptions{ Selector: "123", Description: "my new description", }, }, { name: "remove", cli: "123 --remove cool.md", wants: EditOptions{ Selector: "123", RemoveFilename: "cool.md", }, }, { name: "add and remove are mutually exclusive", cli: "123 --add cool.md --remove great.md", wantsErr: true, }, { name: "filename and remove are mutually exclusive", cli: "123 --filename cool.md --remove great.md", wantsErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { f := &cmdutil.Factory{} argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts *EditOptions cmd := NewCmdEdit(f, func(opts *EditOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err = cmd.ExecuteC() if tt.wantsErr { require.Error(t, err) return } require.NoError(t, err) require.Equal(t, tt.wants.EditFilename, gotOpts.EditFilename) require.Equal(t, tt.wants.AddFilename, gotOpts.AddFilename) require.Equal(t, tt.wants.Selector, gotOpts.Selector) require.Equal(t, tt.wants.RemoveFilename, gotOpts.RemoveFilename) }) } } func Test_editRun(t *testing.T) { fileToAdd := filepath.Join(t.TempDir(), "gist-test.txt") err := os.WriteFile(fileToAdd, []byte("hello"), 0600) require.NoError(t, err) tests := []struct { name string opts *EditOptions mockGist *shared.Gist mockGistList bool httpStubs func(*httpmock.Registry) prompterStubs func(*prompter.MockPrompter) isTTY bool stdin string wantErr string wantLastRequestParameters map[string]interface{} }{ { name: "no such gist", wantErr: "gist not found: 1234", opts: &EditOptions{ Selector: "1234", }, }, { name: "one file", isTTY: false, opts: &EditOptions{ Selector: "1234", }, mockGist: &shared.Gist{ ID: "1234", Files: map[string]*shared.GistFile{ "cicada.txt": { Filename: "cicada.txt", Content: "bwhiizzzbwhuiiizzzz", Type: "text/plain", }, }, Owner: &shared.GistOwner{Login: "octocat"}, }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("POST", "gists/1234"), httpmock.StatusStringResponse(201, "{}")) }, wantLastRequestParameters: map[string]interface{}{ "description": "", "files": map[string]interface{}{ "cicada.txt": map[string]interface{}{ "content": "new file content", "filename": "cicada.txt", }, }, }, }, { name: "multiple files, submit, with TTY", isTTY: true, mockGistList: true, prompterStubs: func(pm *prompter.MockPrompter) { pm.RegisterSelect("Edit which file?", []string{"cicada.txt", "unix.md"}, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "unix.md") }) pm.RegisterSelect("What next?", editNextOptions, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "Submit") }) }, mockGist: &shared.Gist{ ID: "1234", Description: "catbug", Files: map[string]*shared.GistFile{ "cicada.txt": { Filename: "cicada.txt", Content: "bwhiizzzbwhuiiizzzz", }, "unix.md": { Filename: "unix.md", Content: "meow", }, }, Owner: &shared.GistOwner{Login: "octocat"}, }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("POST", "gists/1234"), httpmock.StatusStringResponse(201, "{}")) }, wantLastRequestParameters: map[string]interface{}{ "description": "catbug", "files": map[string]interface{}{ "unix.md": map[string]interface{}{ "content": "new file content", "filename": "unix.md", }, }, }, }, { name: "single file edit flag sends only edited file", opts: &EditOptions{ Selector: "1234", EditFilename: "unix.md", }, mockGist: &shared.Gist{ ID: "1234", Files: map[string]*shared.GistFile{ "cicada.txt": {Filename: "cicada.txt", Content: "bwhiizzzbwhuiiizzzz", Type: "text/plain"}, "unix.md": {Filename: "unix.md", Content: "meow", Type: "text/markdown"}, }, Owner: &shared.GistOwner{Login: "octocat"}, }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("POST", "gists/1234"), httpmock.StatusStringResponse(201, "{}")) }, wantLastRequestParameters: map[string]interface{}{ "description": "", "files": map[string]interface{}{ "unix.md": map[string]interface{}{ "content": "new file content", "filename": "unix.md", }, }, }, }, { name: "multiple files, cancel, with TTY", isTTY: true, opts: &EditOptions{ Selector: "1234", }, prompterStubs: func(pm *prompter.MockPrompter) { pm.RegisterSelect("Edit which file?", []string{"cicada.txt", "unix.md"}, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "unix.md") }) pm.RegisterSelect("What next?", editNextOptions, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "Cancel") }) }, wantErr: "CancelError", mockGist: &shared.Gist{ ID: "1234", Files: map[string]*shared.GistFile{ "cicada.txt": { Filename: "cicada.txt", Content: "bwhiizzzbwhuiiizzzz", Type: "text/plain", }, "unix.md": { Filename: "unix.md", Content: "meow", Type: "application/markdown", }, }, Owner: &shared.GistOwner{Login: "octocat"}, }, }, { name: "not change", opts: &EditOptions{ Selector: "1234", }, mockGist: &shared.Gist{ ID: "1234", Files: map[string]*shared.GistFile{ "cicada.txt": { Filename: "cicada.txt", Content: "new file content", Type: "text/plain", }, }, Owner: &shared.GistOwner{Login: "octocat"}, }, }, { name: "another user's gist", opts: &EditOptions{ Selector: "1234", }, mockGist: &shared.Gist{ ID: "1234", Files: map[string]*shared.GistFile{ "cicada.txt": { Filename: "cicada.txt", Content: "bwhiizzzbwhuiiizzzz", Type: "text/plain", }, }, Owner: &shared.GistOwner{Login: "octocat2"}, }, wantErr: "you do not own this gist", }, { name: "add file to existing gist", opts: &EditOptions{ AddFilename: fileToAdd, Selector: "1234", }, mockGist: &shared.Gist{ ID: "1234", Files: map[string]*shared.GistFile{ "sample.txt": { Filename: "sample.txt", Content: "bwhiizzzbwhuiiizzzz", Type: "text/plain", }, }, Owner: &shared.GistOwner{Login: "octocat"}, }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("POST", "gists/1234"), httpmock.StatusStringResponse(201, "{}")) }, }, { name: "change description", opts: &EditOptions{ Description: "my new description", Selector: "1234", }, mockGist: &shared.Gist{ ID: "1234", Description: "my old description", Files: map[string]*shared.GistFile{ "sample.txt": { Filename: "sample.txt", Type: "text/plain", }, }, Owner: &shared.GistOwner{Login: "octocat"}, }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("POST", "gists/1234"), httpmock.StatusStringResponse(201, "{}")) }, wantLastRequestParameters: map[string]interface{}{ "description": "my new description", "files": map[string]interface{}{ "sample.txt": map[string]interface{}{ "content": "new file content", "filename": "sample.txt", }, }, }, }, { name: "add file to existing gist from source parameter", opts: &EditOptions{ AddFilename: "from_source.txt", SourceFile: fileToAdd, Selector: "1234", }, mockGist: &shared.Gist{ ID: "1234", Files: map[string]*shared.GistFile{ "sample.txt": { Filename: "sample.txt", Content: "bwhiizzzbwhuiiizzzz", Type: "text/plain", }, }, Owner: &shared.GistOwner{Login: "octocat"}, }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("POST", "gists/1234"), httpmock.StatusStringResponse(201, "{}")) }, wantLastRequestParameters: map[string]interface{}{ "description": "", "files": map[string]interface{}{ "from_source.txt": map[string]interface{}{ "content": "hello", "filename": "from_source.txt", }, }, }, }, { name: "add file to existing gist from stdin", opts: &EditOptions{ AddFilename: "from_source.txt", SourceFile: "-", Selector: "1234", }, mockGist: &shared.Gist{ ID: "1234", Files: map[string]*shared.GistFile{ "sample.txt": { Filename: "sample.txt", Content: "bwhiizzzbwhuiiizzzz", Type: "text/plain", }, }, Owner: &shared.GistOwner{Login: "octocat"}, }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("POST", "gists/1234"), httpmock.StatusStringResponse(201, "{}")) }, stdin: "data from stdin", wantLastRequestParameters: map[string]interface{}{ "description": "", "files": map[string]interface{}{ "from_source.txt": map[string]interface{}{ "content": "data from stdin", "filename": "from_source.txt", }, }, }, }, { name: "remove file, file does not exist", opts: &EditOptions{ RemoveFilename: "sample2.txt", Selector: "1234", }, mockGist: &shared.Gist{ ID: "1234", Files: map[string]*shared.GistFile{ "sample.txt": { Filename: "sample.txt", Content: "bwhiizzzbwhuiiizzzz", Type: "text/plain", }, }, Owner: &shared.GistOwner{Login: "octocat"}, }, wantErr: "gist has no file \"sample2.txt\"", }, { name: "remove file from existing gist", opts: &EditOptions{ RemoveFilename: "sample2.txt", Selector: "1234", }, mockGist: &shared.Gist{ ID: "1234", Files: map[string]*shared.GistFile{ "sample.txt": { Filename: "sample.txt", Content: "bwhiizzzbwhuiiizzzz", Type: "text/plain", }, "sample2.txt": { Filename: "sample2.txt", Content: "bwhiizzzbwhuiiizzzz", Type: "text/plain", }, }, Owner: &shared.GistOwner{Login: "octocat"}, }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("POST", "gists/1234"), httpmock.StatusStringResponse(201, "{}")) }, wantLastRequestParameters: map[string]interface{}{ "description": "", "files": map[string]interface{}{ "sample2.txt": nil, }, }, }, { name: "edit gist using file from source parameter", opts: &EditOptions{ SourceFile: fileToAdd, Selector: "1234", }, mockGist: &shared.Gist{ ID: "1234", Files: map[string]*shared.GistFile{ "sample.txt": { Filename: "sample.txt", Content: "bwhiizzzbwhuiiizzzz", Type: "text/plain", }, }, Owner: &shared.GistOwner{Login: "octocat"}, }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("POST", "gists/1234"), httpmock.StatusStringResponse(201, "{}")) }, wantLastRequestParameters: map[string]interface{}{ "description": "", "files": map[string]interface{}{ "sample.txt": map[string]interface{}{ "content": "hello", "filename": "sample.txt", }, }, }, }, { name: "edit gist using stdin", opts: &EditOptions{ SourceFile: "-", Selector: "1234", }, mockGist: &shared.Gist{ ID: "1234", Files: map[string]*shared.GistFile{ "sample.txt": { Filename: "sample.txt", Content: "bwhiizzzbwhuiiizzzz", Type: "text/plain", }, }, Owner: &shared.GistOwner{Login: "octocat"}, }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("POST", "gists/1234"), httpmock.StatusStringResponse(201, "{}")) }, stdin: "data from stdin", wantLastRequestParameters: map[string]interface{}{ "description": "", "files": map[string]interface{}{ "sample.txt": map[string]interface{}{ "content": "data from stdin", "filename": "sample.txt", }, }, }, }, { name: "no arguments notty", isTTY: false, opts: &EditOptions{ Selector: "", }, wantErr: "gist ID or URL required when not running interactively", }, { name: "edit no-file gist (#10626)", opts: &EditOptions{ Selector: "1234", }, mockGist: &shared.Gist{ ID: "1234", Files: map[string]*shared.GistFile{}, Owner: &shared.GistOwner{Login: "octocat"}, }, wantErr: "no file in the gist", }, { name: "edit no-file gist, nil map (#10626)", opts: &EditOptions{ Selector: "1234", }, mockGist: &shared.Gist{ ID: "1234", Files: nil, Owner: &shared.GistOwner{Login: "octocat"}, }, wantErr: "no file in the gist", }, { name: "edit gist with truncated file", opts: &EditOptions{ Selector: "1234", }, mockGist: &shared.Gist{ ID: "1234", Files: map[string]*shared.GistFile{ "large.txt": { Filename: "large.txt", Content: "This is truncated content...", Type: "text/plain", Truncated: true, RawURL: "https://gist.githubusercontent.com/user/1234/raw/large.txt", }, }, Owner: &shared.GistOwner{Login: "octocat"}, }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("POST", "gists/1234"), httpmock.StatusStringResponse(201, "{}")) }, wantLastRequestParameters: map[string]interface{}{ "description": "", "files": map[string]interface{}{ "large.txt": map[string]interface{}{ "content": "new file content", "filename": "large.txt", }, }, }, }, { name: "edit specific truncated file in gist with multiple truncated files", opts: &EditOptions{ Selector: "1234", EditFilename: "large.txt", }, mockGist: &shared.Gist{ ID: "1234", Files: map[string]*shared.GistFile{ "large.txt": { Filename: "large.txt", Content: "This is truncated content...", Type: "text/plain", Truncated: true, RawURL: "https://gist.githubusercontent.com/user/1234/raw/large.txt", }, "also-truncated.txt": { Filename: "also-truncated.txt", Content: "", // Empty because GitHub truncates subsequent files Type: "text/plain", Truncated: true, // Subsequent files are also marked as truncated RawURL: "https://gist.githubusercontent.com/user/1234/raw/also-truncated.txt", }, }, Owner: &shared.GistOwner{Login: "octocat"}, }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("POST", "gists/1234"), httpmock.StatusStringResponse(201, "{}")) }, wantLastRequestParameters: map[string]interface{}{ "description": "", "files": map[string]interface{}{ "large.txt": map[string]interface{}{ "content": "new file content", "filename": "large.txt", }, }, }, }, { name: "interactive truncated multi-file gist fetches only selected file raw content the first time", isTTY: true, opts: &EditOptions{Selector: "1234"}, prompterStubs: func(pm *prompter.MockPrompter) { pm.RegisterSelect("Edit which file?", []string{"also-truncated.txt", "large.txt"}, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "large.txt") }) pm.RegisterSelect("What next?", editNextOptions, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "Edit another file") }) // Editing large.txt twice to ensure that fetch for the raw URL happens only once pm.RegisterSelect("Edit which file?", []string{"also-truncated.txt", "large.txt"}, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "large.txt") }) pm.RegisterSelect("What next?", editNextOptions, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "Submit") }) }, mockGist: &shared.Gist{ ID: "1234", Files: map[string]*shared.GistFile{ "large.txt": {Filename: "large.txt", Content: "This is truncated content...", Type: "text/plain", Truncated: true, RawURL: "https://gist.githubusercontent.com/user/1234/raw/large.txt"}, "also-truncated.txt": {Filename: "also-truncated.txt", Content: "stuff...", Type: "text/plain", Truncated: true, RawURL: "https://gist.githubusercontent.com/user/1234/raw/also-truncated.txt"}, }, Owner: &shared.GistOwner{Login: "octocat"}, }, httpStubs: func(reg *httpmock.Registry) { reg.Register(httpmock.REST("POST", "gists/1234"), httpmock.StatusStringResponse(201, "{}")) // Explicity exclude also-truncated.txt raw URL to ensure it is not fetched since we did not select it. reg.Exclude(t, httpmock.REST("GET", "user/1234/raw/also-truncated.txt")) }, wantLastRequestParameters: map[string]interface{}{ "description": "", "files": map[string]interface{}{ "large.txt": map[string]interface{}{ "content": "new file content", "filename": "large.txt", }, }, }, }, } for _, tt := range tests { reg := &httpmock.Registry{} pm := prompter.NewMockPrompter(t) if tt.opts == nil { tt.opts = &EditOptions{} } if tt.opts.Selector != "" { // Only register the HTTP stubs for a direct gist lookup if a selector is provided. if tt.mockGist == nil { // If no gist is provided, we expect a 404. reg.Register(httpmock.REST("GET", fmt.Sprintf("gists/%s", tt.opts.Selector)), httpmock.StatusStringResponse(404, "Not Found")) } else { // If a gist is provided, we expect the gist to be fetched. reg.Register(httpmock.REST("GET", fmt.Sprintf("gists/%s", tt.opts.Selector)), httpmock.JSONResponse(tt.mockGist)) reg.Register(httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data":{"viewer":{"login":"octocat"}}}`)) // Register raw URL mocks for truncated files for filename, file := range tt.mockGist.Files { if file.Truncated && file.RawURL != "" { // Mock the raw URL response for GetRawGistFile calls if filename == "large.txt" { reg.Register(httpmock.REST("GET", "user/1234/raw/large.txt"), httpmock.StringResponse("This is the full content of the large file retrieved from raw URL")) } } } } } if tt.mockGistList { sixHours, _ := time.ParseDuration("6h") sixHoursAgo := time.Now().Add(-sixHours) reg.Register(httpmock.GraphQL(`query GistList\b`), httpmock.StringResponse( fmt.Sprintf(`{ "data": { "viewer": { "gists": { "nodes": [ { "description": "whatever", "files": [{ "name": "cicada.txt" }, { "name": "unix.md" }], "isPublic": true, "name": "1234", "updatedAt": "%s" } ], "pageInfo": { "hasNextPage": false, "endCursor": "somevaluedoesnotmatter" } } } } }`, sixHoursAgo.Format(time.RFC3339)))) reg.Register(httpmock.REST("GET", "gists/1234"), httpmock.JSONResponse(tt.mockGist)) reg.Register(httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data":{"viewer":{"login":"octocat"}}}`)) gistList := "cicada.txt whatever about 6 hours ago" pm.RegisterSelect("Select a gist", []string{gistList}, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, gistList) }) } if tt.httpStubs != nil { tt.httpStubs(reg) } tt.opts.Edit = func(_, _, _ string, _ *iostreams.IOStreams) (string, error) { return "new file content", nil } tt.opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } ios, stdin, stdout, stderr := iostreams.Test() stdin.WriteString(tt.stdin) ios.SetStdoutTTY(tt.isTTY) ios.SetStdinTTY(tt.isTTY) ios.SetStderrTTY(tt.isTTY) tt.opts.IO = ios tt.opts.Config = func() (gh.Config, error) { return config.NewBlankConfig(), nil } t.Run(tt.name, func(t *testing.T) { if tt.prompterStubs != nil { tt.prompterStubs(pm) } tt.opts.Prompter = pm err := editRun(tt.opts) reg.Verify(t) if tt.wantErr != "" { assert.EqualError(t, err, tt.wantErr) return } assert.NoError(t, err) if tt.wantLastRequestParameters != nil { // Currently only checking that the last request has // the expected request parameters. // // This might need to be changed, if a test were to be added // that needed to check that a request other than the last // has the desired parameters. lastRequest := reg.Requests[len(reg.Requests)-1] bodyBytes, _ := io.ReadAll(lastRequest.Body) reqBody := make(map[string]interface{}) err = json.Unmarshal(bodyBytes, &reqBody) if err != nil { t.Fatalf("error decoding JSON: %v", err) } assert.Equal(t, tt.wantLastRequestParameters, reqBody) } assert.Equal(t, "", stdout.String()) assert.Equal(t, "", stderr.String()) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/gist/view/view.go
pkg/cmd/gist/view/view.go
package view import ( "fmt" "net/http" "sort" "strings" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghinstance" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/internal/text" "github.com/cli/cli/v2/pkg/cmd/gist/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/pkg/markdown" "github.com/spf13/cobra" ) type browser interface { Browse(string) error } type ViewOptions struct { IO *iostreams.IOStreams Config func() (gh.Config, error) HttpClient func() (*http.Client, error) Browser browser Prompter prompter.Prompter Selector string Filename string Raw bool Web bool ListFiles bool } func NewCmdView(f *cmdutil.Factory, runF func(*ViewOptions) error) *cobra.Command { opts := &ViewOptions{ IO: f.IOStreams, Config: f.Config, HttpClient: f.HttpClient, Browser: f.Browser, Prompter: f.Prompter, } cmd := &cobra.Command{ Use: "view [<id> | <url>]", Short: "View a gist", Long: `View the given gist or select from recent gists.`, Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { if len(args) == 1 { opts.Selector = args[0] } if !opts.IO.IsStdoutTTY() { opts.Raw = true } if runF != nil { return runF(opts) } return viewRun(opts) }, } cmd.Flags().BoolVarP(&opts.Raw, "raw", "r", false, "Print raw instead of rendered gist contents") cmd.Flags().BoolVarP(&opts.Web, "web", "w", false, "Open gist in the browser") cmd.Flags().BoolVar(&opts.ListFiles, "files", false, "List file names from the gist") cmd.Flags().StringVarP(&opts.Filename, "filename", "f", "", "Display a single file from the gist") return cmd } func viewRun(opts *ViewOptions) error { gistID := opts.Selector client, err := opts.HttpClient() if err != nil { return err } cfg, err := opts.Config() if err != nil { return err } hostname, _ := cfg.Authentication().DefaultHost() cs := opts.IO.ColorScheme() if gistID == "" { if !opts.IO.CanPrompt() { return cmdutil.FlagErrorf("gist ID or URL required when not running interactively") } gist, err := shared.PromptGists(opts.Prompter, client, hostname, cs) if err != nil { return err } if gist.ID == "" { fmt.Fprintln(opts.IO.Out, "No gists found.") return nil } gistID = gist.ID } if opts.Web { gistURL := gistID if !strings.Contains(gistURL, "/") { gistURL = ghinstance.GistPrefix(hostname) + gistID } if opts.IO.IsStderrTTY() { fmt.Fprintf(opts.IO.ErrOut, "Opening %s in your browser.\n", text.DisplayURL(gistURL)) } return opts.Browser.Browse(gistURL) } if strings.Contains(gistID, "/") { id, err := shared.GistIDFromURL(gistID) if err != nil { return err } gistID = id } gist, err := shared.GetGist(client, hostname, gistID) if err != nil { return err } opts.IO.DetectTerminalTheme() if err := opts.IO.StartPager(); err != nil { fmt.Fprintf(opts.IO.ErrOut, "starting pager failed: %v\n", err) } defer opts.IO.StopPager() render := func(gf *shared.GistFile) error { if gf.Truncated { fullContent, err := shared.GetRawGistFile(client, gf.RawURL) if err != nil { return err } gf.Content = fullContent } if shared.IsBinaryContents([]byte(gf.Content)) { if len(gist.Files) == 1 || opts.Filename != "" { return fmt.Errorf("error: file is binary") } _, err = fmt.Fprintln(opts.IO.Out, cs.Muted("(skipping rendering binary content)")) return nil } if strings.Contains(gf.Type, "markdown") && !opts.Raw { rendered, err := markdown.Render(gf.Content, markdown.WithTheme(opts.IO.TerminalTheme()), markdown.WithWrap(opts.IO.TerminalWidth())) if err != nil { return err } _, err = fmt.Fprint(opts.IO.Out, rendered) return err } if _, err := fmt.Fprint(opts.IO.Out, gf.Content); err != nil { return err } if !strings.HasSuffix(gf.Content, "\n") { _, err := fmt.Fprint(opts.IO.Out, "\n") return err } return nil } if opts.Filename != "" { gistFile, ok := gist.Files[opts.Filename] if !ok { return fmt.Errorf("gist has no such file: %q", opts.Filename) } return render(gistFile) } if gist.Description != "" && !opts.ListFiles { fmt.Fprintf(opts.IO.Out, "%s\n\n", cs.Bold(gist.Description)) } showFilenames := len(gist.Files) > 1 filenames := make([]string, 0, len(gist.Files)) for fn := range gist.Files { filenames = append(filenames, fn) } sort.Slice(filenames, func(i, j int) bool { return strings.ToLower(filenames[i]) < strings.ToLower(filenames[j]) }) if opts.ListFiles { for _, fn := range filenames { fmt.Fprintln(opts.IO.Out, fn) } return nil } for i, fn := range filenames { if showFilenames { fmt.Fprintf(opts.IO.Out, "%s\n\n", cs.Muted(fn)) } if err := render(gist.Files[fn]); err != nil { return err } if i < len(filenames)-1 { fmt.Fprint(opts.IO.Out, "\n") } } return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/gist/view/view_test.go
pkg/cmd/gist/view/view_test.go
package view import ( "bytes" "fmt" "net/http" "testing" "time" "github.com/cli/cli/v2/internal/config" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/pkg/cmd/gist/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNewCmdView(t *testing.T) { tests := []struct { name string cli string wants ViewOptions tty bool }{ { name: "tty no arguments", tty: true, cli: "123", wants: ViewOptions{ Raw: false, Selector: "123", ListFiles: false, }, }, { name: "nontty no arguments", cli: "123", wants: ViewOptions{ Raw: true, Selector: "123", ListFiles: false, }, }, { name: "filename passed", cli: "-fcool.txt 123", tty: true, wants: ViewOptions{ Raw: false, Selector: "123", Filename: "cool.txt", ListFiles: false, }, }, { name: "files passed", cli: "--files 123", tty: true, wants: ViewOptions{ Raw: false, Selector: "123", ListFiles: true, }, }, { name: "tty no ID supplied", cli: "", tty: true, wants: ViewOptions{ Raw: false, Selector: "", ListFiles: true, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() ios.SetStdoutTTY(tt.tty) f := &cmdutil.Factory{ IOStreams: ios, } argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts *ViewOptions cmd := NewCmdView(f, func(opts *ViewOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err = cmd.ExecuteC() assert.NoError(t, err) assert.Equal(t, tt.wants.Raw, gotOpts.Raw) assert.Equal(t, tt.wants.Selector, gotOpts.Selector) assert.Equal(t, tt.wants.Filename, gotOpts.Filename) }) } } func Test_viewRun(t *testing.T) { tests := []struct { name string opts *ViewOptions wantOut string mockGist *shared.Gist mockGistList bool isTTY bool wantErr string }{ { name: "no such gist", isTTY: false, opts: &ViewOptions{ Selector: "1234", ListFiles: false, }, wantErr: "not found", }, { name: "one file", isTTY: true, opts: &ViewOptions{ Selector: "1234", ListFiles: false, }, mockGist: &shared.Gist{ Files: map[string]*shared.GistFile{ "cicada.txt": { Content: "bwhiizzzbwhuiiizzzz", Type: "text/plain", }, }, }, wantOut: "bwhiizzzbwhuiiizzzz\n", }, { name: "one file, no ID supplied", isTTY: true, opts: &ViewOptions{ Selector: "", ListFiles: false, }, mockGistList: true, mockGist: &shared.Gist{ Files: map[string]*shared.GistFile{ "cicada.txt": { Content: "test interactive mode", Type: "text/plain", }, }, }, wantOut: "test interactive mode\n", }, { name: "no arguments notty", isTTY: false, wantErr: "gist ID or URL required when not running interactively", }, { name: "filename selected", isTTY: true, opts: &ViewOptions{ Selector: "1234", Filename: "cicada.txt", ListFiles: false, }, mockGist: &shared.Gist{ Files: map[string]*shared.GistFile{ "cicada.txt": { Content: "bwhiizzzbwhuiiizzzz", Type: "text/plain", }, "foo.md": { Content: "# foo", Type: "application/markdown", }, }, }, wantOut: "bwhiizzzbwhuiiizzzz\n", }, { name: "filename selected, raw", isTTY: true, opts: &ViewOptions{ Selector: "1234", Filename: "cicada.txt", Raw: true, ListFiles: false, }, mockGist: &shared.Gist{ Files: map[string]*shared.GistFile{ "cicada.txt": { Content: "bwhiizzzbwhuiiizzzz", Type: "text/plain", }, "foo.md": { Content: "# foo", Type: "application/markdown", }, }, }, wantOut: "bwhiizzzbwhuiiizzzz\n", }, { name: "multiple files, no description", isTTY: true, opts: &ViewOptions{ Selector: "1234", ListFiles: false, }, mockGist: &shared.Gist{ Files: map[string]*shared.GistFile{ "cicada.txt": { Content: "bwhiizzzbwhuiiizzzz", Type: "text/plain", }, "foo.md": { Content: "# foo", Type: "application/markdown", }, }, }, wantOut: "cicada.txt\n\nbwhiizzzbwhuiiizzzz\n\nfoo.md\n\n\n # foo \n\n", }, { name: "multiple files, trailing newlines", isTTY: true, opts: &ViewOptions{ Selector: "1234", ListFiles: false, }, mockGist: &shared.Gist{ Files: map[string]*shared.GistFile{ "cicada.txt": { Content: "bwhiizzzbwhuiiizzzz\n", Type: "text/plain", }, "foo.txt": { Content: "bar\n", Type: "text/plain", }, }, }, wantOut: "cicada.txt\n\nbwhiizzzbwhuiiizzzz\n\nfoo.txt\n\nbar\n", }, { name: "multiple files, description", isTTY: true, opts: &ViewOptions{ Selector: "1234", ListFiles: false, }, mockGist: &shared.Gist{ Description: "some files", Files: map[string]*shared.GistFile{ "cicada.txt": { Content: "bwhiizzzbwhuiiizzzz", Type: "text/plain", }, "foo.md": { Content: "- foo", Type: "application/markdown", }, }, }, wantOut: "some files\n\ncicada.txt\n\nbwhiizzzbwhuiiizzzz\n\nfoo.md\n\n\n \n • foo \n\n", }, { name: "multiple files, raw", isTTY: true, opts: &ViewOptions{ Selector: "1234", Raw: true, ListFiles: false, }, mockGist: &shared.Gist{ Description: "some files", Files: map[string]*shared.GistFile{ "cicada.txt": { Content: "bwhiizzzbwhuiiizzzz", Type: "text/plain", }, "foo.md": { Content: "- foo", Type: "application/markdown", }, }, }, wantOut: "some files\n\ncicada.txt\n\nbwhiizzzbwhuiiizzzz\n\nfoo.md\n\n- foo\n", }, { name: "one file, list files", isTTY: true, opts: &ViewOptions{ Selector: "1234", Raw: false, ListFiles: true, }, mockGist: &shared.Gist{ Description: "some files", Files: map[string]*shared.GistFile{ "cicada.txt": { Content: "bwhiizzzbwhuiiizzzz", Type: "text/plain", }, }, }, wantOut: "cicada.txt\n", }, { name: "multiple file, list files", isTTY: true, opts: &ViewOptions{ Selector: "1234", Raw: false, ListFiles: true, }, mockGist: &shared.Gist{ Description: "some files", Files: map[string]*shared.GistFile{ "cicada.txt": { Content: "bwhiizzzbwhuiiizzzz", Type: "text/plain", }, "foo.md": { Content: "- foo", Type: "application/markdown", }, }, }, wantOut: "cicada.txt\nfoo.md\n", }, { name: "truncated file with raw and filename", isTTY: true, opts: &ViewOptions{ Selector: "1234", Raw: true, Filename: "large.txt", }, mockGist: &shared.Gist{ Files: map[string]*shared.GistFile{ "large.txt": { Content: "This is truncated content...", Type: "text/plain", Truncated: true, RawURL: "https://gist.githubusercontent.com/user/1234/raw/large.txt", }, }, }, wantOut: "This is the full content of the large file retrieved from raw URL\n", }, { name: "truncated file without raw flag", isTTY: true, opts: &ViewOptions{ Selector: "1234", Raw: false, Filename: "large.txt", }, mockGist: &shared.Gist{ Files: map[string]*shared.GistFile{ "large.txt": { Content: "This is truncated content...", Type: "text/plain", Truncated: true, RawURL: "https://gist.githubusercontent.com/user/1234/raw/large.txt", }, }, }, wantOut: "This is the full content of the large file retrieved from raw URL\n", }, { name: "multiple files with one truncated", isTTY: true, opts: &ViewOptions{ Selector: "1234", Raw: true, }, mockGist: &shared.Gist{ Description: "Mixed files", Files: map[string]*shared.GistFile{ "normal.txt": { Content: "normal content", Type: "text/plain", }, "large.txt": { Content: "This is truncated content...", Type: "text/plain", Truncated: true, RawURL: "https://gist.githubusercontent.com/user/1234/raw/large.txt", }, }, }, wantOut: "Mixed files\n\nlarge.txt\n\nThis is the full content of the large file retrieved from raw URL\n\nnormal.txt\n\nnormal content\n", }, { name: "multiple files with subsequent files truncated as empty", isTTY: true, opts: &ViewOptions{ Selector: "1234", Raw: true, }, mockGist: &shared.Gist{ Description: "Large gist with multiple files", Files: map[string]*shared.GistFile{ "large.txt": { Content: "This is truncated content...", Type: "text/plain", Truncated: true, RawURL: "https://gist.githubusercontent.com/user/1234/raw/large.txt", }, "also-truncated.txt": { Type: "text/plain", Content: "", // Empty because GitHub truncates subsequent files Truncated: true, // Subsequent files are also marked as truncated RawURL: "https://gist.githubusercontent.com/user/1234/raw/also-truncated.txt", }, }, }, wantOut: "Large gist with multiple files\n\nalso-truncated.txt\n\nThis is the full content of the also-truncated file retrieved from raw URL\n\nlarge.txt\n\nThis is the full content of the large file retrieved from raw URL\n", }, } for _, tt := range tests { reg := &httpmock.Registry{} if tt.mockGist == nil { reg.Register(httpmock.REST("GET", "gists/1234"), httpmock.StatusStringResponse(404, "Not Found")) } else { reg.Register(httpmock.REST("GET", "gists/1234"), httpmock.JSONResponse(tt.mockGist)) for filename, file := range tt.mockGist.Files { if file.Truncated && file.RawURL != "" { if filename == "large.txt" { reg.Register(httpmock.REST("GET", "user/1234/raw/large.txt"), httpmock.StringResponse("This is the full content of the large file retrieved from raw URL")) } else if filename == "also-truncated.txt" { reg.Register(httpmock.REST("GET", "user/1234/raw/also-truncated.txt"), httpmock.StringResponse("This is the full content of the also-truncated file retrieved from raw URL")) } } } } if tt.opts == nil { tt.opts = &ViewOptions{} } if tt.mockGistList { sixHours, _ := time.ParseDuration("6h") sixHoursAgo := time.Now().Add(-sixHours) reg.Register( httpmock.GraphQL(`query GistList\b`), httpmock.StringResponse(fmt.Sprintf( `{ "data": { "viewer": { "gists": { "nodes": [ { "name": "1234", "files": [{ "name": "cool.txt" }], "description": "", "updatedAt": "%s", "isPublic": true } ] } } } }`, sixHoursAgo.Format(time.RFC3339), )), ) pm := prompter.NewMockPrompter(t) pm.RegisterSelect("Select a gist", []string{"cool.txt about 6 hours ago"}, func(_, _ string, opts []string) (int, error) { return 0, nil }) tt.opts.Prompter = pm } tt.opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } tt.opts.Config = func() (gh.Config, error) { return config.NewBlankConfig(), nil } ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(tt.isTTY) ios.SetStdinTTY(tt.isTTY) ios.SetStderrTTY(tt.isTTY) tt.opts.IO = ios t.Run(tt.name, func(t *testing.T) { err := viewRun(tt.opts) if tt.wantErr != "" { require.EqualError(t, err, tt.wantErr) return } else { require.NoError(t, err) } assert.Equal(t, tt.wantOut, stdout.String()) reg.Verify(t) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/gist/create/create.go
pkg/cmd/gist/create/create.go
package create import ( "bytes" "encoding/json" "errors" "fmt" "io" "net/http" "os" "path/filepath" "regexp" "sort" "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/ghinstance" "github.com/cli/cli/v2/internal/text" "github.com/cli/cli/v2/pkg/cmd/gist/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type CreateOptions struct { IO *iostreams.IOStreams Description string Public bool Filenames []string FilenameOverride string WebMode bool Config func() (gh.Config, error) HttpClient func() (*http.Client, error) Browser browser.Browser } func NewCmdCreate(f *cmdutil.Factory, runF func(*CreateOptions) error) *cobra.Command { opts := CreateOptions{ IO: f.IOStreams, Config: f.Config, HttpClient: f.HttpClient, Browser: f.Browser, } cmd := &cobra.Command{ Use: "create [<filename>... | <pattern>... | -]", Short: "Create a new gist", Long: heredoc.Docf(` Create a new GitHub gist with given contents. Gists can be created from one or multiple files. Alternatively, pass %[1]s-%[1]s as filename to read from standard input. By default, gists are secret; use %[1]s--public%[1]s to make publicly listed ones. `, "`"), Example: heredoc.Doc(` # Publish file 'hello.py' as a public gist $ gh gist create --public hello.py # Create a gist with a description $ gh gist create hello.py -d "my Hello-World program in Python" # Create a gist containing several files $ gh gist create hello.py world.py cool.txt # Create a gist containing several files using patterns $ gh gist create *.md *.txt artifact.* # Read from standard input to create a gist $ gh gist create - # Create a gist from output piped from another command $ cat cool.txt | gh gist create `), Args: func(cmd *cobra.Command, args []string) error { if len(args) > 0 { return nil } if opts.IO.IsStdinTTY() { return cmdutil.FlagErrorf("no filenames passed and nothing on STDIN") } return nil }, Aliases: []string{"new"}, RunE: func(c *cobra.Command, args []string) error { opts.Filenames = args if runF != nil { return runF(&opts) } return createRun(&opts) }, } cmd.Flags().StringVarP(&opts.Description, "desc", "d", "", "A description for this gist") cmd.Flags().BoolVarP(&opts.WebMode, "web", "w", false, "Open the web browser with created gist") cmd.Flags().BoolVarP(&opts.Public, "public", "p", false, "List the gist publicly (default \"secret\")") cmd.Flags().StringVarP(&opts.FilenameOverride, "filename", "f", "", "Provide a filename to be used when reading from standard input") return cmd } func createRun(opts *CreateOptions) error { readFromStdInArg, filenames := cmdutil.Partition(opts.Filenames, func(f string) bool { return f == "-" }) filenames, err := cmdutil.GlobPaths(filenames) if err != nil { return err } filenames = append(filenames, readFromStdInArg...) if len(filenames) == 0 { filenames = []string{"-"} } files, err := processFiles(opts.IO.In, opts.FilenameOverride, filenames) if err != nil { return fmt.Errorf("failed to collect files for posting: %w", err) } errOut := opts.IO.ErrOut cs := opts.IO.ColorScheme() gistName := guessGistName(files) processMessage := "Creating gist..." if gistName != "" { if len(files) > 1 { processMessage = "Creating gist with multiple files" } else { processMessage = fmt.Sprintf("Creating gist %s", gistName) } } fmt.Fprintf(errOut, "%s %s\n", cs.Muted("-"), processMessage) httpClient, err := opts.HttpClient() if err != nil { return err } cfg, err := opts.Config() if err != nil { return err } host, _ := cfg.Authentication().DefaultHost() opts.IO.StartProgressIndicator() gist, err := createGist(httpClient, host, opts.Description, opts.Public, files) opts.IO.StopProgressIndicator() if err != nil { var httpError api.HTTPError if errors.As(err, &httpError) { if httpError.StatusCode == http.StatusUnprocessableEntity { if detectEmptyFiles(files) { fmt.Fprintf(errOut, "%s Failed to create gist: %s\n", cs.FailureIcon(), "a gist file cannot be blank") return cmdutil.SilentError } } } return fmt.Errorf("%s Failed to create gist: %w", cs.Red("X"), err) } completionMessage := fmt.Sprintf("Created %s gist", cs.Green("secret")) if opts.Public { completionMessage = fmt.Sprintf("Created %s gist", cs.Red("public")) } if gistName != "" { completionMessage += " " + gistName } fmt.Fprintf(errOut, "%s %s\n", cs.SuccessIconWithColor(cs.Green), completionMessage) if opts.WebMode { fmt.Fprintf(opts.IO.Out, "Opening %s in your browser.\n", text.DisplayURL(gist.HTMLURL)) return opts.Browser.Browse(gist.HTMLURL) } fmt.Fprintln(opts.IO.Out, gist.HTMLURL) return nil } func processFiles(stdin io.ReadCloser, filenameOverride string, filenames []string) (map[string]*shared.GistFile, error) { fs := map[string]*shared.GistFile{} if len(filenames) == 0 { return nil, errors.New("no files passed") } for i, f := range filenames { var filename string var content []byte var err error if f == "-" { if filenameOverride != "" { filename = filenameOverride } else { filename = fmt.Sprintf("gistfile%d.txt", i) } content, err = io.ReadAll(stdin) if err != nil { return fs, fmt.Errorf("failed to read from stdin: %w", err) } stdin.Close() if shared.IsBinaryContents(content) { return nil, fmt.Errorf("binary file contents not supported") } } else { isBinary, err := shared.IsBinaryFile(f) if err != nil { return fs, fmt.Errorf("failed to read file %s: %w", f, err) } if isBinary { return nil, fmt.Errorf("failed to upload %s: binary file not supported", f) } content, err = os.ReadFile(f) if err != nil { return fs, fmt.Errorf("failed to read file %s: %w", f, err) } filename = filepath.Base(f) } fs[filename] = &shared.GistFile{ Content: string(content), } } return fs, nil } func guessGistName(files map[string]*shared.GistFile) string { filenames := make([]string, 0, len(files)) gistName := "" re := regexp.MustCompile(`^gistfile\d+\.txt$`) for k := range files { if !re.MatchString(k) { filenames = append(filenames, k) } } if len(filenames) > 0 { sort.Strings(filenames) gistName = filenames[0] } return gistName } func createGist(client *http.Client, hostname, description string, public bool, files map[string]*shared.GistFile) (*shared.Gist, error) { body := &shared.Gist{ Description: description, Public: public, Files: files, } requestBody := &bytes.Buffer{} enc := json.NewEncoder(requestBody) if err := enc.Encode(body); err != nil { return nil, err } u := ghinstance.RESTPrefix(hostname) + "gists" req, err := http.NewRequest(http.MethodPost, u, requestBody) 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() if resp.StatusCode > 299 { api.EndpointNeedsScopes(resp, "gist") return nil, api.HandleHTTPError(resp) } result := &shared.Gist{} dec := json.NewDecoder(resp.Body) if err := dec.Decode(result); err != nil { return nil, err } return result, nil } func detectEmptyFiles(files map[string]*shared.GistFile) bool { for _, file := range files { if strings.TrimSpace(file.Content) == "" { return true } } return false }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/gist/create/create_test.go
pkg/cmd/gist/create/create_test.go
package create import ( "bytes" "encoding/json" "io" "net/http" "os" "path/filepath" "strings" "testing" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/browser" "github.com/cli/cli/v2/internal/config" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/run" "github.com/cli/cli/v2/pkg/cmd/gist/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" ) func Test_processFiles(t *testing.T) { fakeStdin := strings.NewReader("hey cool how is it going") files, err := processFiles(io.NopCloser(fakeStdin), "", []string{"-"}) if err != nil { t.Fatalf("unexpected error processing files: %s", err) } assert.Equal(t, 1, len(files)) assert.Equal(t, "hey cool how is it going", files["gistfile0.txt"].Content) } func Test_guessGistName_stdin(t *testing.T) { files := map[string]*shared.GistFile{ "gistfile0.txt": {Content: "sample content"}, } gistName := guessGistName(files) assert.Equal(t, "", gistName) } func Test_guessGistName_userFiles(t *testing.T) { files := map[string]*shared.GistFile{ "fig.txt": {Content: "I am a fig"}, "apple.txt": {Content: "I am an apple"}, "gistfile0.txt": {Content: "sample content"}, } gistName := guessGistName(files) assert.Equal(t, "apple.txt", gistName) } func TestNewCmdCreate(t *testing.T) { tests := []struct { name string cli string factory func(*cmdutil.Factory) *cmdutil.Factory wants CreateOptions wantsErr bool }{ { name: "no arguments", cli: "", wants: CreateOptions{ Description: "", Public: false, Filenames: []string{""}, }, wantsErr: false, }, { name: "no arguments with TTY stdin", factory: func(f *cmdutil.Factory) *cmdutil.Factory { f.IOStreams.SetStdinTTY(true) return f }, cli: "", wants: CreateOptions{ Description: "", Public: false, Filenames: []string{""}, }, wantsErr: true, }, { name: "stdin argument", cli: "-", wants: CreateOptions{ Description: "", Public: false, Filenames: []string{"-"}, }, wantsErr: false, }, { name: "with description", cli: `-d "my new gist" -`, wants: CreateOptions{ Description: "my new gist", Public: false, Filenames: []string{"-"}, }, wantsErr: false, }, { name: "public", cli: `--public -`, wants: CreateOptions{ Description: "", Public: true, Filenames: []string{"-"}, }, wantsErr: false, }, { name: "list of files", cli: "file1.txt file2.txt", wants: CreateOptions{ Description: "", Public: false, Filenames: []string{"file1.txt", "file2.txt"}, }, wantsErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() f := &cmdutil.Factory{ IOStreams: ios, } if tt.factory != nil { f = tt.factory(f) } argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts *CreateOptions cmd := NewCmdCreate(f, func(opts *CreateOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) return } assert.NoError(t, err) assert.Equal(t, tt.wants.Description, gotOpts.Description) assert.Equal(t, tt.wants.Public, gotOpts.Public) }) } } func Test_createRun(t *testing.T) { tempDir := t.TempDir() fixtureFile := filepath.Join(tempDir, "fixture.txt") assert.NoError(t, os.WriteFile(fixtureFile, []byte("{}"), 0644)) emptyFile := filepath.Join(tempDir, "empty.txt") assert.NoError(t, os.WriteFile(emptyFile, []byte(" \t\n"), 0644)) tests := []struct { name string opts *CreateOptions stdin string wantOut string wantStderr string wantParams map[string]interface{} wantErr bool wantBrowse string responseStatus int }{ { name: "public", opts: &CreateOptions{ Public: true, Filenames: []string{fixtureFile}, }, wantOut: "https://gist.github.com/aa5a315d61ae9438b18d\n", wantStderr: "- Creating gist fixture.txt\n✓ Created public gist fixture.txt\n", wantErr: false, wantParams: map[string]interface{}{ "description": "", "updated_at": "0001-01-01T00:00:00Z", "public": true, "files": map[string]interface{}{ "fixture.txt": map[string]interface{}{ "content": "{}", }, }, }, responseStatus: http.StatusOK, }, { name: "with description", opts: &CreateOptions{ Description: "an incredibly interesting gist", Filenames: []string{fixtureFile}, }, wantOut: "https://gist.github.com/aa5a315d61ae9438b18d\n", wantStderr: "- Creating gist fixture.txt\n✓ Created secret gist fixture.txt\n", wantErr: false, wantParams: map[string]interface{}{ "description": "an incredibly interesting gist", "updated_at": "0001-01-01T00:00:00Z", "public": false, "files": map[string]interface{}{ "fixture.txt": map[string]interface{}{ "content": "{}", }, }, }, responseStatus: http.StatusOK, }, { name: "when both a file and the stdin '-' are provided, it matches on all the files passed in and stdin", opts: &CreateOptions{ Filenames: []string{fixtureFile, "-"}, }, stdin: "cool stdin content", wantOut: "https://gist.github.com/aa5a315d61ae9438b18d\n", wantStderr: "- Creating gist with multiple files\n✓ Created secret gist fixture.txt\n", wantErr: false, wantParams: map[string]interface{}{ "description": "", "updated_at": "0001-01-01T00:00:00Z", "public": false, "files": map[string]interface{}{ "fixture.txt": map[string]interface{}{ "content": "{}", }, "gistfile1.txt": map[string]interface{}{ "content": "cool stdin content", }, }, }, responseStatus: http.StatusOK, }, { name: "when both a file and the stdin '-' are provided, but '-' is not the last argument, it matches on all the files provided and stdin", opts: &CreateOptions{ Filenames: []string{"-", fixtureFile}, }, stdin: "cool stdin content", wantOut: "https://gist.github.com/aa5a315d61ae9438b18d\n", wantStderr: "- Creating gist with multiple files\n✓ Created secret gist fixture.txt\n", wantErr: false, wantParams: map[string]interface{}{ "description": "", "updated_at": "0001-01-01T00:00:00Z", "public": false, "files": map[string]interface{}{ "fixture.txt": map[string]interface{}{ "content": "{}", }, "gistfile1.txt": map[string]interface{}{ "content": "cool stdin content", }, }, }, responseStatus: http.StatusOK, }, { name: "file with empty content", opts: &CreateOptions{ Filenames: []string{emptyFile}, }, wantOut: "", wantStderr: heredoc.Doc(` - Creating gist empty.txt X Failed to create gist: a gist file cannot be blank `), wantErr: true, wantParams: map[string]interface{}{ "description": "", "updated_at": "0001-01-01T00:00:00Z", "public": false, "files": map[string]interface{}{ "empty.txt": map[string]interface{}{"content": " \t\n"}, }, }, responseStatus: http.StatusUnprocessableEntity, }, { name: "stdin arg", opts: &CreateOptions{ Filenames: []string{"-"}, }, stdin: "cool stdin content", wantOut: "https://gist.github.com/aa5a315d61ae9438b18d\n", wantStderr: "- Creating gist...\n✓ Created secret gist\n", wantErr: false, wantParams: map[string]interface{}{ "description": "", "updated_at": "0001-01-01T00:00:00Z", "public": false, "files": map[string]interface{}{ "gistfile0.txt": map[string]interface{}{ "content": "cool stdin content", }, }, }, responseStatus: http.StatusOK, }, { name: "web arg", opts: &CreateOptions{ WebMode: true, Filenames: []string{fixtureFile}, }, wantOut: "Opening https://gist.github.com/aa5a315d61ae9438b18d in your browser.\n", wantStderr: "- Creating gist fixture.txt\n✓ Created secret gist fixture.txt\n", wantErr: false, wantBrowse: "https://gist.github.com/aa5a315d61ae9438b18d", wantParams: map[string]interface{}{ "description": "", "updated_at": "0001-01-01T00:00:00Z", "public": false, "files": map[string]interface{}{ "fixture.txt": map[string]interface{}{ "content": "{}", }, }, }, responseStatus: http.StatusOK, }, } for _, tt := range tests { reg := &httpmock.Registry{} if tt.responseStatus == http.StatusOK { reg.Register( httpmock.REST("POST", "gists"), httpmock.StringResponse(`{ "html_url": "https://gist.github.com/aa5a315d61ae9438b18d" }`)) } else { reg.Register( httpmock.REST("POST", "gists"), httpmock.StatusStringResponse(tt.responseStatus, "{}")) } mockClient := func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } tt.opts.HttpClient = mockClient tt.opts.Config = func() (gh.Config, error) { return config.NewBlankConfig(), nil } ios, stdin, stdout, stderr := iostreams.Test() tt.opts.IO = ios browser := &browser.Stub{} tt.opts.Browser = browser _, teardown := run.Stub() defer teardown(t) t.Run(tt.name, func(t *testing.T) { stdin.WriteString(tt.stdin) if err := createRun(tt.opts); (err != nil) != tt.wantErr { t.Errorf("createRun() error = %v, wantErr %v", err, tt.wantErr) } bodyBytes, _ := io.ReadAll(reg.Requests[0].Body) reqBody := make(map[string]interface{}) err := json.Unmarshal(bodyBytes, &reqBody) if err != nil { t.Fatalf("error decoding JSON: %v", err) } assert.Equal(t, tt.wantOut, stdout.String()) assert.Equal(t, tt.wantStderr, stderr.String()) assert.Equal(t, tt.wantParams, reqBody) reg.Verify(t) browser.Verify(t, tt.wantBrowse) }) } } func Test_detectEmptyFiles(t *testing.T) { tests := []struct { content string isEmptyFile bool }{ { content: "{}", isEmptyFile: false, }, { content: "\n\t", isEmptyFile: true, }, } for _, tt := range tests { files := map[string]*shared.GistFile{} files["file"] = &shared.GistFile{ Content: tt.content, } isEmptyFile := detectEmptyFiles(files) assert.Equal(t, tt.isEmptyFile, isEmptyFile) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/gist/clone/clone_test.go
pkg/cmd/gist/clone/clone_test.go
package clone import ( "net/http" "testing" "github.com/cli/cli/v2/git" "github.com/cli/cli/v2/internal/config" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/run" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/test" "github.com/google/shlex" "github.com/stretchr/testify/assert" ) func runCloneCommand(httpClient *http.Client, cli string) (*test.CmdOut, error) { ios, stdin, stdout, stderr := iostreams.Test() fac := &cmdutil.Factory{ IOStreams: ios, HttpClient: func() (*http.Client, error) { return httpClient, nil }, Config: func() (gh.Config, error) { return config.NewBlankConfig(), nil }, GitClient: &git.Client{ GhPath: "some/path/gh", GitPath: "some/path/git", }, } cmd := NewCmdClone(fac, nil) argv, err := shlex.Split(cli) cmd.SetArgs(argv) cmd.SetIn(stdin) cmd.SetOut(stderr) cmd.SetErr(stderr) if err != nil { panic(err) } _, err = cmd.ExecuteC() if err != nil { return nil, err } return &test.CmdOut{OutBuf: stdout, ErrBuf: stderr}, nil } func Test_GistClone(t *testing.T) { tests := []struct { name string args string want string }{ { name: "shorthand", args: "GIST", want: "git clone https://gist.github.com/GIST.git", }, { name: "shorthand with directory", args: "GIST target_directory", want: "git clone https://gist.github.com/GIST.git target_directory", }, { name: "clone arguments", args: "GIST -- -o upstream --depth 1", want: "git clone -o upstream --depth 1 https://gist.github.com/GIST.git", }, { name: "clone arguments with directory", args: "GIST target_directory -- -o upstream --depth 1", want: "git clone -o upstream --depth 1 https://gist.github.com/GIST.git target_directory", }, { name: "HTTPS URL", args: "https://gist.github.com/OWNER/GIST", want: "git clone https://gist.github.com/OWNER/GIST", }, { name: "SSH URL", args: "git@gist.github.com:GIST.git", want: "git clone git@gist.github.com:GIST.git", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { reg := &httpmock.Registry{} defer reg.Verify(t) httpClient := &http.Client{Transport: reg} cs, restore := run.Stub() defer restore(t) cs.Register(tt.want, 0, "") output, err := runCloneCommand(httpClient, tt.args) if err != nil { t.Fatalf("error running command `gist clone`: %v", err) } assert.Equal(t, "", output.String()) assert.Equal(t, "", output.Stderr()) }) } } func Test_GistClone_flagError(t *testing.T) { _, err := runCloneCommand(nil, "--depth 1 GIST") if err == nil || err.Error() != "unknown flag: --depth\nSeparate git clone flags with '--'." { t.Errorf("unexpected error %v", err) } } func Test_formatRemoteURL(t *testing.T) { type args struct { hostname string gistID string protocol string } tests := []struct { name string args args want string }{ { name: "github.com HTTPS", args: args{ hostname: "github.com", protocol: "https", gistID: "ID", }, want: "https://gist.github.com/ID.git", }, { name: "github.com SSH", args: args{ hostname: "github.com", protocol: "ssh", gistID: "ID", }, want: "git@gist.github.com:ID.git", }, { name: "Enterprise HTTPS", args: args{ hostname: "acme.org", protocol: "https", gistID: "ID", }, want: "https://acme.org/gist/ID.git", }, { name: "Enterprise SSH", args: args{ hostname: "acme.org", protocol: "ssh", gistID: "ID", }, want: "git@acme.org:gist/ID.git", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := formatRemoteURL(tt.args.hostname, tt.args.gistID, tt.args.protocol); got != tt.want { t.Errorf("formatRemoteURL() = %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/gist/clone/clone.go
pkg/cmd/gist/clone/clone.go
package clone import ( "context" "fmt" "net/http" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/git" "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" "github.com/spf13/pflag" ghauth "github.com/cli/go-gh/v2/pkg/auth" ) type CloneOptions struct { HttpClient func() (*http.Client, error) GitClient *git.Client Config func() (gh.Config, error) IO *iostreams.IOStreams GitArgs []string Directory string Gist string } func NewCmdClone(f *cmdutil.Factory, runF func(*CloneOptions) error) *cobra.Command { opts := &CloneOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, GitClient: f.GitClient, Config: f.Config, } cmd := &cobra.Command{ DisableFlagsInUseLine: true, Use: "clone <gist> [<directory>] [-- <gitflags>...]", Args: cmdutil.MinimumArgs(1, "cannot clone: gist argument required"), Short: "Clone a gist locally", Long: heredoc.Docf(` Clone a GitHub gist locally. A gist can be supplied as argument in either of the following formats: - by ID, e.g. %[1]s5b0e0062eb8e9654adad7bb1d81cc75f%[1]s - by URL, e.g. %[1]shttps://gist.github.com/OWNER/5b0e0062eb8e9654adad7bb1d81cc75f%[1]s Pass additional %[1]sgit clone%[1]s flags by listing them after %[1]s--%[1]s. `, "`"), RunE: func(cmd *cobra.Command, args []string) error { opts.Gist = args[0] opts.GitArgs = args[1:] if runF != nil { return runF(opts) } return cloneRun(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) }) return cmd } func cloneRun(opts *CloneOptions) error { gistURL := opts.Gist if !git.IsURL(gistURL) { cfg, err := opts.Config() if err != nil { return err } hostname, _ := cfg.Authentication().DefaultHost() protocol := cfg.GitProtocol(hostname).Value gistURL = formatRemoteURL(hostname, gistURL, protocol) } _, err := opts.GitClient.Clone(context.Background(), gistURL, opts.GitArgs) if err != nil { return err } return nil } func formatRemoteURL(hostname string, gistID string, protocol string) string { if ghauth.IsEnterprise(hostname) { if protocol == "ssh" { return fmt.Sprintf("git@%s:gist/%s.git", hostname, gistID) } return fmt.Sprintf("https://%s/gist/%s.git", hostname, gistID) } if protocol == "ssh" { return fmt.Sprintf("git@gist.%s:%s.git", hostname, gistID) } return fmt.Sprintf("https://gist.%s/%s.git", hostname, gistID) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/gist/shared/shared_test.go
pkg/cmd/gist/shared/shared_test.go
package shared import ( "fmt" "net/http" "testing" "time" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/stretchr/testify/assert" ) func Test_GetGistIDFromURL(t *testing.T) { tests := []struct { name string url string want string wantErr bool }{ { name: "url", url: "https://gist.github.com/1234", want: "1234", }, { name: "url with username", url: "https://gist.github.com/octocat/1234", want: "1234", }, { name: "url, specific file", url: "https://gist.github.com/1234#file-test-md", want: "1234", }, { name: "invalid url", url: "https://gist.github.com", wantErr: true, want: "Invalid gist URL https://gist.github.com", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { id, err := GistIDFromURL(tt.url) if tt.wantErr { assert.Error(t, err) assert.EqualError(t, err, tt.want) return } assert.NoError(t, err) assert.Equal(t, tt.want, id) }) } } func TestIsBinaryContents(t *testing.T) { tests := []struct { fileContent []byte want bool }{ { want: false, fileContent: []byte("package main"), }, { want: false, fileContent: []byte(""), }, { want: false, fileContent: []byte(nil), }, { want: true, fileContent: []byte{239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 16, 74, 70, 73, 70, 239, 191, 189, 1, 1, 1, 1, 44, 1, 44, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 67, 239, 191, 189, 8, 6, 6, 7, 6, 5, 8, 7, 7, 7, 9, 9, 8, 10, 12, 20, 10, 12, 11, 11, 12, 25, 18, 19, 15, 20, 29, 26, 31, 30, 29, 26, 28, 28, 32, 36, 46, 39, 32, 34, 44, 35, 28, 28, 40, 55, 41, 44, 48, 49, 52, 52, 52, 31, 39, 57, 61, 56, 50, 60, 46, 51, 52, 50, 239, 191, 189, 239, 191, 189, 239, 191, 189, 67, 1, 9, 9, 9, 12}, }, } for _, tt := range tests { assert.Equal(t, tt.want, IsBinaryContents(tt.fileContent)) } } func TestPromptGists(t *testing.T) { sixHours, _ := time.ParseDuration("6h") sixHoursAgo := time.Now().Add(-sixHours) sixHoursAgoFormatted := sixHoursAgo.Format(time.RFC3339Nano) tests := []struct { name string prompterStubs func(pm *prompter.MockPrompter) response string wantOut Gist wantErr bool }{ { name: "multiple files, select first gist", prompterStubs: func(pm *prompter.MockPrompter) { pm.RegisterSelect("Select a gist", []string{"cool.txt about 6 hours ago", "gistfile0.txt about 6 hours ago"}, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "cool.txt about 6 hours ago") }) }, response: `{ "data": { "viewer": { "gists": { "nodes": [ { "name": "1234", "files": [{ "name": "cool.txt" }], "description": "", "updatedAt": "%[1]v", "isPublic": true }, { "name": "5678", "files": [{ "name": "gistfile0.txt" }], "description": "", "updatedAt": "%[1]v", "isPublic": true } ] } } } }`, wantOut: Gist{ID: "1234", Files: map[string]*GistFile{"cool.txt": {Filename: "cool.txt"}}, UpdatedAt: sixHoursAgo, Public: true}, }, { name: "multiple files, select second gist", prompterStubs: func(pm *prompter.MockPrompter) { pm.RegisterSelect("Select a gist", []string{"cool.txt about 6 hours ago", "gistfile0.txt about 6 hours ago"}, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "gistfile0.txt about 6 hours ago") }) }, response: `{ "data": { "viewer": { "gists": { "nodes": [ { "name": "1234", "files": [{ "name": "cool.txt" }], "description": "", "updatedAt": "%[1]v", "isPublic": true }, { "name": "5678", "files": [{ "name": "gistfile0.txt" }], "description": "", "updatedAt": "%[1]v", "isPublic": true } ] } } } }`, wantOut: Gist{ID: "5678", Files: map[string]*GistFile{"gistfile0.txt": {Filename: "gistfile0.txt"}}, UpdatedAt: sixHoursAgo, Public: true}, }, { name: "no files", response: `{ "data": { "viewer": { "gists": { "nodes": [] } } } }`, wantOut: Gist{}, }, { name: "prompt list contains no-file gist (#10626)", prompterStubs: func(pm *prompter.MockPrompter) { pm.RegisterSelect("Select a gist", []string{" about 6 hours ago", "gistfile0.txt about 6 hours ago"}, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, " about 6 hours ago") }) }, response: `{ "data": { "viewer": { "gists": { "nodes": [ { "name": "1234", "files": [], "description": "", "updatedAt": "%[1]v", "isPublic": true }, { "name": "5678", "files": [{ "name": "gistfile0.txt" }], "description": "", "updatedAt": "%[1]v", "isPublic": true } ] } } } }`, wantOut: Gist{ID: "1234", Files: map[string]*GistFile{}, UpdatedAt: sixHoursAgo, Public: true}, }, } ios, _, _, _ := iostreams.Test() for _, tt := range tests { reg := &httpmock.Registry{} const query = `query GistList\b` reg.Register( httpmock.GraphQL(query), httpmock.StringResponse(fmt.Sprintf( tt.response, sixHoursAgoFormatted, )), ) client := &http.Client{Transport: reg} t.Run(tt.name, func(t *testing.T) { mockPrompter := prompter.NewMockPrompter(t) if tt.prompterStubs != nil { tt.prompterStubs(mockPrompter) } gist, err := PromptGists(mockPrompter, client, "github.com", ios.ColorScheme()) assert.NoError(t, err) assert.Equal(t, tt.wantOut.ID, gist.ID) reg.Verify(t) }) } } func TestGetRawGistFile(t *testing.T) { tests := []struct { name string response string statusCode int want string wantErr bool errContains string }{ { name: "successful request", response: "Hello, World!", statusCode: http.StatusOK, want: "Hello, World!", wantErr: false, }, { name: "empty response", response: "", statusCode: http.StatusOK, want: "", wantErr: false, }, { name: "not found error", response: "Not Found", statusCode: http.StatusNotFound, want: "", wantErr: true, errContains: "HTTP 404", }, { name: "server error", response: "Internal Server Error", statusCode: http.StatusInternalServerError, want: "", wantErr: true, errContains: "HTTP 500", }, { name: "large content", response: "This is a very large file content with multiple lines\nLine 2\nLine 3\nAnd more content...", statusCode: http.StatusOK, want: "This is a very large file content with multiple lines\nLine 2\nLine 3\nAnd more content...", wantErr: false, }, { name: "special characters", response: "Special chars: àáâãäåæçèéêë 中文 🎉 \"quotes\" 'single'", statusCode: http.StatusOK, want: "Special chars: àáâãäåæçèéêë 中文 🎉 \"quotes\" 'single'", wantErr: false, }, { name: "JSON content", response: `{"name": "test", "version": "1.0.0", "dependencies": {"lodash": "^4.17.21"}}`, statusCode: http.StatusOK, want: `{"name": "test", "version": "1.0.0", "dependencies": {"lodash": "^4.17.21"}}`, wantErr: false, }, { name: "HTML content", response: "<!DOCTYPE html><html><head><title>Test</title></head><body><h1>Hello</h1></body></html>", statusCode: http.StatusOK, want: "<!DOCTYPE html><html><head><title>Test</title></head><body><h1>Hello</h1></body></html>", wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { reg := &httpmock.Registry{} reg.Register( httpmock.REST("GET", "raw-url"), httpmock.StatusStringResponse(tt.statusCode, tt.response), ) client := &http.Client{Transport: reg} result, err := GetRawGistFile(client, "https://gist.githubusercontent.com/raw-url") if tt.wantErr { assert.Error(t, err) if tt.errContains != "" { assert.Contains(t, err.Error(), tt.errContains) } } else { assert.NoError(t, err) assert.Equal(t, tt.want, result) } reg.Verify(t) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/gist/shared/shared.go
pkg/cmd/gist/shared/shared.go
package shared import ( "errors" "fmt" "io" "net/http" "net/url" "regexp" "sort" "strings" "time" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/internal/text" "github.com/cli/cli/v2/pkg/iostreams" "github.com/gabriel-vasile/mimetype" "github.com/shurcooL/githubv4" ) type GistFile struct { Filename string `json:"filename,omitempty"` Type string `json:"type,omitempty"` Language string `json:"language,omitempty"` Content string `json:"content"` RawURL string `json:"raw_url,omitempty"` Truncated bool `json:"truncated,omitempty"` } type GistOwner struct { Login string `json:"login,omitempty"` } type Gist struct { ID string `json:"id,omitempty"` Description string `json:"description"` Files map[string]*GistFile `json:"files"` UpdatedAt time.Time `json:"updated_at"` Public bool `json:"public"` HTMLURL string `json:"html_url,omitempty"` Owner *GistOwner `json:"owner,omitempty"` } func (g Gist) Filename() string { filenames := make([]string, 0, len(g.Files)) for fn := range g.Files { filenames = append(filenames, fn) } if len(filenames) == 0 { return "" } sort.Strings(filenames) return filenames[0] } func (g Gist) TruncDescription() string { return text.Truncate(100, text.RemoveExcessiveWhitespace(g.Description)) } var NotFoundErr = errors.New("not found") func GetGist(client *http.Client, hostname, gistID string) (*Gist, error) { gist := Gist{} path := fmt.Sprintf("gists/%s", gistID) apiClient := api.NewClientFromHTTP(client) err := apiClient.REST(hostname, "GET", path, nil, &gist) if err != nil { var httpErr api.HTTPError if errors.As(err, &httpErr) && httpErr.StatusCode == 404 { return nil, NotFoundErr } return nil, err } return &gist, nil } func GistIDFromURL(gistURL string) (string, error) { u, err := url.Parse(gistURL) if err == nil && strings.HasPrefix(u.Path, "/") { split := strings.Split(u.Path, "/") if len(split) > 2 { return split[2], nil } if len(split) == 2 && split[1] != "" { return split[1], nil } } return "", fmt.Errorf("Invalid gist URL %s", u) } const maxPerPage = 100 func ListGists(client *http.Client, hostname string, limit int, filter *regexp.Regexp, includeContent bool, visibility string) ([]Gist, error) { type response struct { Viewer struct { Gists struct { Nodes []struct { Description string Files []struct { Name string Text string `graphql:"text @include(if: $includeContent)"` } IsPublic bool Name string UpdatedAt time.Time } PageInfo struct { HasNextPage bool EndCursor string } } `graphql:"gists(first: $per_page, after: $endCursor, privacy: $visibility, orderBy: {field: CREATED_AT, direction: DESC})"` } } perPage := limit if perPage > maxPerPage { perPage = maxPerPage } variables := map[string]interface{}{ "per_page": githubv4.Int(perPage), "endCursor": (*githubv4.String)(nil), "visibility": githubv4.GistPrivacy(strings.ToUpper(visibility)), "includeContent": githubv4.Boolean(includeContent), } filterFunc := func(gist *Gist) bool { if filter.MatchString(gist.Description) { return true } for _, file := range gist.Files { if filter.MatchString(file.Filename) { return true } if includeContent && filter.MatchString(file.Content) { return true } } return false } gql := api.NewClientFromHTTP(client) gists := []Gist{} pagination: for { var result response err := gql.Query(hostname, "GistList", &result, variables) if err != nil { return nil, err } for _, gist := range result.Viewer.Gists.Nodes { files := map[string]*GistFile{} for _, file := range gist.Files { files[file.Name] = &GistFile{ Filename: file.Name, Content: file.Text, } } gist := Gist{ ID: gist.Name, Description: gist.Description, Files: files, UpdatedAt: gist.UpdatedAt, Public: gist.IsPublic, } if filter == nil || filterFunc(&gist) { gists = append(gists, gist) } if len(gists) == limit { break pagination } } if !result.Viewer.Gists.PageInfo.HasNextPage { break } variables["endCursor"] = githubv4.String(result.Viewer.Gists.PageInfo.EndCursor) } return gists, nil } func IsBinaryFile(file string) (bool, error) { detectedMime, err := mimetype.DetectFile(file) if err != nil { return false, err } isBinary := true for mime := detectedMime; mime != nil; mime = mime.Parent() { if mime.Is("text/plain") { isBinary = false break } } return isBinary, nil } func IsBinaryContents(contents []byte) bool { isBinary := true for mime := mimetype.Detect(contents); mime != nil; mime = mime.Parent() { if mime.Is("text/plain") { isBinary = false break } } return isBinary } func PromptGists(prompter prompter.Prompter, client *http.Client, host string, cs *iostreams.ColorScheme) (gist *Gist, err error) { gists, err := ListGists(client, host, 10, nil, false, "all") if err != nil { return &Gist{}, err } if len(gists) == 0 { return &Gist{}, nil } var opts = make([]string, len(gists)) for i, gist := range gists { gistTime := text.FuzzyAgo(time.Now(), gist.UpdatedAt) // TODO: support dynamic maxWidth opts[i] = fmt.Sprintf("%s %s %s", cs.Bold(gist.Filename()), gist.TruncDescription(), cs.Muted(gistTime)) } result, err := prompter.Select("Select a gist", "", opts) if err != nil { return &Gist{}, err } return &gists[result], nil } func GetRawGistFile(httpClient *http.Client, rawURL string) (string, error) { req, err := http.NewRequest("GET", rawURL, nil) if err != nil { return "", err } resp, err := httpClient.Do(req) if err != nil { return "", err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return "", api.HandleHTTPError(resp) } body, err := io.ReadAll(resp.Body) if err != nil { return "", err } return string(body), nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/attestation.go
pkg/cmd/attestation/attestation.go
package attestation import ( "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/pkg/cmd/attestation/download" "github.com/cli/cli/v2/pkg/cmd/attestation/inspect" "github.com/cli/cli/v2/pkg/cmd/attestation/trustedroot" "github.com/cli/cli/v2/pkg/cmd/attestation/verify" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/spf13/cobra" ) func NewCmdAttestation(f *cmdutil.Factory) *cobra.Command { root := &cobra.Command{ Use: "attestation [subcommand]", Short: "Work with artifact attestations", Aliases: []string{"at"}, Long: heredoc.Doc(` Download and verify artifact attestations. `), } root.AddCommand(download.NewDownloadCmd(f, nil)) root.AddCommand(inspect.NewInspectCmd(f, nil)) root.AddCommand(verify.NewVerifyCmd(f, nil)) root.AddCommand(trustedroot.NewTrustedRootCmd(f, nil)) return root }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/verify/policy.go
pkg/cmd/attestation/verify/policy.go
package verify import ( "errors" "fmt" "regexp" "strings" "github.com/sigstore/sigstore-go/pkg/fulcio/certificate" "github.com/sigstore/sigstore-go/pkg/verify" "github.com/cli/cli/v2/pkg/cmd/attestation/artifact" "github.com/cli/cli/v2/pkg/cmd/attestation/verification" ) const hostRegex = `^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+.*$` func expandToGitHubURL(tenant, ownerOrRepo string) string { if tenant == "" { return fmt.Sprintf("https://github.com/%s", ownerOrRepo) } return fmt.Sprintf("https://%s.ghe.com/%s", tenant, ownerOrRepo) } func expandToGitHubURLRegex(tenant, ownerOrRepo string) string { url := expandToGitHubURL(tenant, ownerOrRepo) return fmt.Sprintf("(?i)^%s/", url) } func newEnforcementCriteria(opts *Options) (verification.EnforcementCriteria, error) { // initialize the enforcement criteria with the provided PredicateType c := verification.EnforcementCriteria{ PredicateType: opts.PredicateType, } // set the owner value by checking the repo and owner options var owner string if opts.Repo != "" { // we expect the repo argument to be in the format <OWNER>/<REPO> splitRepo := strings.Split(opts.Repo, "/") // if Repo is provided but owner is not, set the OWNER portion of the Repo value // to Owner owner = splitRepo[0] } else { // otherwise use the user provided owner value owner = opts.Owner } // Set the SANRegex and SAN values using the provided options // First check if the opts.SANRegex or opts.SAN values are provided if opts.SANRegex != "" || opts.SAN != "" { c.SANRegex = opts.SANRegex c.SAN = opts.SAN } else if opts.SignerRepo != "" { // next check if opts.SignerRepo was provided signedRepoRegex := expandToGitHubURLRegex(opts.Tenant, opts.SignerRepo) c.SANRegex = signedRepoRegex } else if opts.SignerWorkflow != "" { validatedWorkflowRegex, err := validateSignerWorkflow(opts.Hostname, opts.SignerWorkflow) if err != nil { return verification.EnforcementCriteria{}, err } c.SANRegex = validatedWorkflowRegex } else if opts.Repo != "" { // if the user has not provided the SAN, SANRegex, SignerRepo, or SignerWorkflow options // then we default to the repo option c.SANRegex = expandToGitHubURLRegex(opts.Tenant, opts.Repo) } else { // if opts.Repo was not provided, we fall back to the opts.Owner value c.SANRegex = expandToGitHubURLRegex(opts.Tenant, owner) } // if the DenySelfHostedRunner option is set to true, set the // RunnerEnvironment extension to the GitHub hosted runner value if opts.DenySelfHostedRunner { c.Certificate.RunnerEnvironment = verification.GitHubRunner } else { // if Certificate.RunnerEnvironment value is set to the empty string // through the second function argument, // no certificate matching will happen on the RunnerEnvironment field c.Certificate.RunnerEnvironment = "" } // If the Repo option is provided, set the SourceRepositoryURI extension if opts.Repo != "" { c.Certificate.SourceRepositoryURI = expandToGitHubURL(opts.Tenant, opts.Repo) } // Set the SourceRepositoryOwnerURI extension using owner and tenant if provided c.Certificate.SourceRepositoryOwnerURI = expandToGitHubURL(opts.Tenant, owner) // if the tenant is provided and OIDC issuer provided matches the default // use the tenant-specific issuer if opts.Tenant != "" && opts.OIDCIssuer == verification.GitHubOIDCIssuer { c.Certificate.Issuer = fmt.Sprintf(verification.GitHubTenantOIDCIssuer, opts.Tenant) } else { // otherwise use the custom OIDC issuer provided as an option c.Certificate.Issuer = opts.OIDCIssuer } // set the SourceRepositoryDigest, SourceRepositoryRef, and BuildSignerDigest // extensions if the options are provided c.Certificate.BuildSignerDigest = opts.SignerDigest c.Certificate.SourceRepositoryDigest = opts.SourceDigest c.Certificate.SourceRepositoryRef = opts.SourceRef return c, nil } func buildCertificateIdentityOption(c verification.EnforcementCriteria) (verify.PolicyOption, error) { sanMatcher, err := verify.NewSANMatcher(c.SAN, c.SANRegex) if err != nil { return nil, err } // Accept any issuer, we will verify the issuer as part of the extension verification issuerMatcher, err := verify.NewIssuerMatcher("", ".*") if err != nil { return nil, err } extensions := certificate.Extensions{ RunnerEnvironment: c.Certificate.RunnerEnvironment, } certId, err := verify.NewCertificateIdentity(sanMatcher, issuerMatcher, extensions) if err != nil { return nil, err } return verify.WithCertificateIdentity(certId), nil } func buildSigstoreVerifyPolicy(c verification.EnforcementCriteria, a artifact.DigestedArtifact) (verify.PolicyBuilder, error) { artifactDigestPolicyOption, err := verification.BuildDigestPolicyOption(a) if err != nil { return verify.PolicyBuilder{}, err } certIdOption, err := buildCertificateIdentityOption(c) if err != nil { return verify.PolicyBuilder{}, err } policy := verify.NewPolicy(artifactDigestPolicyOption, certIdOption) return policy, nil } func validateSignerWorkflow(hostname, signerWorkflow string) (string, error) { // we expect a provided workflow argument be in the format [HOST/]/<OWNER>/<REPO>/path/to/workflow.yml // if the provided workflow does not contain a host, set the host match, err := regexp.MatchString(hostRegex, signerWorkflow) if err != nil { return "", err } if match { return fmt.Sprintf("^https://%s", signerWorkflow), nil } // if the provided workflow did not match the expect format // we move onto creating a signer workflow using the provided host name if hostname == "" { return "", errors.New("unknown signer workflow host") } return fmt.Sprintf("^https://%s/%s", hostname, signerWorkflow), nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/verify/verify.go
pkg/cmd/attestation/verify/verify.go
package verify import ( "errors" "fmt" "regexp" "github.com/cli/cli/v2/internal/ghinstance" "github.com/cli/cli/v2/internal/text" "github.com/cli/cli/v2/pkg/cmd/attestation/api" "github.com/cli/cli/v2/pkg/cmd/attestation/artifact" "github.com/cli/cli/v2/pkg/cmd/attestation/artifact/oci" "github.com/cli/cli/v2/pkg/cmd/attestation/auth" "github.com/cli/cli/v2/pkg/cmd/attestation/io" "github.com/cli/cli/v2/pkg/cmd/attestation/verification" "github.com/cli/cli/v2/pkg/cmdutil" ghauth "github.com/cli/go-gh/v2/pkg/auth" "github.com/MakeNowJust/heredoc" "github.com/spf13/cobra" ) func NewVerifyCmd(f *cmdutil.Factory, runF func(*Options) error) *cobra.Command { opts := &Options{} verifyCmd := &cobra.Command{ Use: "verify [<file-path> | oci://<image-uri>] [--owner | --repo]", Args: cmdutil.ExactArgs(1, "must specify file path or container image URI, as well as one of --owner or --repo"), Short: "Verify an artifact's integrity using attestations", Long: heredoc.Docf(` Verify the integrity and provenance of an artifact using its associated cryptographically signed attestations. ## Understanding Verification An attestation is a claim (i.e. a provenance statement) made by an actor (i.e. a GitHub Actions workflow) regarding a subject (i.e. an artifact). In order to verify an attestation, you must provide an artifact and validate: * the identity of the actor that produced the attestation * the expected attestation predicate type (the nature of the claim) By default, this command enforces the %[1]s%[2]s%[1]s predicate type. To verify other attestation predicate types use the %[1]s--predicate-type%[1]s flag. The "actor identity" consists of: * the repository or the repository owner the artifact is linked with * the Actions workflow that produced the attestation (a.k.a the signer workflow) This identity is then validated against the attestation's certificate's SourceRepository, SourceRepositoryOwner, and SubjectAlternativeName (SAN) fields, among others. It is up to you to decide how precisely you want to enforce this identity. At a minimum, this command requires either: * the %[1]s--owner%[1]s flag (e.g. --owner github), or * the %[1]s--repo%[1]s flag (e.g. --repo github/example) The more precisely you specify the identity, the more control you will have over the security guarantees offered by the verification process. Ideally, the path of the signer workflow is also validated using the %[1]s--signer-workflow%[1]s or %[1]s--cert-identity%[1]s flags. Please note: if your attestation was generated via a reusable workflow then that reusable workflow is the signer whose identity needs to be validated. In this situation, you must use either the %[1]s--signer-workflow%[1]s or the %[1]s--signer-repo%[1]s flag. For more options, see the other available flags. ## Loading Artifacts And Attestations To specify the artifact, this command requires: * a file path to an artifact, or * a container image URI (e.g. %[1]soci://<image-uri>%[1]s) * (note that if you provide an OCI URL, you must already be authenticated with its container registry) By default, this command will attempt to fetch relevant attestations via the GitHub API using the values provided to %[1]s--owner%[1]s or %[1]s--repo%[1]s. To instead fetch attestations from your artifact's OCI registry, use the %[1]s--bundle-from-oci%[1]s flag. For offline verification using attestations stored on disk (c.f. the download command) provide a path to the %[1]s--bundle%[1]s flag. ## Additional Policy Enforcement Given the %[1]s--format=json%[1]s flag, upon successful verification this command will output a JSON array containing one entry per verified attestation. This output can then be used for additional policy enforcement, i.e. by being piped into a policy engine. Each object in the array contains two properties: * an %[1]sattestation%[1]s object, which contains the bundle that was verified * a %[1]sverificationResult%[1]s object, which is a parsed representation of the contents of the bundle that was verified. Within the %[1]sverificationResult%[1]s object you will find: * %[1]ssignature.certificate%[1]s, which is a parsed representation of the X.509 certificate embedded in the attestation, * %[1]sverifiedTimestamps%[1]s, an array of objects denoting when the attestation was witnessed by a transparency log or a timestamp authority * %[1]sstatement%[1]s, which contains the %[1]ssubject%[1]s array referencing artifacts, the %[1]spredicateType%[1]s field, and the %[1]spredicate%[1]s object which contains additional, often user-controllable, metadata IMPORTANT: please note that only the %[1]ssignature.certificate%[1]s and the %[1]sverifiedTimestamps%[1]s properties contain values that cannot be manipulated by the workflow that originated the attestation. When dealing with attestations created within GitHub Actions, the contents of %[1]ssignature.certificate%[1]s are populated directly from the OpenID Connect token that GitHub has generated. The contents of the %[1]sverifiedTimestamps%[1]s array are populated from the signed timestamps originating from either a transparency log or a timestamp authority – and likewise cannot be forged by users. When designing policy enforcement using this output, special care must be taken when examining the contents of the %[1]sstatement.predicate%[1]s property: should an attacker gain access to your workflow's execution context, they could then falsify the contents of the %[1]sstatement.predicate%[1]s. To mitigate this attack vector, consider using a "trusted builder": when generating an artifact, have the build and attestation signing occur within a reusable workflow whose execution cannot be influenced by input provided through the caller workflow. See above re: %[1]s--signer-workflow%[1]s. `, "`", verification.SLSAPredicateV1), Example: heredoc.Doc(` # Verify an artifact linked with a repository $ gh attestation verify example.bin --repo github/example # Verify an artifact linked with an organization $ gh attestation verify example.bin --owner github # Verify an artifact and output the full verification result $ gh attestation verify example.bin --owner github --format json # Verify an OCI image using attestations stored on disk $ gh attestation verify oci://<image-uri> --owner github --bundle sha256:foo.jsonl # Verify an artifact signed with a reusable workflow $ gh attestation verify example.bin --owner github --signer-repo actions/example `), // PreRunE is used to validate flags before the command is run // If an error is returned, its message will be printed to the terminal // along with information about how use the command PreRunE: func(cmd *cobra.Command, args []string) error { // Create a logger for use throughout the verify command opts.Logger = io.NewHandler(f.IOStreams) // set the artifact path opts.ArtifactPath = args[0] // Check that the given flag combination is valid if err := opts.AreFlagsValid(); err != nil { return err } // Clean file path options opts.Clean() return nil }, RunE: func(cmd *cobra.Command, args []string) error { hc, err := f.HttpClient() if err != nil { return err } opts.OCIClient = oci.NewLiveClient() if opts.Hostname == "" { opts.Hostname, _ = ghauth.DefaultHost() } err = auth.IsHostSupported(opts.Hostname) if err != nil { return err } opts.APIClient = api.NewLiveClient(hc, opts.Hostname, opts.Logger) config := verification.SigstoreConfig{ HttpClient: hc, Logger: opts.Logger, NoPublicGood: opts.NoPublicGood, TrustedRoot: opts.TrustedRoot, } // Prepare for tenancy if detected if ghauth.IsTenancy(opts.Hostname) { td, err := opts.APIClient.GetTrustDomain() if err != nil { return fmt.Errorf("error getting trust domain, make sure you are authenticated against the host: %w", err) } tenant, found := ghinstance.TenantName(opts.Hostname) if !found { return fmt.Errorf("invalid hostname provided: '%s'", opts.Hostname) } config.TrustDomain = td opts.Tenant = tenant } if runF != nil { return runF(opts) } sigstoreVerifier, err := verification.NewLiveSigstoreVerifier(config) if err != nil { return fmt.Errorf("error creating Sigstore verifier: %w", err) } opts.SigstoreVerifier = sigstoreVerifier opts.Config = f.Config if err := runVerify(opts); err != nil { return fmt.Errorf("\nError: %v", err) } return nil }, } // general flags verifyCmd.Flags().StringVarP(&opts.BundlePath, "bundle", "b", "", "Path to bundle on disk, either a single bundle in a JSON file or a JSON lines file with multiple bundles") cmdutil.DisableAuthCheckFlag(verifyCmd.Flags().Lookup("bundle")) verifyCmd.Flags().BoolVarP(&opts.UseBundleFromRegistry, "bundle-from-oci", "", false, "When verifying an OCI image, fetch the attestation bundle from the OCI registry instead of from GitHub") cmdutil.StringEnumFlag(verifyCmd, &opts.DigestAlgorithm, "digest-alg", "d", "sha256", []string{"sha256", "sha512"}, "The algorithm used to compute a digest of the artifact") verifyCmd.Flags().StringVarP(&opts.Owner, "owner", "o", "", "GitHub organization to scope attestation lookup by") verifyCmd.Flags().StringVarP(&opts.Repo, "repo", "R", "", "Repository name in the format <owner>/<repo>") verifyCmd.MarkFlagsMutuallyExclusive("owner", "repo") verifyCmd.MarkFlagsOneRequired("owner", "repo") verifyCmd.Flags().BoolVarP(&opts.NoPublicGood, "no-public-good", "", false, "Do not verify attestations signed with Sigstore public good instance") verifyCmd.Flags().StringVarP(&opts.TrustedRoot, "custom-trusted-root", "", "", "Path to a trusted_root.jsonl file; likely for offline verification") verifyCmd.Flags().IntVarP(&opts.Limit, "limit", "L", api.DefaultLimit, "Maximum number of attestations to fetch") cmdutil.AddFormatFlags(verifyCmd, &opts.exporter) verifyCmd.Flags().StringVarP(&opts.Hostname, "hostname", "", "", "Configure host to use") // policy enforcement flags verifyCmd.Flags().StringVarP(&opts.PredicateType, "predicate-type", "", verification.SLSAPredicateV1, "Enforce that verified attestations' predicate type matches the provided value") verifyCmd.Flags().BoolVarP(&opts.DenySelfHostedRunner, "deny-self-hosted-runners", "", false, "Fail verification for attestations generated on self-hosted runners") verifyCmd.Flags().StringVarP(&opts.SAN, "cert-identity", "", "", "Enforce that the certificate's SubjectAlternativeName matches the provided value exactly") verifyCmd.Flags().StringVarP(&opts.SANRegex, "cert-identity-regex", "i", "", "Enforce that the certificate's SubjectAlternativeName matches the provided regex") verifyCmd.Flags().StringVarP(&opts.SignerRepo, "signer-repo", "", "", "Enforce that the workflow that signed the attestation's repository matches the provided value (<owner>/<repo>)") verifyCmd.Flags().StringVarP(&opts.SignerWorkflow, "signer-workflow", "", "", "Enforce that the workflow that signed the attestation matches the provided value ([host/]<owner>/<repo>/<path>/<to>/<workflow>)") verifyCmd.MarkFlagsMutuallyExclusive("cert-identity", "cert-identity-regex", "signer-repo", "signer-workflow") verifyCmd.Flags().StringVarP(&opts.OIDCIssuer, "cert-oidc-issuer", "", verification.GitHubOIDCIssuer, "Enforce that the issuer of the OIDC token matches the provided value") verifyCmd.Flags().StringVarP(&opts.SignerDigest, "signer-digest", "", "", "Enforce that the digest associated with the signer workflow matches the provided value") verifyCmd.Flags().StringVarP(&opts.SourceRef, "source-ref", "", "", "Enforce that the git ref associated with the source repository matches the provided value") verifyCmd.Flags().StringVarP(&opts.SourceDigest, "source-digest", "", "", "Enforce that the digest associated with the source repository matches the provided value") return verifyCmd } func runVerify(opts *Options) error { ec, err := newEnforcementCriteria(opts) if err != nil { opts.Logger.Println(opts.Logger.ColorScheme.Red("✗ Failed to build verification policy")) return err } if err := ec.Valid(); err != nil { opts.Logger.Println(opts.Logger.ColorScheme.Red("✗ Invalid verification policy")) return err } artifact, err := artifact.NewDigestedArtifact(opts.OCIClient, opts.ArtifactPath, opts.DigestAlgorithm) if err != nil { opts.Logger.Printf(opts.Logger.ColorScheme.Red("✗ Loading digest for %s failed\n"), opts.ArtifactPath) return err } opts.Logger.Printf("Loaded digest %s for %s\n", artifact.DigestWithAlg(), artifact.URL) attestations, logMsg, err := getAttestations(opts, *artifact) if err != nil { if ok := errors.Is(err, api.ErrNoAttestationsFound); ok { opts.Logger.Printf(opts.Logger.ColorScheme.Red("✗ No attestations found for subject %s\n"), artifact.DigestWithAlg()) return err } // Print the message signifying failure fetching attestations opts.Logger.Println(opts.Logger.ColorScheme.Red(logMsg)) return err } // Print the message signifying success fetching attestations opts.Logger.Println(logMsg) // print information about the policy that will be enforced against attestations opts.Logger.Println("\nThe following policy criteria will be enforced:") opts.Logger.Println(ec.BuildPolicyInformation()) verified, errMsg, err := verifyAttestations(*artifact, attestations, opts.SigstoreVerifier, ec) if err != nil { opts.Logger.Println(opts.Logger.ColorScheme.Red(errMsg)) return err } opts.Logger.Println(opts.Logger.ColorScheme.Green("✓ Verification succeeded!\n")) // If an exporter is provided with the --json flag, write the results to the terminal in JSON format if opts.exporter != nil { // print the results to the terminal as an array of JSON objects if err = opts.exporter.Write(opts.Logger.IO, verified); err != nil { opts.Logger.Println(opts.Logger.ColorScheme.Red("✗ Failed to write JSON output")) return err } return nil } opts.Logger.Printf("The following %s matched the policy criteria\n\n", text.Pluralize(len(verified), "attestation")) // Otherwise print the results to the terminal for i, v := range verified { buildConfigURI := v.VerificationResult.Signature.Certificate.Extensions.BuildConfigURI sourceRepoAndOrg, sourceWorkflow, err := extractAttestationDetail(opts.Tenant, buildConfigURI) if err != nil { opts.Logger.Println(opts.Logger.ColorScheme.Red("failed to parse build config URI")) return err } builderSignerURI := v.VerificationResult.Signature.Certificate.Extensions.BuildSignerURI signerRepoAndOrg, signerWorkflow, err := extractAttestationDetail(opts.Tenant, builderSignerURI) if err != nil { opts.Logger.Println(opts.Logger.ColorScheme.Red("failed to parse build signer URI")) return err } opts.Logger.Printf("- Attestation #%d\n", i+1) rows := [][]string{ {" - Build repo", sourceRepoAndOrg}, {" - Build workflow", sourceWorkflow}, {" - Signer repo", signerRepoAndOrg}, {" - Signer workflow", signerWorkflow}, } //nolint:errcheck opts.Logger.PrintBulletPoints(rows) } // All attestations passed verification and policy evaluation return nil } func extractAttestationDetail(tenant, builderSignerURI string) (string, string, error) { // If given a build signer URI like // https://github.com/foo/bar/.github/workflows/release.yml@refs/heads/main // We want to extract: // * foo/bar // * .github/workflows/release.yml@refs/heads/main var orgAndRepoRegexp *regexp.Regexp var workflowRegexp *regexp.Regexp if tenant == "" { orgAndRepoRegexp = regexp.MustCompile(`https://github\.com/([^/]+/[^/]+)/`) workflowRegexp = regexp.MustCompile(`https://github\.com/[^/]+/[^/]+/(.+)`) } else { var tr = regexp.QuoteMeta(tenant) orgAndRepoRegexp = regexp.MustCompile(fmt.Sprintf( `https://%s\.ghe\.com/([^/]+/[^/]+)/`, tr)) workflowRegexp = regexp.MustCompile(fmt.Sprintf( `https://%s\.ghe\.com/[^/]+/[^/]+/(.+)`, tr)) } match := orgAndRepoRegexp.FindStringSubmatch(builderSignerURI) if len(match) < 2 { return "", "", fmt.Errorf("no match found for org and repo: %s", builderSignerURI) } orgAndRepo := match[1] match = workflowRegexp.FindStringSubmatch(builderSignerURI) if len(match) < 2 { return "", "", fmt.Errorf("no match found for workflow: %s", builderSignerURI) } workflow := match[1] return orgAndRepo, workflow, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/verify/policy_test.go
pkg/cmd/attestation/verify/policy_test.go
package verify import ( "testing" "github.com/cli/cli/v2/pkg/cmd/attestation/verification" "github.com/stretchr/testify/require" ) func TestNewEnforcementCriteria(t *testing.T) { artifactPath := "../test/data/sigstore-js-2.1.0.tgz" t.Run("sets SANRegex and SAN using SANRegex and SAN", func(t *testing.T) { opts := &Options{ ArtifactPath: artifactPath, Owner: "foo", Repo: "foo/bar", SAN: "https://github/foo/bar/.github/workflows/attest.yml", SANRegex: "(?i)^https://github/foo", SignerRepo: "wrong/value", SignerWorkflow: "wrong/value/.github/workflows/attest.yml", } c, err := newEnforcementCriteria(opts) require.NoError(t, err) require.Equal(t, "https://github/foo/bar/.github/workflows/attest.yml", c.SAN) require.Equal(t, "(?i)^https://github/foo", c.SANRegex) }) t.Run("sets SANRegex using SignerRepo", func(t *testing.T) { opts := &Options{ ArtifactPath: artifactPath, Owner: "wrong", Repo: "wrong/value", SignerRepo: "foo/bar", SignerWorkflow: "wrong/value/.github/workflows/attest.yml", } c, err := newEnforcementCriteria(opts) require.NoError(t, err) require.Equal(t, "(?i)^https://github.com/foo/bar/", c.SANRegex) require.Zero(t, c.SAN) }) t.Run("sets SANRegex using SignerRepo and Tenant", func(t *testing.T) { opts := &Options{ ArtifactPath: artifactPath, Owner: "wrong", Repo: "wrong/value", SignerRepo: "foo/bar", SignerWorkflow: "wrong/value/.github/workflows/attest.yml", Tenant: "baz", } c, err := newEnforcementCriteria(opts) require.NoError(t, err) require.Equal(t, "(?i)^https://baz.ghe.com/foo/bar/", c.SANRegex) require.Zero(t, c.SAN) }) t.Run("sets SANRegex using SignerWorkflow matching host regex", func(t *testing.T) { opts := &Options{ ArtifactPath: artifactPath, Owner: "wrong", Repo: "wrong/value", SignerWorkflow: "foo/bar/.github/workflows/attest.yml", Hostname: "github.com", } c, err := newEnforcementCriteria(opts) require.NoError(t, err) require.Equal(t, "^https://github.com/foo/bar/.github/workflows/attest.yml", c.SANRegex) require.Zero(t, c.SAN) }) t.Run("sets SANRegex using opts.Repo", func(t *testing.T) { opts := &Options{ ArtifactPath: artifactPath, Owner: "wrong", Repo: "foo/bar", } c, err := newEnforcementCriteria(opts) require.NoError(t, err) require.Equal(t, "(?i)^https://github.com/foo/bar/", c.SANRegex) }) t.Run("sets SANRegex using opts.Owner", func(t *testing.T) { opts := &Options{ ArtifactPath: artifactPath, Owner: "foo", } c, err := newEnforcementCriteria(opts) require.NoError(t, err) require.Equal(t, "(?i)^https://github.com/foo/", c.SANRegex) }) t.Run("sets Extensions.RunnerEnvironment to GitHubRunner value if opts.DenySelfHostedRunner is true", func(t *testing.T) { opts := &Options{ ArtifactPath: artifactPath, Owner: "foo", Repo: "foo/bar", DenySelfHostedRunner: true, } c, err := newEnforcementCriteria(opts) require.NoError(t, err) require.Equal(t, verification.GitHubRunner, c.Certificate.RunnerEnvironment) }) t.Run("sets Extensions.RunnerEnvironment to * value if opts.DenySelfHostedRunner is false", func(t *testing.T) { opts := &Options{ ArtifactPath: artifactPath, Owner: "foo", Repo: "foo/bar", DenySelfHostedRunner: false, } c, err := newEnforcementCriteria(opts) require.NoError(t, err) require.Zero(t, c.Certificate.RunnerEnvironment) }) t.Run("sets Extensions.SourceRepositoryURI using opts.Repo and opts.Tenant", func(t *testing.T) { opts := &Options{ ArtifactPath: artifactPath, Owner: "foo", Repo: "foo/bar", Tenant: "baz", } c, err := newEnforcementCriteria(opts) require.NoError(t, err) require.Equal(t, "https://baz.ghe.com/foo/bar", c.Certificate.SourceRepositoryURI) }) t.Run("sets Extensions.SourceRepositoryURI using opts.Repo", func(t *testing.T) { opts := &Options{ ArtifactPath: artifactPath, Owner: "foo", Repo: "foo/bar", } c, err := newEnforcementCriteria(opts) require.NoError(t, err) require.Equal(t, "https://github.com/foo/bar", c.Certificate.SourceRepositoryURI) }) t.Run("sets SANRegex and SAN using SANRegex and SAN, sets Extensions.SourceRepositoryURI using opts.Repo", func(t *testing.T) { opts := &Options{ ArtifactPath: artifactPath, Owner: "baz", Repo: "baz/xyz", SAN: "https://github/foo/bar/.github/workflows/attest.yml", SANRegex: "(?i)^https://github/foo", } c, err := newEnforcementCriteria(opts) require.NoError(t, err) require.Equal(t, "https://github/foo/bar/.github/workflows/attest.yml", c.SAN) require.Equal(t, "(?i)^https://github/foo", c.SANRegex) require.Equal(t, "https://github.com/baz/xyz", c.Certificate.SourceRepositoryURI) }) t.Run("sets Extensions.SourceRepositoryOwnerURI using opts.Owner and opts.Tenant", func(t *testing.T) { opts := &Options{ ArtifactPath: artifactPath, Owner: "foo", Repo: "foo/bar", Tenant: "baz", } c, err := newEnforcementCriteria(opts) require.NoError(t, err) require.Equal(t, "https://baz.ghe.com/foo", c.Certificate.SourceRepositoryOwnerURI) }) t.Run("sets Extensions.SourceRepositoryOwnerURI using opts.Owner", func(t *testing.T) { opts := &Options{ ArtifactPath: artifactPath, Owner: "foo", Repo: "foo/bar", } c, err := newEnforcementCriteria(opts) require.NoError(t, err) require.Equal(t, "https://github.com/foo", c.Certificate.SourceRepositoryOwnerURI) }) t.Run("sets OIDCIssuer using opts.Tenant", func(t *testing.T) { opts := &Options{ ArtifactPath: artifactPath, Owner: "foo", Repo: "foo/bar", Tenant: "baz", OIDCIssuer: verification.GitHubOIDCIssuer, } c, err := newEnforcementCriteria(opts) require.NoError(t, err) require.Equal(t, "https://token.actions.baz.ghe.com", c.Certificate.Issuer) }) t.Run("sets OIDCIssuer using opts.OIDCIssuer", func(t *testing.T) { opts := &Options{ ArtifactPath: artifactPath, Owner: "foo", Repo: "foo/bar", OIDCIssuer: "https://foo.com", Tenant: "baz", } c, err := newEnforcementCriteria(opts) require.NoError(t, err) require.Equal(t, "https://foo.com", c.Certificate.Issuer) }) t.Run("sets Certificate.BuildSignerDigest using opts.SignerDigest", func(t *testing.T) { opts := &Options{ ArtifactPath: artifactPath, Owner: "wrong", Repo: "wrong/value", SignerDigest: "foo", Hostname: "github.com", } c, err := newEnforcementCriteria(opts) require.NoError(t, err) require.Equal(t, "foo", c.Certificate.BuildSignerDigest) }) t.Run("sets Certificate.SourceRepositoryDigest using opts.SourceDigest", func(t *testing.T) { opts := &Options{ ArtifactPath: artifactPath, Owner: "wrong", Repo: "wrong/value", SourceDigest: "foo", Hostname: "github.com", } c, err := newEnforcementCriteria(opts) require.NoError(t, err) require.Equal(t, "foo", c.Certificate.SourceRepositoryDigest) }) t.Run("sets Certificate.SourceRepositoryRef using opts.SourceRef", func(t *testing.T) { opts := &Options{ ArtifactPath: artifactPath, Owner: "wrong", Repo: "wrong/value", SourceRef: "refs/heads/main", Hostname: "github.com", } c, err := newEnforcementCriteria(opts) require.NoError(t, err) require.Equal(t, "refs/heads/main", c.Certificate.SourceRepositoryRef) }) } func TestValidateSignerWorkflow(t *testing.T) { type testcase struct { name string providedSignerWorkflow string expectedWorkflowRegex string host string expectErr bool errContains string } testcases := []testcase{ { name: "workflow with no host specified", providedSignerWorkflow: "github/artifact-attestations-workflows/.github/workflows/attest.yml", expectErr: true, errContains: "unknown signer workflow host", }, { name: "workflow with default host", providedSignerWorkflow: "github/artifact-attestations-workflows/.github/workflows/attest.yml", expectedWorkflowRegex: "^https://github.com/github/artifact-attestations-workflows/.github/workflows/attest.yml", host: "github.com", }, { name: "workflow with workflow URL included", providedSignerWorkflow: "github.com/github/artifact-attestations-workflows/.github/workflows/attest.yml", expectedWorkflowRegex: "^https://github.com/github/artifact-attestations-workflows/.github/workflows/attest.yml", host: "github.com", }, { name: "workflow with GH_HOST set", providedSignerWorkflow: "github/artifact-attestations-workflows/.github/workflows/attest.yml", expectedWorkflowRegex: "^https://myhost.github.com/github/artifact-attestations-workflows/.github/workflows/attest.yml", host: "myhost.github.com", }, { name: "workflow with authenticated host", providedSignerWorkflow: "github/artifact-attestations-workflows/.github/workflows/attest.yml", expectedWorkflowRegex: "^https://authedhost.github.com/github/artifact-attestations-workflows/.github/workflows/attest.yml", host: "authedhost.github.com", }, } for _, tc := range testcases { // All host resolution is done verify.go:RunE workflowRegex, err := validateSignerWorkflow(tc.host, tc.providedSignerWorkflow) require.Equal(t, tc.expectedWorkflowRegex, workflowRegex) if tc.expectErr { require.Error(t, err) require.ErrorContains(t, err, tc.errContains) } else { require.NoError(t, err) require.Equal(t, tc.expectedWorkflowRegex, workflowRegex) } } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/verify/attestation_test.go
pkg/cmd/attestation/verify/attestation_test.go
package verify import ( "testing" "github.com/cli/cli/v2/pkg/cmd/attestation/api" "github.com/cli/cli/v2/pkg/cmd/attestation/artifact" "github.com/cli/cli/v2/pkg/cmd/attestation/artifact/oci" "github.com/cli/cli/v2/pkg/cmd/attestation/verification" "github.com/stretchr/testify/require" ) func TestGetAttestations_OCIRegistry_PredicateTypeFiltering(t *testing.T) { artifact, err := artifact.NewDigestedArtifact(nil, "../test/data/gh_2.60.1_windows_arm64.zip", "sha256") require.NoError(t, err) o := &Options{ OCIClient: oci.MockClient{}, PredicateType: verification.SLSAPredicateV1, Repo: "cli/cli", UseBundleFromRegistry: true, } attestations, msg, err := getAttestations(o, *artifact) require.NoError(t, err) require.Contains(t, msg, "Loaded 2 attestations from OCI registry") require.Len(t, attestations, 2) o.PredicateType = "custom predicate type" attestations, msg, err = getAttestations(o, *artifact) require.Error(t, err) require.Contains(t, msg, "no attestations found with predicate type") require.Nil(t, attestations) } func TestGetAttestations_LocalBundle_PredicateTypeFiltering(t *testing.T) { artifact, err := artifact.NewDigestedArtifact(nil, "../test/data/gh_2.60.1_windows_arm64.zip", "sha256") require.NoError(t, err) o := &Options{ BundlePath: "../test/data/sigstore-js-2.1.0-bundle.json", PredicateType: verification.SLSAPredicateV1, Repo: "sigstore/sigstore-js", } attestations, _, err := getAttestations(o, *artifact) require.NoError(t, err) require.Len(t, attestations, 1) o.PredicateType = "custom predicate type" attestations, _, err = getAttestations(o, *artifact) require.Error(t, err) require.Nil(t, attestations) } func TestGetAttestations_GhAPI_NoAttestationsFound(t *testing.T) { artifact, err := artifact.NewDigestedArtifact(nil, "../test/data/gh_2.60.1_windows_arm64.zip", "sha256") require.NoError(t, err) o := &Options{ APIClient: api.NewTestClient(), PredicateType: verification.SLSAPredicateV1, Repo: "sigstore/sigstore-js", } attestations, _, err := getAttestations(o, *artifact) require.NoError(t, err) require.Len(t, attestations, 2) o.PredicateType = "custom predicate type" attestations, _, err = getAttestations(o, *artifact) require.Error(t, err) require.Nil(t, attestations) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/verify/verify_test.go
pkg/cmd/attestation/verify/verify_test.go
package verify import ( "bytes" "encoding/json" "fmt" "net/http" "strings" "testing" "github.com/cli/cli/v2/pkg/cmd/attestation/api" "github.com/cli/cli/v2/pkg/cmd/attestation/artifact/oci" "github.com/cli/cli/v2/pkg/cmd/attestation/io" "github.com/cli/cli/v2/pkg/cmd/attestation/test" "github.com/cli/cli/v2/pkg/cmd/attestation/verification" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/spf13/cobra" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) const ( SigstoreSanValue = "https://github.com/sigstore/sigstore-js/.github/workflows/release.yml@refs/heads/main" SigstoreSanRegex = "^https://github.com/sigstore/sigstore-js/" ) var ( artifactPath = test.NormalizeRelativePath("../test/data/sigstore-js-2.1.0.tgz") bundlePath = test.NormalizeRelativePath("../test/data/sigstore-js-2.1.0-bundle.json") ) func TestNewVerifyCmd(t *testing.T) { testIO, _, _, _ := iostreams.Test() var testReg httpmock.Registry var metaResp = api.MetaResponse{ Domains: api.Domain{ ArtifactAttestations: api.ArtifactAttestations{ TrustDomain: "foo", }, }, } testReg.Register(httpmock.REST(http.MethodGet, "meta"), httpmock.StatusJSONResponse(200, &metaResp)) f := &cmdutil.Factory{ IOStreams: testIO, HttpClient: func() (*http.Client, error) { reg := &testReg client := &http.Client{} httpmock.ReplaceTripper(client, reg) return client, nil }, } testcases := []struct { name string cli string wants Options wantsErr bool wantsExporter bool }{ { name: "Invalid digest-alg flag", cli: fmt.Sprintf("%s --bundle %s --digest-alg sha384 --owner sigstore", artifactPath, bundlePath), wants: Options{ ArtifactPath: test.NormalizeRelativePath("../test/data/sigstore-js-2.1.0.tgz"), BundlePath: test.NormalizeRelativePath("../test/data/sigstore-js-2.1.0-bundle.json"), DigestAlgorithm: "sha384", Hostname: "github.com", Limit: 30, OIDCIssuer: verification.GitHubOIDCIssuer, Owner: "sigstore", PredicateType: verification.SLSAPredicateV1, SigstoreVerifier: verification.NewMockSigstoreVerifier(t), }, wantsErr: true, }, { name: "Use default digest-alg value", cli: fmt.Sprintf("%s --bundle %s --owner sigstore", artifactPath, bundlePath), wants: Options{ ArtifactPath: test.NormalizeRelativePath("../test/data/sigstore-js-2.1.0.tgz"), BundlePath: test.NormalizeRelativePath("../test/data/sigstore-js-2.1.0-bundle.json"), DigestAlgorithm: "sha256", Hostname: "github.com", Limit: 30, OIDCIssuer: verification.GitHubOIDCIssuer, Owner: "sigstore", PredicateType: verification.SLSAPredicateV1, SigstoreVerifier: verification.NewMockSigstoreVerifier(t), }, wantsErr: false, }, { name: "Custom host", cli: fmt.Sprintf("%s --bundle %s --owner sigstore --hostname foo.ghe.com", artifactPath, bundlePath), wants: Options{ ArtifactPath: test.NormalizeRelativePath("../test/data/sigstore-js-2.1.0.tgz"), BundlePath: test.NormalizeRelativePath("../test/data/sigstore-js-2.1.0-bundle.json"), DigestAlgorithm: "sha256", Hostname: "foo.ghe.com", Limit: 30, OIDCIssuer: verification.GitHubOIDCIssuer, Owner: "sigstore", PredicateType: verification.SLSAPredicateV1, SigstoreVerifier: verification.NewMockSigstoreVerifier(t), }, wantsErr: false, }, { name: "Invalid custom host", cli: fmt.Sprintf("%s --bundle %s --owner sigstore --hostname foo.bar.com", artifactPath, bundlePath), wants: Options{ ArtifactPath: test.NormalizeRelativePath("../test/data/sigstore-js-2.1.0.tgz"), BundlePath: test.NormalizeRelativePath("../test/data/sigstore-js-2.1.0-bundle.json"), DigestAlgorithm: "sha256", Hostname: "foo.ghe.com", Limit: 30, OIDCIssuer: verification.GitHubOIDCIssuer, Owner: "sigstore", PredicateType: verification.SLSAPredicateV1, SigstoreVerifier: verification.NewMockSigstoreVerifier(t), }, wantsErr: true, }, { name: "Use custom digest-alg value", cli: fmt.Sprintf("%s --bundle %s --owner sigstore --digest-alg sha512", artifactPath, bundlePath), wants: Options{ ArtifactPath: test.NormalizeRelativePath("../test/data/sigstore-js-2.1.0.tgz"), BundlePath: test.NormalizeRelativePath("../test/data/sigstore-js-2.1.0-bundle.json"), DigestAlgorithm: "sha512", Hostname: "github.com", Limit: 30, OIDCIssuer: verification.GitHubOIDCIssuer, Owner: "sigstore", PredicateType: verification.SLSAPredicateV1, SigstoreVerifier: verification.NewMockSigstoreVerifier(t), }, wantsErr: false, }, { name: "Missing owner and repo flags", cli: artifactPath, wants: Options{ ArtifactPath: test.NormalizeRelativePath("../test/data/sigstore-js-2.1.0.tgz"), DigestAlgorithm: "sha256", Hostname: "github.com", Limit: 30, OIDCIssuer: verification.GitHubOIDCIssuer, Owner: "sigstore", PredicateType: verification.SLSAPredicateV1, SANRegex: "(?i)^https://github.com/sigstore/", SigstoreVerifier: verification.NewMockSigstoreVerifier(t), }, wantsErr: true, }, { name: "Has both owner and repo flags", cli: fmt.Sprintf("%s --owner sigstore --repo sigstore/sigstore-js", artifactPath), wants: Options{ ArtifactPath: artifactPath, DigestAlgorithm: "sha256", Hostname: "github.com", Limit: 30, OIDCIssuer: verification.GitHubOIDCIssuer, Owner: "sigstore", PredicateType: verification.SLSAPredicateV1, Repo: "sigstore/sigstore-js", SigstoreVerifier: verification.NewMockSigstoreVerifier(t), }, wantsErr: true, }, { name: "Uses default limit flag", cli: fmt.Sprintf("%s --owner sigstore", artifactPath), wants: Options{ ArtifactPath: artifactPath, DigestAlgorithm: "sha256", Hostname: "github.com", Limit: 30, OIDCIssuer: verification.GitHubOIDCIssuer, Owner: "sigstore", PredicateType: verification.SLSAPredicateV1, SigstoreVerifier: verification.NewMockSigstoreVerifier(t), }, wantsErr: false, }, { name: "Uses custom limit flag", cli: fmt.Sprintf("%s --owner sigstore --limit 101", artifactPath), wants: Options{ ArtifactPath: artifactPath, DigestAlgorithm: "sha256", Hostname: "github.com", Limit: 101, OIDCIssuer: verification.GitHubOIDCIssuer, Owner: "sigstore", PredicateType: verification.SLSAPredicateV1, SigstoreVerifier: verification.NewMockSigstoreVerifier(t), }, wantsErr: false, }, { name: "Uses invalid limit flag", cli: fmt.Sprintf("%s --owner sigstore --limit 0", artifactPath), wants: Options{ ArtifactPath: artifactPath, DigestAlgorithm: "sha256", Hostname: "github.com", Limit: 0, OIDCIssuer: verification.GitHubOIDCIssuer, Owner: "sigstore", PredicateType: verification.SLSAPredicateV1, SANRegex: "(?i)^https://github.com/sigstore/", SigstoreVerifier: verification.NewMockSigstoreVerifier(t), }, wantsErr: true, }, { name: "Has both cert-identity and cert-identity-regex flags", cli: fmt.Sprintf("%s --owner sigstore --cert-identity https://github.com/sigstore/ --cert-identity-regex ^https://github.com/sigstore/", artifactPath), wants: Options{ ArtifactPath: artifactPath, DigestAlgorithm: "sha256", Hostname: "github.com", Limit: 30, OIDCIssuer: verification.GitHubOIDCIssuer, Owner: "sigstore", PredicateType: verification.SLSAPredicateV1, SAN: "https://github.com/sigstore/", SANRegex: "(?i)^https://github.com/sigstore/", SigstoreVerifier: verification.NewMockSigstoreVerifier(t), }, wantsErr: true, }, { name: "Prints output in JSON format", cli: fmt.Sprintf("%s --bundle %s --owner sigstore --format json", artifactPath, bundlePath), wants: Options{ ArtifactPath: artifactPath, BundlePath: bundlePath, DigestAlgorithm: "sha256", Hostname: "github.com", Limit: 30, OIDCIssuer: verification.GitHubOIDCIssuer, Owner: "sigstore", PredicateType: verification.SLSAPredicateV1, SigstoreVerifier: verification.NewMockSigstoreVerifier(t), }, wantsExporter: true, }, { name: "Use specified predicate type", cli: fmt.Sprintf("%s --bundle %s --owner sigstore --predicate-type https://spdx.dev/Document/v2.3 --format json", artifactPath, bundlePath), wants: Options{ ArtifactPath: artifactPath, BundlePath: bundlePath, DigestAlgorithm: "sha256", Hostname: "github.com", Limit: 30, OIDCIssuer: verification.GitHubOIDCIssuer, Owner: "sigstore", PredicateType: "https://spdx.dev/Document/v2.3", SigstoreVerifier: verification.NewMockSigstoreVerifier(t), }, wantsExporter: true, }, } for _, tc := range testcases { t.Run(tc.name, func(t *testing.T) { var opts *Options cmd := NewVerifyCmd(f, func(o *Options) error { opts = o return nil }) argv := strings.Split(tc.cli, " ") cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err := cmd.ExecuteC() if tc.wantsErr { assert.Error(t, err) return } assert.NoError(t, err) assert.Equal(t, tc.wants.ArtifactPath, opts.ArtifactPath) assert.Equal(t, tc.wants.BundlePath, opts.BundlePath) assert.Equal(t, tc.wants.DenySelfHostedRunner, opts.DenySelfHostedRunner) assert.Equal(t, tc.wants.DigestAlgorithm, opts.DigestAlgorithm) assert.Equal(t, tc.wants.Hostname, opts.Hostname) assert.Equal(t, tc.wants.Limit, opts.Limit) assert.Equal(t, tc.wants.NoPublicGood, opts.NoPublicGood) assert.Equal(t, tc.wants.OIDCIssuer, opts.OIDCIssuer) assert.Equal(t, tc.wants.Owner, opts.Owner) assert.Equal(t, tc.wants.PredicateType, opts.PredicateType) assert.Equal(t, tc.wants.Repo, opts.Repo) assert.Equal(t, tc.wants.SAN, opts.SAN) assert.Equal(t, tc.wants.SANRegex, opts.SANRegex) assert.Equal(t, tc.wants.TrustedRoot, opts.TrustedRoot) assert.NotNil(t, opts.APIClient) assert.NotNil(t, opts.Logger) assert.NotNil(t, opts.OCIClient) assert.Equal(t, tc.wantsExporter, opts.exporter != nil) }) } } func TestVerifyCmdAuthChecks(t *testing.T) { f := &cmdutil.Factory{} t.Run("by default auth check is required", func(t *testing.T) { cmd := NewVerifyCmd(f, func(o *Options) error { return nil }) // IsAuthCheckEnabled assumes commands under test are subcommands parent := &cobra.Command{Use: "root"} parent.AddCommand(cmd) require.NoError(t, cmd.ParseFlags([]string{})) require.True(t, cmdutil.IsAuthCheckEnabled(cmd), "expected auth check to be required") }) t.Run("when --bundle flag is provided, auth check is not required", func(t *testing.T) { cmd := NewVerifyCmd(f, func(o *Options) error { return nil }) // IsAuthCheckEnabled assumes commands under test are subcommands parent := &cobra.Command{Use: "root"} parent.AddCommand(cmd) require.NoError(t, cmd.ParseFlags([]string{"--bundle", "not-important"})) require.False(t, cmdutil.IsAuthCheckEnabled(cmd), "expected auth check not to be required due to --bundle flag") }) } func TestJSONOutput(t *testing.T) { testIO, _, out, _ := iostreams.Test() opts := Options{ ArtifactPath: artifactPath, BundlePath: bundlePath, DigestAlgorithm: "sha512", APIClient: api.NewTestClient(), Logger: io.NewHandler(testIO), OCIClient: oci.MockClient{}, OIDCIssuer: verification.GitHubOIDCIssuer, Owner: "sigstore", PredicateType: verification.SLSAPredicateV1, SANRegex: "^https://github.com/sigstore/", SigstoreVerifier: verification.NewMockSigstoreVerifier(t), exporter: cmdutil.NewJSONExporter(), } require.NoError(t, runVerify(&opts)) var target []*verification.AttestationProcessingResult err := json.Unmarshal(out.Bytes(), &target) require.NoError(t, err) } func TestRunVerify(t *testing.T) { logger := io.NewTestHandler() publicGoodOpts := Options{ ArtifactPath: artifactPath, BundlePath: bundlePath, DigestAlgorithm: "sha512", APIClient: api.NewTestClient(), Logger: logger, OCIClient: oci.MockClient{}, OIDCIssuer: verification.GitHubOIDCIssuer, Owner: "sigstore", PredicateType: verification.SLSAPredicateV1, SANRegex: "^https://github.com/sigstore/", SigstoreVerifier: verification.NewMockSigstoreVerifier(t), } t.Run("with valid artifact and bundle", func(t *testing.T) { require.NoError(t, runVerify(&publicGoodOpts)) }) t.Run("with failing OCI artifact fetch", func(t *testing.T) { opts := publicGoodOpts opts.ArtifactPath = "oci://ghcr.io/github/test" opts.OCIClient = oci.ReferenceFailClient{} err := runVerify(&opts) require.Error(t, err) require.ErrorContains(t, err, "failed to parse reference") }) t.Run("with missing artifact path", func(t *testing.T) { opts := publicGoodOpts opts.ArtifactPath = "../test/data/non-existent-artifact.zip" require.Error(t, runVerify(&opts)) }) t.Run("with missing bundle path", func(t *testing.T) { opts := publicGoodOpts opts.BundlePath = "../test/data/non-existent-sigstoreBundle.json" require.Error(t, runVerify(&opts)) }) t.Run("with owner", func(t *testing.T) { opts := publicGoodOpts opts.BundlePath = "" opts.Owner = "sigstore" require.NoError(t, runVerify(&opts)) }) t.Run("with owner which not matches SourceRepositoryOwnerURI", func(t *testing.T) { opts := publicGoodOpts opts.BundlePath = "" opts.Owner = "owner" err := runVerify(&opts) require.ErrorContains(t, err, "expected SourceRepositoryOwnerURI to be https://github.com/owner, got https://github.com/sigstore") }) t.Run("with repo", func(t *testing.T) { opts := publicGoodOpts opts.BundlePath = "" opts.Repo = "sigstore/sigstore-js" require.Nil(t, runVerify(&opts)) }) // Test with bad tenancy t.Run("with bad tenancy", func(t *testing.T) { opts := publicGoodOpts opts.BundlePath = "" opts.Repo = "sigstore/sigstore-js" opts.Tenant = "foo" err := runVerify(&opts) require.ErrorContains(t, err, "expected SourceRepositoryOwnerURI to be https://foo.ghe.com/sigstore, got https://github.com/sigstore") }) t.Run("with repo which not matches SourceRepositoryURI", func(t *testing.T) { opts := publicGoodOpts opts.BundlePath = "" opts.Repo = "sigstore/wrong" err := runVerify(&opts) require.ErrorContains(t, err, "expected SourceRepositoryURI to be https://github.com/sigstore/wrong, got https://github.com/sigstore/sigstore-js") }) t.Run("with invalid repo", func(t *testing.T) { opts := publicGoodOpts opts.BundlePath = "" opts.Repo = "wrong/example" opts.APIClient = api.NewFailTestClient() err := runVerify(&opts) require.Error(t, err) require.ErrorContains(t, err, "failed to fetch attestations from wrong/example") }) t.Run("with invalid owner", func(t *testing.T) { opts := publicGoodOpts opts.BundlePath = "" opts.APIClient = api.NewFailTestClient() opts.Owner = "wrong-owner" err := runVerify(&opts) require.Error(t, err) require.ErrorContains(t, err, "failed to fetch attestations from wrong-owner") }) t.Run("with missing API client", func(t *testing.T) { customOpts := publicGoodOpts customOpts.APIClient = nil customOpts.BundlePath = "" require.Error(t, runVerify(&customOpts)) }) t.Run("with valid OCI artifact", func(t *testing.T) { customOpts := publicGoodOpts customOpts.ArtifactPath = "oci://ghcr.io/github/test" customOpts.BundlePath = "" require.Nil(t, runVerify(&customOpts)) }) t.Run("with valid OCI artifact with UseBundleFromRegistry flag", func(t *testing.T) { customOpts := publicGoodOpts customOpts.ArtifactPath = "oci://ghcr.io/github/test" customOpts.BundlePath = "" customOpts.UseBundleFromRegistry = true require.Nil(t, runVerify(&customOpts)) }) t.Run("with valid OCI artifact with UseBundleFromRegistry flag and unknown predicate type", func(t *testing.T) { customOpts := publicGoodOpts customOpts.ArtifactPath = "oci://ghcr.io/github/test" customOpts.BundlePath = "" customOpts.UseBundleFromRegistry = true customOpts.PredicateType = "https://predicate.type" err := runVerify(&customOpts) require.Error(t, err) require.ErrorContains(t, err, "no attestations found with predicate type") }) t.Run("with valid OCI artifact with UseBundleFromRegistry flag but no bundle return from registry", func(t *testing.T) { customOpts := publicGoodOpts customOpts.ArtifactPath = "oci://ghcr.io/github/test" customOpts.BundlePath = "" customOpts.UseBundleFromRegistry = true customOpts.OCIClient = oci.NoAttestationsClient{} require.ErrorContains(t, runVerify(&customOpts), "no attestations found in the OCI registry. Retry the command without the --bundle-from-oci flag to check GitHub for the attestation") }) t.Run("with valid OCI artifact with UseBundleFromRegistry flag but fail on fetching bundle from registry", func(t *testing.T) { customOpts := publicGoodOpts customOpts.ArtifactPath = "oci://ghcr.io/github/test" customOpts.BundlePath = "" customOpts.UseBundleFromRegistry = true customOpts.OCIClient = oci.NoAttestationsClient{} require.ErrorContains(t, runVerify(&customOpts), "no attestations found in the OCI registry. Retry the command without the --bundle-from-oci flag to check GitHub for the attestation") }) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/verify/verify_integration_test.go
pkg/cmd/attestation/verify/verify_integration_test.go
//go:build integration package verify import ( "net/http" "testing" "github.com/cli/cli/v2/pkg/cmd/attestation/api" "github.com/cli/cli/v2/pkg/cmd/attestation/artifact/oci" "github.com/cli/cli/v2/pkg/cmd/attestation/io" "github.com/cli/cli/v2/pkg/cmd/attestation/test" "github.com/cli/cli/v2/pkg/cmd/attestation/verification" "github.com/cli/cli/v2/pkg/cmd/factory" o "github.com/cli/cli/v2/pkg/option" "github.com/cli/go-gh/v2/pkg/auth" "github.com/stretchr/testify/require" ) func TestVerifyIntegration(t *testing.T) { logger := io.NewTestHandler() sigstoreConfig := verification.SigstoreConfig{ HttpClient: http.DefaultClient, Logger: logger, TUFMetadataDir: o.Some(t.TempDir()), } cmdFactory := factory.New("test") hc, err := cmdFactory.HttpClient() if err != nil { t.Fatal(err) } host, _ := auth.DefaultHost() sigstoreVerifier, err := verification.NewLiveSigstoreVerifier(sigstoreConfig) require.NoError(t, err) publicGoodOpts := Options{ APIClient: api.NewLiveClient(hc, host, logger), ArtifactPath: artifactPath, BundlePath: bundlePath, DigestAlgorithm: "sha512", Logger: logger, OCIClient: oci.NewLiveClient(), OIDCIssuer: verification.GitHubOIDCIssuer, Owner: "sigstore", PredicateType: verification.SLSAPredicateV1, SANRegex: "^https://github.com/sigstore/", SigstoreVerifier: sigstoreVerifier, } t.Run("with valid owner", func(t *testing.T) { err := runVerify(&publicGoodOpts) require.NoError(t, err) }) t.Run("with valid repo", func(t *testing.T) { opts := publicGoodOpts opts.Repo = "sigstore/sigstore-js" err := runVerify(&opts) require.NoError(t, err) }) t.Run("with valid owner and invalid repo", func(t *testing.T) { opts := publicGoodOpts opts.Repo = "sigstore/fakerepo" err := runVerify(&opts) require.Error(t, err) require.ErrorContains(t, err, "expected SourceRepositoryURI to be https://github.com/sigstore/fakerepo, got https://github.com/sigstore/sigstore-js") }) t.Run("with invalid owner", func(t *testing.T) { opts := publicGoodOpts opts.Owner = "fakeowner" err := runVerify(&opts) require.Error(t, err) require.ErrorContains(t, err, "expected SourceRepositoryOwnerURI to be https://github.com/fakeowner, got https://github.com/sigstore") }) t.Run("with no matching OIDC issuer", func(t *testing.T) { opts := publicGoodOpts opts.OIDCIssuer = "some-other-issuer" err := runVerify(&opts) require.Error(t, err) require.ErrorContains(t, err, "expected Issuer to be some-other-issuer, got https://token.actions.githubusercontent.com") }) t.Run("with invalid SAN", func(t *testing.T) { opts := publicGoodOpts opts.SAN = "fake san" err := runVerify(&opts) require.Error(t, err) require.ErrorContains(t, err, "verifying with issuer \"sigstore.dev\"") }) t.Run("with invalid SAN regex", func(t *testing.T) { opts := publicGoodOpts opts.SANRegex = "^https://github.com/sigstore/not-real/" err := runVerify(&opts) require.Error(t, err) require.ErrorContains(t, err, "verifying with issuer \"sigstore.dev\"") }) t.Run("with bundle from OCI registry", func(t *testing.T) { sigstoreVerifier, err := verification.NewLiveSigstoreVerifier(sigstoreConfig) require.NoError(t, err) opts := Options{ APIClient: api.NewLiveClient(hc, host, logger), ArtifactPath: "oci://ghcr.io/github/artifact-attestations-helm-charts/policy-controller:v0.10.0-github9", UseBundleFromRegistry: true, DigestAlgorithm: "sha256", Logger: logger, OCIClient: oci.NewLiveClient(), OIDCIssuer: verification.GitHubOIDCIssuer, Owner: "github", PredicateType: verification.SLSAPredicateV1, SANRegex: "^https://github.com/github/", SigstoreVerifier: sigstoreVerifier, } err = runVerify(&opts) require.NoError(t, err) }) } func TestVerifyIntegrationCustomIssuer(t *testing.T) { artifactPath := test.NormalizeRelativePath("../test/data/custom-issuer-artifact") bundlePath := test.NormalizeRelativePath("../test/data/custom-issuer.sigstore.json") logger := io.NewTestHandler() sigstoreConfig := verification.SigstoreConfig{ HttpClient: http.DefaultClient, Logger: logger, TUFMetadataDir: o.Some(t.TempDir()), } cmdFactory := factory.New("test") hc, err := cmdFactory.HttpClient() if err != nil { t.Fatal(err) } host, _ := auth.DefaultHost() sigstoreVerifier, err := verification.NewLiveSigstoreVerifier(sigstoreConfig) require.NoError(t, err) baseOpts := Options{ APIClient: api.NewLiveClient(hc, host, logger), ArtifactPath: artifactPath, BundlePath: bundlePath, DigestAlgorithm: "sha256", Logger: logger, OCIClient: oci.NewLiveClient(), OIDCIssuer: "https://token.actions.githubusercontent.com/hammer-time", PredicateType: verification.SLSAPredicateV1, SigstoreVerifier: sigstoreVerifier, } t.Run("with owner and valid workflow SAN", func(t *testing.T) { opts := baseOpts opts.Owner = "too-legit" opts.SAN = "https://github.com/too-legit/attest/.github/workflows/integration.yml@refs/heads/main" err := runVerify(&opts) require.NoError(t, err) }) t.Run("with owner and valid workflow SAN regex", func(t *testing.T) { opts := baseOpts opts.Owner = "too-legit" opts.SANRegex = "^https://github.com/too-legit/attest" err := runVerify(&opts) require.NoError(t, err) }) t.Run("with repo and valid workflow SAN", func(t *testing.T) { opts := baseOpts opts.Owner = "too-legit" opts.Repo = "too-legit/attest" opts.SAN = "https://github.com/too-legit/attest/.github/workflows/integration.yml@refs/heads/main" err := runVerify(&opts) require.NoError(t, err) }) t.Run("with repo and valid workflow SAN regex", func(t *testing.T) { opts := baseOpts opts.Owner = "too-legit" opts.Repo = "too-legit/attest" opts.SANRegex = "^https://github.com/too-legit/attest" err := runVerify(&opts) require.NoError(t, err) }) } func TestVerifyIntegrationReusableWorkflow(t *testing.T) { artifactPath := test.NormalizeRelativePath("../test/data/reusable-workflow-artifact") bundlePath := test.NormalizeRelativePath("../test/data/reusable-workflow-attestation.sigstore.json") logger := io.NewTestHandler() sigstoreConfig := verification.SigstoreConfig{ HttpClient: http.DefaultClient, Logger: logger, TUFMetadataDir: o.Some(t.TempDir()), } cmdFactory := factory.New("test") hc, err := cmdFactory.HttpClient() if err != nil { t.Fatal(err) } host, _ := auth.DefaultHost() sigstoreVerifier, err := verification.NewLiveSigstoreVerifier(sigstoreConfig) require.NoError(t, err) baseOpts := Options{ APIClient: api.NewLiveClient(hc, host, logger), ArtifactPath: artifactPath, BundlePath: bundlePath, DigestAlgorithm: "sha256", Logger: logger, OCIClient: oci.NewLiveClient(), OIDCIssuer: verification.GitHubOIDCIssuer, PredicateType: verification.SLSAPredicateV1, SigstoreVerifier: sigstoreVerifier, } t.Run("with owner and valid reusable workflow SAN", func(t *testing.T) { opts := baseOpts opts.Owner = "malancas" opts.SAN = "https://github.com/github/artifact-attestations-workflows/.github/workflows/attest.yml@09b495c3f12c7881b3cc17209a327792065c1a1d" err := runVerify(&opts) require.NoError(t, err) }) t.Run("with owner and valid reusable workflow SAN regex", func(t *testing.T) { opts := baseOpts opts.Owner = "malancas" opts.SANRegex = "^https://github.com/github/artifact-attestations-workflows/" err := runVerify(&opts) require.NoError(t, err) }) t.Run("with owner and valid reusable signer repo", func(t *testing.T) { opts := baseOpts opts.Owner = "malancas" opts.SignerRepo = "github/artifact-attestations-workflows" err := runVerify(&opts) require.NoError(t, err) }) t.Run("with repo and valid reusable workflow SAN", func(t *testing.T) { opts := baseOpts opts.Owner = "malancas" opts.Repo = "malancas/attest-demo" opts.SAN = "https://github.com/github/artifact-attestations-workflows/.github/workflows/attest.yml@09b495c3f12c7881b3cc17209a327792065c1a1d" err := runVerify(&opts) require.NoError(t, err) }) t.Run("with repo and valid reusable workflow SAN regex", func(t *testing.T) { opts := baseOpts opts.Owner = "malancas" opts.Repo = "malancas/attest-demo" opts.SANRegex = "^https://github.com/github/artifact-attestations-workflows/" err := runVerify(&opts) require.NoError(t, err) }) t.Run("with repo and valid reusable signer repo", func(t *testing.T) { opts := baseOpts opts.Owner = "malancas" opts.Repo = "malancas/attest-demo" opts.SignerRepo = "github/artifact-attestations-workflows" err := runVerify(&opts) require.NoError(t, err) }) } func TestVerifyIntegrationReusableWorkflowSignerWorkflow(t *testing.T) { artifactPath := test.NormalizeRelativePath("../test/data/reusable-workflow-artifact") bundlePath := test.NormalizeRelativePath("../test/data/reusable-workflow-attestation.sigstore.json") logger := io.NewTestHandler() sigstoreConfig := verification.SigstoreConfig{ HttpClient: http.DefaultClient, Logger: logger, TUFMetadataDir: o.Some(t.TempDir()), } cmdFactory := factory.New("test") hc, err := cmdFactory.HttpClient() if err != nil { t.Fatal(err) } host, _ := auth.DefaultHost() sigstoreVerifier, err := verification.NewLiveSigstoreVerifier(sigstoreConfig) require.NoError(t, err) baseOpts := Options{ APIClient: api.NewLiveClient(hc, host, logger), ArtifactPath: artifactPath, BundlePath: bundlePath, Config: cmdFactory.Config, DigestAlgorithm: "sha256", Logger: logger, OCIClient: oci.NewLiveClient(), OIDCIssuer: verification.GitHubOIDCIssuer, Owner: "malancas", PredicateType: verification.SLSAPredicateV1, Repo: "malancas/attest-demo", SigstoreVerifier: sigstoreVerifier, } type testcase struct { name string signerWorkflow string expectErr bool host string } testcases := []testcase{ { name: "with invalid signer workflow", signerWorkflow: "foo/bar/.github/workflows/attest.yml", expectErr: true, }, { name: "valid signer workflow with host", signerWorkflow: "github.com/github/artifact-attestations-workflows/.github/workflows/attest.yml", expectErr: false, }, { name: "valid signer workflow without host (defaults to github.com)", signerWorkflow: "github/artifact-attestations-workflows/.github/workflows/attest.yml", expectErr: false, host: "github.com", }, } for _, tc := range testcases { opts := baseOpts opts.SignerWorkflow = tc.signerWorkflow opts.Hostname = tc.host err := runVerify(&opts) if tc.expectErr { require.Error(t, err, "expected error for '%s'", tc.name) } else { require.NoError(t, err, "unexpected error for '%s'", tc.name) } } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/verify/options_test.go
pkg/cmd/attestation/verify/options_test.go
package verify import ( "testing" "github.com/cli/cli/v2/pkg/cmd/attestation/test" "github.com/stretchr/testify/require" ) var ( publicGoodArtifactPath = test.NormalizeRelativePath("../test/data/sigstore-js-2.1.0.tgz") publicGoodBundlePath = test.NormalizeRelativePath("../test/data/psigstore-js-2.1.0-bundle.json") ) var baseOptions = Options{ ArtifactPath: publicGoodArtifactPath, BundlePath: publicGoodBundlePath, DigestAlgorithm: "sha512", Limit: 1, Owner: "sigstore", OIDCIssuer: "some issuer", } func TestAreFlagsValid(t *testing.T) { t.Run("has invalid Repo value", func(t *testing.T) { opts := baseOptions opts.Repo = "sigstoresigstore-js" err := opts.AreFlagsValid() require.Error(t, err) require.ErrorContains(t, err, "invalid value provided for repo") }) t.Run("invalid limit == 0", func(t *testing.T) { opts := baseOptions opts.Limit = 0 err := opts.AreFlagsValid() require.Error(t, err) require.ErrorContains(t, err, "limit 0 not allowed, must be between 1 and 1000") }) t.Run("invalid limit > 1000", func(t *testing.T) { opts := baseOptions opts.Limit = 1001 err := opts.AreFlagsValid() require.Error(t, err) require.ErrorContains(t, err, "limit 1001 not allowed, must be between 1 and 1000") }) t.Run("returns error when UseBundleFromRegistry is true and ArtifactPath is not an OCI path", func(t *testing.T) { opts := baseOptions opts.BundlePath = "" opts.UseBundleFromRegistry = true err := opts.AreFlagsValid() require.Error(t, err) require.ErrorContains(t, err, "bundle-from-oci flag can only be used with OCI artifact paths") }) t.Run("does not return error when UseBundleFromRegistry is true and ArtifactPath is an OCI path", func(t *testing.T) { opts := baseOptions opts.ArtifactPath = "oci://sigstore/sigstore-js:2.1.0" opts.BundlePath = "" opts.UseBundleFromRegistry = true err := opts.AreFlagsValid() require.NoError(t, err) }) t.Run("returns error when UseBundleFromRegistry is true and BundlePath is provided", func(t *testing.T) { opts := baseOptions opts.ArtifactPath = "oci://sigstore/sigstore-js:2.1.0" opts.UseBundleFromRegistry = true err := opts.AreFlagsValid() require.Error(t, err) require.ErrorContains(t, err, "bundle-from-oci flag cannot be used with bundle-path flag") }) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/verify/options.go
pkg/cmd/attestation/verify/options.go
package verify import ( "fmt" "path/filepath" "strings" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghinstance" "github.com/cli/cli/v2/pkg/cmd/attestation/api" "github.com/cli/cli/v2/pkg/cmd/attestation/artifact/oci" "github.com/cli/cli/v2/pkg/cmd/attestation/io" "github.com/cli/cli/v2/pkg/cmd/attestation/verification" "github.com/cli/cli/v2/pkg/cmdutil" ) // Options captures the options for the verify command type Options struct { ArtifactPath string BundlePath string UseBundleFromRegistry bool Config func() (gh.Config, error) TrustedRoot string DenySelfHostedRunner bool DigestAlgorithm string Limit int NoPublicGood bool OIDCIssuer string Owner string PredicateType string Repo string SAN string SANRegex string SignerDigest string SignerRepo string SignerWorkflow string SourceDigest string SourceRef string APIClient api.Client Logger *io.Handler OCIClient oci.Client SigstoreVerifier verification.SigstoreVerifier exporter cmdutil.Exporter Hostname string // Tenant is only set when tenancy is used Tenant string } // Clean cleans the file path option values func (opts *Options) Clean() { if opts.BundlePath != "" { opts.BundlePath = filepath.Clean(opts.BundlePath) } } // FetchAttestationsFromGitHubAPI returns true if the command should fetch attestations from the GitHub API // It checks that a bundle path is not provided and that the "use bundle from registry" flag is not set func (opts *Options) FetchAttestationsFromGitHubAPI() bool { return opts.BundlePath == "" && !opts.UseBundleFromRegistry } // AreFlagsValid checks that the provided flag combination is valid // and returns an error otherwise func (opts *Options) AreFlagsValid() error { // If provided, check that the Repo option is in the expected format <OWNER>/<REPO> if opts.Repo != "" && !isProvidedRepoValid(opts.Repo) { return fmt.Errorf("invalid value provided for repo: %s", opts.Repo) } // If provided, check that the SignerRepo option is in the expected format <OWNER>/<REPO> if opts.SignerRepo != "" && !isProvidedRepoValid(opts.SignerRepo) { return fmt.Errorf("invalid value provided for signer-repo: %s", opts.SignerRepo) } // Check that limit is between 1 and 1000 if opts.Limit < 1 || opts.Limit > 1000 { return fmt.Errorf("limit %d not allowed, must be between 1 and 1000", opts.Limit) } // Check that the bundle-from-oci flag is only used with OCI artifact paths if opts.UseBundleFromRegistry && !strings.HasPrefix(opts.ArtifactPath, "oci://") { return fmt.Errorf("bundle-from-oci flag can only be used with OCI artifact paths") } // Check that both the bundle-from-oci and bundle-path flags are not used together if opts.UseBundleFromRegistry && opts.BundlePath != "" { return fmt.Errorf("bundle-from-oci flag cannot be used with bundle-path flag") } // Verify provided hostname if opts.Hostname != "" { if err := ghinstance.HostnameValidator(opts.Hostname); err != nil { return fmt.Errorf("error parsing hostname: %w", err) } } return nil } func isProvidedRepoValid(repo string) bool { // we expect a provided repository argument be in the format <OWNER>/<REPO> splitRepo := strings.Split(repo, "/") return len(splitRepo) == 2 }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/verify/attestation.go
pkg/cmd/attestation/verify/attestation.go
package verify import ( "errors" "fmt" "github.com/cli/cli/v2/internal/text" "github.com/cli/cli/v2/pkg/cmd/attestation/api" "github.com/cli/cli/v2/pkg/cmd/attestation/artifact" "github.com/cli/cli/v2/pkg/cmd/attestation/verification" ) func getAttestations(o *Options, a artifact.DigestedArtifact) ([]*api.Attestation, string, error) { // Fetch attestations from GitHub API within this if block since predicate type // filter is done when the API is called if o.FetchAttestationsFromGitHubAPI() { if o.APIClient == nil { errMsg := "✗ No APIClient provided" return nil, errMsg, errors.New(errMsg) } params := api.FetchParams{ Digest: a.DigestWithAlg(), Limit: o.Limit, Owner: o.Owner, PredicateType: o.PredicateType, Repo: o.Repo, Initiator: "user", } attestations, err := o.APIClient.GetByDigest(params) if err != nil { msg := "✗ Loading attestations from GitHub API failed" return nil, msg, err } pluralAttestation := text.Pluralize(len(attestations), "attestation") msg := fmt.Sprintf("Loaded %s from GitHub API", pluralAttestation) return attestations, msg, nil } // Fetch attestations from local bundle or OCI registry // Predicate type filtering is done after the attestations are fetched var attestations []*api.Attestation var err error var msg string if o.BundlePath != "" { attestations, err = verification.GetLocalAttestations(o.BundlePath) if err != nil { pluralAttestation := text.Pluralize(len(attestations), "attestation") msg = fmt.Sprintf("Loaded %s from %s", pluralAttestation, o.BundlePath) } else { msg = fmt.Sprintf("Loaded %d attestations from %s", len(attestations), o.BundlePath) } } else if o.UseBundleFromRegistry { attestations, err = verification.GetOCIAttestations(o.OCIClient, a) if err != nil { msg = "✗ Loading attestations from OCI registry failed" } else { pluralAttestation := text.Pluralize(len(attestations), "attestation") msg = fmt.Sprintf("Loaded %s from OCI registry", pluralAttestation) } } if err != nil { return nil, msg, err } filtered, err := api.FilterAttestations(o.PredicateType, attestations) if err != nil { return nil, err.Error(), err } return filtered, msg, nil } func verifyAttestations(art artifact.DigestedArtifact, att []*api.Attestation, sgVerifier verification.SigstoreVerifier, ec verification.EnforcementCriteria) ([]*verification.AttestationProcessingResult, string, error) { sgPolicy, err := buildSigstoreVerifyPolicy(ec, art) if err != nil { logMsg := "✗ Failed to build Sigstore verification policy" return nil, logMsg, err } sigstoreVerified, err := sgVerifier.Verify(att, sgPolicy) if err != nil { logMsg := "✗ Sigstore verification failed" return nil, logMsg, err } // Verify extensions certExtVerified, err := verification.VerifyCertExtensions(sigstoreVerified, ec) if err != nil { logMsg := "✗ Policy verification failed" return nil, logMsg, err } return certExtVerified, "", nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/verify/attestation_integration_test.go
pkg/cmd/attestation/verify/attestation_integration_test.go
//go:build integration package verify import ( "net/http" "testing" "github.com/cli/cli/v2/pkg/cmd/attestation/api" "github.com/cli/cli/v2/pkg/cmd/attestation/artifact" "github.com/cli/cli/v2/pkg/cmd/attestation/io" "github.com/cli/cli/v2/pkg/cmd/attestation/test" "github.com/cli/cli/v2/pkg/cmd/attestation/verification" o "github.com/cli/cli/v2/pkg/option" "github.com/sigstore/sigstore-go/pkg/fulcio/certificate" "github.com/stretchr/testify/require" ) func getAttestationsFor(t *testing.T, bundlePath string) []*api.Attestation { t.Helper() attestations, err := verification.GetLocalAttestations(bundlePath) require.NoError(t, err) return attestations } func TestVerifyAttestations(t *testing.T) { sgVerifier, err := verification.NewLiveSigstoreVerifier(verification.SigstoreConfig{ HttpClient: http.DefaultClient, Logger: io.NewTestHandler(), TUFMetadataDir: o.Some(t.TempDir()), }) require.NoError(t, err) certSummary := certificate.Summary{} certSummary.SourceRepositoryOwnerURI = "https://github.com/sigstore" certSummary.SourceRepositoryURI = "https://github.com/sigstore/sigstore-js" certSummary.Issuer = verification.GitHubOIDCIssuer ec := verification.EnforcementCriteria{ Certificate: certSummary, PredicateType: verification.SLSAPredicateV1, SANRegex: "^https://github.com/sigstore/", } require.NoError(t, ec.Valid()) artifactPath := test.NormalizeRelativePath("../test/data/sigstore-js-2.1.0.tgz") a, err := artifact.NewDigestedArtifact(nil, artifactPath, "sha512") require.NoError(t, err) t.Run("all attestations pass verification", func(t *testing.T) { attestations := getAttestationsFor(t, "../test/data/sigstore-js-2.1.0_with_2_bundles.jsonl") require.Len(t, attestations, 2) results, errMsg, err := verifyAttestations(*a, attestations, sgVerifier, ec) require.NoError(t, err) require.Zero(t, errMsg) require.Len(t, results, 2) }) t.Run("passes verification with 2/3 attestations passing Sigstore verification", func(t *testing.T) { invalidBundle := getAttestationsFor(t, "../test/data/sigstore-js-2.1.0-bundle-v0.1.json") attestations := getAttestationsFor(t, "../test/data/sigstore-js-2.1.0_with_2_bundles.jsonl") attestations = append(attestations, invalidBundle[0]) require.Len(t, attestations, 3) results, errMsg, err := verifyAttestations(*a, attestations, sgVerifier, ec) require.NoError(t, err) require.Zero(t, errMsg) require.Len(t, results, 2) }) t.Run("fails verification when Sigstore verification fails", func(t *testing.T) { invalidBundle := getAttestationsFor(t, "../test/data/sigstore-js-2.1.0-bundle-v0.1.json") invalidBundle2 := getAttestationsFor(t, "../test/data/sigstore-js-2.1.0-bundle-v0.1.json") attestations := append(invalidBundle, invalidBundle2...) require.Len(t, attestations, 2) results, errMsg, err := verifyAttestations(*a, attestations, sgVerifier, ec) require.Error(t, err) require.Contains(t, errMsg, "✗ Sigstore verification failed") require.Nil(t, results) }) t.Run("attestations fail to verify when cert extensions don't match enforcement criteria", func(t *testing.T) { sgjAttestation := getAttestationsFor(t, "../test/data/sigstore-js-2.1.0_with_2_bundles.jsonl") reusableWorkflowAttestations := getAttestationsFor(t, "../test/data/reusable-workflow-attestation.sigstore.json") attestations := []*api.Attestation{sgjAttestation[0], reusableWorkflowAttestations[0], sgjAttestation[1]} require.Len(t, attestations, 3) rwfResult := verification.BuildMockResult(reusableWorkflowAttestations[0].Bundle, "", "", "https://github.com/malancas", "", verification.GitHubOIDCIssuer) sgjResult := verification.BuildSigstoreJsMockResult(t) mockResults := []*verification.AttestationProcessingResult{&sgjResult, &rwfResult, &sgjResult} mockSgVerifier := verification.NewMockSigstoreVerifierWithMockResults(t, mockResults) // we want to test that attestations that pass Sigstore verification but fail // cert extension verification are filtered out properly in the second step // in verifyAttestations. By using a mock Sigstore verifier, we can ensure // that the call to verification.VerifyCertExtensions in verifyAttestations // is filtering out attestations as expected results, errMsg, err := verifyAttestations(*a, attestations, mockSgVerifier, ec) require.NoError(t, err) require.Zero(t, errMsg) require.Len(t, results, 2) for _, result := range results { require.NotEqual(t, result.Attestation.Bundle, reusableWorkflowAttestations[0].Bundle) } }) t.Run("fails verification when cert extension verification fails", func(t *testing.T) { attestations := getAttestationsFor(t, "../test/data/sigstore-js-2.1.0_with_2_bundles.jsonl") require.Len(t, attestations, 2) expectedCriteria := ec expectedCriteria.Certificate.SourceRepositoryOwnerURI = "https://github.com/wrong" results, errMsg, err := verifyAttestations(*a, attestations, sgVerifier, expectedCriteria) require.Error(t, err) require.Contains(t, errMsg, "✗ Policy verification failed") require.Nil(t, results) }) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/verification/policy.go
pkg/cmd/attestation/verification/policy.go
package verification import ( "encoding/hex" "fmt" "strings" "github.com/cli/cli/v2/pkg/cmd/attestation/artifact" "github.com/sigstore/sigstore-go/pkg/fulcio/certificate" "github.com/sigstore/sigstore-go/pkg/verify" ) // represents the GitHub hosted runner in the certificate RunnerEnvironment extension const GitHubRunner = "github-hosted" // BuildDigestPolicyOption builds a verify.ArtifactPolicyOption // from the given artifact digest and digest algorithm func BuildDigestPolicyOption(a artifact.DigestedArtifact) (verify.ArtifactPolicyOption, error) { // sigstore-go expects the artifact digest to be decoded from hex decoded, err := hex.DecodeString(a.Digest()) if err != nil { return nil, err } return verify.WithArtifactDigest(a.Algorithm(), decoded), nil } type EnforcementCriteria struct { Certificate certificate.Summary PredicateType string SANRegex string SAN string } func (c EnforcementCriteria) Valid() error { if c.Certificate.Issuer == "" { return fmt.Errorf("Issuer must be set") } if c.Certificate.RunnerEnvironment != "" && c.Certificate.RunnerEnvironment != GitHubRunner { return fmt.Errorf("RunnerEnvironment must be set to either \"\" or %s", GitHubRunner) } if c.Certificate.SourceRepositoryOwnerURI == "" { return fmt.Errorf("SourceRepositoryOwnerURI must be set") } if c.PredicateType == "" { return fmt.Errorf("PredicateType must be set") } if c.SANRegex == "" && c.SAN == "" { return fmt.Errorf("SANRegex or SAN must be set") } return nil } func (c EnforcementCriteria) BuildPolicyInformation() string { policyAttr := [][]string{} policyAttr = appendStr(policyAttr, "- Predicate type must match", c.PredicateType) policyAttr = appendStr(policyAttr, "- Source Repository Owner URI must match", c.Certificate.SourceRepositoryOwnerURI) if c.Certificate.SourceRepositoryURI != "" { policyAttr = appendStr(policyAttr, "- Source Repository URI must match", c.Certificate.SourceRepositoryURI) } if c.Certificate.BuildSignerDigest != "" { policyAttr = appendStr(policyAttr, "- Build signer digest must match", c.Certificate.BuildSignerDigest) } if c.Certificate.SourceRepositoryDigest != "" { policyAttr = appendStr(policyAttr, "- Source repo digest digest must match", c.Certificate.SourceRepositoryDigest) } if c.Certificate.SourceRepositoryRef != "" { policyAttr = appendStr(policyAttr, "- Source repo ref must match", c.Certificate.SourceRepositoryRef) } if c.SAN != "" { policyAttr = appendStr(policyAttr, "- Subject Alternative Name must match", c.SAN) } else if c.SANRegex != "" { policyAttr = appendStr(policyAttr, "- Subject Alternative Name must match regex", c.SANRegex) } policyAttr = appendStr(policyAttr, "- OIDC Issuer must match", c.Certificate.Issuer) if c.Certificate.RunnerEnvironment == GitHubRunner { policyAttr = appendStr(policyAttr, "- Action workflow Runner Environment must match ", GitHubRunner) } maxColLen := 0 for _, attr := range policyAttr { if len(attr[0]) > maxColLen { maxColLen = len(attr[0]) } } policyInfo := "" for _, attr := range policyAttr { dots := strings.Repeat(".", maxColLen-len(attr[0])) policyInfo += fmt.Sprintf("%s:%s %s\n", attr[0], dots, attr[1]) } return policyInfo } func appendStr(arr [][]string, a, b string) [][]string { return append(arr, []string{a, b}) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/verification/sigstore_integration_test.go
pkg/cmd/attestation/verification/sigstore_integration_test.go
//go:build integration package verification import ( "net/http" "testing" "github.com/cli/cli/v2/pkg/cmd/attestation/api" "github.com/cli/cli/v2/pkg/cmd/attestation/artifact" "github.com/cli/cli/v2/pkg/cmd/attestation/io" "github.com/cli/cli/v2/pkg/cmd/attestation/test" o "github.com/cli/cli/v2/pkg/option" "github.com/sigstore/sigstore-go/pkg/verify" "github.com/stretchr/testify/require" ) func TestLiveSigstoreVerifier(t *testing.T) { type testcase struct { name string attestations []*api.Attestation expectErr bool errContains string } testcases := []testcase{ { name: "with invalid signature", attestations: getAttestationsFor(t, "../test/data/sigstoreBundle-invalid-signature.json"), expectErr: true, errContains: "verifying with issuer \"sigstore.dev\"", }, { name: "with valid artifact and JSON lines file containing multiple Sigstore bundles", attestations: getAttestationsFor(t, "../test/data/sigstore-js-2.1.0_with_2_bundles.jsonl"), }, { name: "with invalid bundle version", attestations: getAttestationsFor(t, "../test/data/sigstore-js-2.1.0-bundle-v0.1.json"), expectErr: true, errContains: "unsupported bundle version", }, { name: "with no attestations", attestations: []*api.Attestation{}, expectErr: true, errContains: "no attestations were verified", }, } for _, tc := range testcases { t.Run(tc.name, func(t *testing.T) { verifier, err := NewLiveSigstoreVerifier(SigstoreConfig{ HttpClient: http.DefaultClient, Logger: io.NewTestHandler(), TUFMetadataDir: o.Some(t.TempDir()), }) require.NoError(t, err) results, err := verifier.Verify(tc.attestations, publicGoodPolicy(t)) if tc.expectErr { require.Error(t, err) require.ErrorContains(t, err, tc.errContains) require.Nil(t, results) } else { require.NoError(t, err) require.Equal(t, len(tc.attestations), len(results)) } }) } t.Run("with 2/3 verified attestations", func(t *testing.T) { verifier, err := NewLiveSigstoreVerifier(SigstoreConfig{ HttpClient: http.DefaultClient, Logger: io.NewTestHandler(), TUFMetadataDir: o.Some(t.TempDir()), }) require.NoError(t, err) invalidBundle := getAttestationsFor(t, "../test/data/sigstore-js-2.1.0-bundle-v0.1.json") attestations := getAttestationsFor(t, "../test/data/sigstore-js-2.1.0_with_2_bundles.jsonl") attestations = append(attestations, invalidBundle[0]) require.Len(t, attestations, 3) results, err := verifier.Verify(attestations, publicGoodPolicy(t)) require.Len(t, results, 2) require.NoError(t, err) }) t.Run("fail with 0/2 verified attestations", func(t *testing.T) { verifier, err := NewLiveSigstoreVerifier(SigstoreConfig{ HttpClient: http.DefaultClient, Logger: io.NewTestHandler(), TUFMetadataDir: o.Some(t.TempDir()), }) require.NoError(t, err) invalidBundle := getAttestationsFor(t, "../test/data/sigstore-js-2.1.0-bundle-v0.1.json") attestations := getAttestationsFor(t, "../test/data/sigstoreBundle-invalid-signature.json") attestations = append(attestations, invalidBundle[0]) require.Len(t, attestations, 2) results, err := verifier.Verify(attestations, publicGoodPolicy(t)) require.Nil(t, results) require.Error(t, err) }) t.Run("with GitHub Sigstore artifact", func(t *testing.T) { githubArtifactPath := test.NormalizeRelativePath("../test/data/github_provenance_demo-0.0.12-py3-none-any.whl") githubArtifact, err := artifact.NewDigestedArtifact(nil, githubArtifactPath, "sha256") require.NoError(t, err) githubPolicy := buildPolicy(t, *githubArtifact) attestations := getAttestationsFor(t, "../test/data/github_provenance_demo-0.0.12-py3-none-any-bundle.jsonl") verifier, err := NewLiveSigstoreVerifier(SigstoreConfig{ HttpClient: http.DefaultClient, Logger: io.NewTestHandler(), TUFMetadataDir: o.Some(t.TempDir()), }) require.NoError(t, err) results, err := verifier.Verify(attestations, githubPolicy) require.Len(t, results, 1) require.NoError(t, err) }) t.Run("with custom trusted root", func(t *testing.T) { attestations := getAttestationsFor(t, "../test/data/sigstore-js-2.1.0_with_2_bundles.jsonl") verifier, err := NewLiveSigstoreVerifier(SigstoreConfig{ HttpClient: http.DefaultClient, Logger: io.NewTestHandler(), TrustedRoot: test.NormalizeRelativePath("../test/data/trusted_root.json"), TUFMetadataDir: o.Some(t.TempDir()), }) require.NoError(t, err) results, err := verifier.Verify(attestations, publicGoodPolicy(t)) require.Len(t, results, 2) require.NoError(t, err) }) } func publicGoodPolicy(t *testing.T) verify.PolicyBuilder { t.Helper() artifactPath := test.NormalizeRelativePath("../test/data/sigstore-js-2.1.0.tgz") publicGoodArtifact, err := artifact.NewDigestedArtifact(nil, artifactPath, "sha512") require.NoError(t, err) return buildPolicy(t, *publicGoodArtifact) } func buildPolicy(t *testing.T, artifact artifact.DigestedArtifact) verify.PolicyBuilder { t.Helper() artifactDigestPolicyOption, err := BuildDigestPolicyOption(artifact) require.NoError(t, err) return verify.NewPolicy(artifactDigestPolicyOption, verify.WithoutIdentitiesUnsafe()) } func getAttestationsFor(t *testing.T, bundlePath string) []*api.Attestation { t.Helper() attestations, err := GetLocalAttestations(bundlePath) require.NoError(t, err) return attestations }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/verification/tuf.go
pkg/cmd/attestation/verification/tuf.go
package verification import ( _ "embed" "net/http" "os" "path/filepath" "github.com/cenkalti/backoff/v5" o "github.com/cli/cli/v2/pkg/option" "github.com/cli/go-gh/v2/pkg/config" "github.com/sigstore/sigstore-go/pkg/tuf" "github.com/theupdateframework/go-tuf/v2/metadata/fetcher" ) //go:embed embed/tuf-repo.github.com/root.json var githubRoot []byte const GitHubTUFMirror = "https://tuf-repo.github.com" func DefaultOptionsWithCacheSetting(tufMetadataDir o.Option[string], hc *http.Client) *tuf.Options { opts := tuf.DefaultOptions() // The CODESPACES environment variable will be set to true in a Codespaces workspace if os.Getenv("CODESPACES") == "true" { // if the tool is being used in a Codespace, disable the local cache // because there is a permissions issue preventing the tuf library // from writing the Sigstore cache to the home directory opts.DisableLocalCache = true } // Set the cache path to the provided dir, or a directory owned by the CLI opts.CachePath = tufMetadataDir.UnwrapOr(filepath.Join(config.CacheDir(), ".sigstore", "root")) // Allow TUF cache for 1 day opts.CacheValidity = 1 // configure fetcher timeout and retry f := fetcher.NewDefaultFetcher() f.SetHTTPClient(hc) retryOptions := []backoff.RetryOption{backoff.WithMaxTries(3)} f.SetRetryOptions(retryOptions...) opts.WithFetcher(f) return opts } func GitHubTUFOptions(tufMetadataDir o.Option[string], hc *http.Client) *tuf.Options { opts := DefaultOptionsWithCacheSetting(tufMetadataDir, hc) opts.Root = githubRoot opts.RepositoryBaseURL = GitHubTUFMirror return opts }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/verification/sigstore_test.go
pkg/cmd/attestation/verification/sigstore_test.go
package verification import ( "testing" "github.com/cli/cli/v2/pkg/cmd/attestation/io" "github.com/stretchr/testify/require" ) // Note: Tests that require network access and TUF client initialization // are in sigstore_integration_test.go with the //go:build integration tag. // These unit tests focus on testing the logic without requiring network access. // TestChooseVerifierWithNilPublicGood tests that chooseVerifier returns an error // when a PGI attestation is encountered but the PGI verifier is nil (failed initialization). func TestChooseVerifierWithNilPublicGood(t *testing.T) { verifier := &LiveSigstoreVerifier{ Logger: io.NewTestHandler(), NoPublicGood: false, PublicGood: nil, // Simulate failed PGI initialization GitHub: nil, // Not needed for this test } _, err := verifier.chooseVerifier(PublicGoodIssuerOrg) require.Error(t, err) require.ErrorContains(t, err, "public good verifier is not available") } // TestChooseVerifierUnrecognizedIssuer tests that an error is returned // for unrecognized issuers. func TestChooseVerifierUnrecognizedIssuer(t *testing.T) { verifier := &LiveSigstoreVerifier{ Logger: io.NewTestHandler(), NoPublicGood: false, } _, err := verifier.chooseVerifier("unknown-issuer") require.Error(t, err) require.ErrorContains(t, err, "leaf certificate issuer is not recognized") } func TestLiveSigstoreVerifier_noVerifierSet(t *testing.T) { verifier := &LiveSigstoreVerifier{ Logger: io.NewTestHandler(), NoPublicGood: true, PublicGood: nil, GitHub: nil, } require.True(t, verifier.noVerifierSet()) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/verification/mock_verifier.go
pkg/cmd/attestation/verification/mock_verifier.go
package verification import ( "fmt" "testing" "github.com/cli/cli/v2/pkg/cmd/attestation/api" "github.com/cli/cli/v2/pkg/cmd/attestation/test/data" "github.com/sigstore/sigstore-go/pkg/bundle" "github.com/sigstore/sigstore-go/pkg/fulcio/certificate" in_toto "github.com/in-toto/attestation/go/v1" "github.com/sigstore/sigstore-go/pkg/verify" ) type MockSigstoreVerifier struct { t *testing.T mockResults []*AttestationProcessingResult } func (v *MockSigstoreVerifier) Verify([]*api.Attestation, verify.PolicyBuilder) ([]*AttestationProcessingResult, error) { if v.mockResults != nil { return v.mockResults, nil } statement := &in_toto.Statement{} statement.PredicateType = SLSAPredicateV1 result := AttestationProcessingResult{ Attestation: &api.Attestation{ Bundle: data.SigstoreBundle(v.t), }, VerificationResult: &verify.VerificationResult{ Statement: statement, Signature: &verify.SignatureVerificationResult{ Certificate: &certificate.Summary{ Extensions: certificate.Extensions{ BuildSignerURI: "https://github.com/github/example/.github/workflows/release.yml@refs/heads/main", SourceRepositoryOwnerURI: "https://github.com/sigstore", SourceRepositoryURI: "https://github.com/sigstore/sigstore-js", Issuer: "https://token.actions.githubusercontent.com", }, }, }, }, } results := []*AttestationProcessingResult{&result} return results, nil } func NewMockSigstoreVerifier(t *testing.T) *MockSigstoreVerifier { result := BuildSigstoreJsMockResult(t) results := []*AttestationProcessingResult{&result} return &MockSigstoreVerifier{t, results} } func NewMockSigstoreVerifierWithMockResults(t *testing.T, mockResults []*AttestationProcessingResult) *MockSigstoreVerifier { return &MockSigstoreVerifier{t, mockResults} } type FailSigstoreVerifier struct{} func (v *FailSigstoreVerifier) Verify([]*api.Attestation, verify.PolicyBuilder) ([]*AttestationProcessingResult, error) { return nil, fmt.Errorf("failed to verify attestations") } func BuildMockResult(b *bundle.Bundle, buildConfigURI, buildSignerURI, sourceRepoOwnerURI, sourceRepoURI, issuer string) AttestationProcessingResult { statement := &in_toto.Statement{} statement.PredicateType = SLSAPredicateV1 return AttestationProcessingResult{ Attestation: &api.Attestation{ Bundle: b, }, VerificationResult: &verify.VerificationResult{ Statement: statement, Signature: &verify.SignatureVerificationResult{ Certificate: &certificate.Summary{ Extensions: certificate.Extensions{ BuildConfigURI: buildConfigURI, BuildSignerURI: buildSignerURI, Issuer: issuer, SourceRepositoryOwnerURI: sourceRepoOwnerURI, SourceRepositoryURI: sourceRepoURI, }, }, }, }, } } func BuildSigstoreJsMockResult(t *testing.T) AttestationProcessingResult { bundle := data.SigstoreBundle(t) buildConfigURI := "https://github.com/sigstore/sigstore-js/.github/workflows/build.yml@refs/heads/main" buildSignerURI := "https://github.com/github/example/.github/workflows/release.yml@refs/heads/main" sourceRepoOwnerURI := "https://github.com/sigstore" sourceRepoURI := "https://github.com/sigstore/sigstore-js" issuer := "https://token.actions.githubusercontent.com" return BuildMockResult(bundle, buildConfigURI, buildSignerURI, sourceRepoOwnerURI, sourceRepoURI, issuer) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/verification/extensions_test.go
pkg/cmd/attestation/verification/extensions_test.go
package verification import ( "testing" "github.com/sigstore/sigstore-go/pkg/fulcio/certificate" "github.com/sigstore/sigstore-go/pkg/verify" "github.com/stretchr/testify/require" ) func createSampleResult() *AttestationProcessingResult { return &AttestationProcessingResult{ VerificationResult: &verify.VerificationResult{ Signature: &verify.SignatureVerificationResult{ Certificate: &certificate.Summary{ Extensions: certificate.Extensions{ SourceRepositoryOwnerURI: "https://github.com/owner", SourceRepositoryURI: "https://github.com/owner/repo", Issuer: "https://token.actions.githubusercontent.com", }, }, }, }, } } func TestVerifyCertExtensions(t *testing.T) { results := []*AttestationProcessingResult{createSampleResult()} certSummary := certificate.Summary{} certSummary.SourceRepositoryOwnerURI = "https://github.com/owner" certSummary.SourceRepositoryURI = "https://github.com/owner/repo" certSummary.Issuer = GitHubOIDCIssuer c := EnforcementCriteria{ Certificate: certSummary, } t.Run("passes with one result", func(t *testing.T) { verified, err := VerifyCertExtensions(results, c) require.NoError(t, err) require.Len(t, verified, 1) }) t.Run("passes with 1/2 valid results", func(t *testing.T) { twoResults := []*AttestationProcessingResult{createSampleResult(), createSampleResult()} require.Len(t, twoResults, 2) twoResults[1].VerificationResult.Signature.Certificate.Extensions.SourceRepositoryOwnerURI = "https://github.com/wrong" verified, err := VerifyCertExtensions(twoResults, c) require.NoError(t, err) require.Len(t, verified, 1) }) t.Run("fails when all results fail verification", func(t *testing.T) { twoResults := []*AttestationProcessingResult{createSampleResult(), createSampleResult()} require.Len(t, twoResults, 2) twoResults[0].VerificationResult.Signature.Certificate.Extensions.SourceRepositoryOwnerURI = "https://github.com/wrong" twoResults[1].VerificationResult.Signature.Certificate.Extensions.SourceRepositoryOwnerURI = "https://github.com/wrong" verified, err := VerifyCertExtensions(twoResults, c) require.Error(t, err) require.Nil(t, verified) }) t.Run("with wrong SourceRepositoryOwnerURI", func(t *testing.T) { expectedCriteria := c expectedCriteria.Certificate.SourceRepositoryOwnerURI = "https://github.com/wrong" verified, err := VerifyCertExtensions(results, expectedCriteria) require.ErrorContains(t, err, "expected SourceRepositoryOwnerURI to be https://github.com/wrong, got https://github.com/owner") require.Nil(t, verified) }) t.Run("with wrong SourceRepositoryURI", func(t *testing.T) { expectedCriteria := c expectedCriteria.Certificate.SourceRepositoryURI = "https://github.com/foo/wrong" verified, err := VerifyCertExtensions(results, expectedCriteria) require.ErrorContains(t, err, "expected SourceRepositoryURI to be https://github.com/foo/wrong, got https://github.com/owner/repo") require.Nil(t, verified) }) t.Run("with wrong OIDCIssuer", func(t *testing.T) { expectedCriteria := c expectedCriteria.Certificate.Issuer = "wrong" verified, err := VerifyCertExtensions(results, expectedCriteria) require.ErrorContains(t, err, "expected Issuer to be wrong, got https://token.actions.githubusercontent.com") require.Nil(t, verified) }) t.Run("with partial OIDCIssuer match", func(t *testing.T) { expectedResults := results expectedResults[0].VerificationResult.Signature.Certificate.Extensions.Issuer = "https://token.actions.githubusercontent.com/foo-bar" verified, err := VerifyCertExtensions(expectedResults, c) require.ErrorContains(t, err, "expected Issuer to be https://token.actions.githubusercontent.com, got https://token.actions.githubusercontent.com/foo-bar -- if you have a custom OIDC issuer") require.Nil(t, verified) }) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/verification/sigstore.go
pkg/cmd/attestation/verification/sigstore.go
package verification import ( "bufio" "bytes" "crypto/x509" "errors" "fmt" "net/http" "os" "github.com/cli/cli/v2/pkg/cmd/attestation/api" "github.com/cli/cli/v2/pkg/cmd/attestation/io" o "github.com/cli/cli/v2/pkg/option" "github.com/sigstore/sigstore-go/pkg/bundle" "github.com/sigstore/sigstore-go/pkg/root" "github.com/sigstore/sigstore-go/pkg/tuf" "github.com/sigstore/sigstore-go/pkg/verify" ) const ( PublicGoodIssuerOrg = "sigstore.dev" GitHubIssuerOrg = "GitHub, Inc." ) // AttestationProcessingResult captures processing a given attestation's signature verification and policy evaluation type AttestationProcessingResult struct { Attestation *api.Attestation `json:"attestation"` VerificationResult *verify.VerificationResult `json:"verificationResult"` } type SigstoreConfig struct { TrustedRoot string Logger *io.Handler NoPublicGood bool HttpClient *http.Client // If tenancy mode is not used, trust domain is empty TrustDomain string // TUFMetadataDir TUFMetadataDir o.Option[string] } type SigstoreVerifier interface { Verify(attestations []*api.Attestation, policy verify.PolicyBuilder) ([]*AttestationProcessingResult, error) } type LiveSigstoreVerifier struct { Logger *io.Handler NoPublicGood bool PublicGood *verify.Verifier GitHub *verify.Verifier Custom map[string]*verify.Verifier } var ErrNoAttestationsVerified = errors.New("no attestations were verified") // NewLiveSigstoreVerifier creates a new LiveSigstoreVerifier struct // that is used to verify artifacts and attestations against the // Public Good, GitHub, or a custom trusted root. func NewLiveSigstoreVerifier(config SigstoreConfig) (*LiveSigstoreVerifier, error) { liveVerifier := &LiveSigstoreVerifier{ Logger: config.Logger, NoPublicGood: config.NoPublicGood, } // if a custom trusted root is set, configure custom verifiers and assume no Public Good or GitHub verifiers // are needed if config.TrustedRoot != "" { customVerifiers, err := createCustomVerifiers(config.TrustedRoot, config.NoPublicGood) if err != nil { return nil, fmt.Errorf("error creating custom verifiers: %s", err) } liveVerifier.Custom = customVerifiers return liveVerifier, nil } // No custom trusted root is set, so configure Public Good and GitHub verifiers if !config.NoPublicGood { publicGoodVerifier, err := newPublicGoodVerifier(config.TUFMetadataDir, config.HttpClient) if err != nil { // Log warning but continue - PGI unavailability should not block GitHub attestation verification config.Logger.VerbosePrintf("Warning: failed to initialize Sigstore Public Good verifier: %v\n", err) config.Logger.VerbosePrintf("Continuing without Public Good Instance verification\n") } else { liveVerifier.PublicGood = publicGoodVerifier } } github, err := newGitHubVerifier(config.TrustDomain, config.TUFMetadataDir, config.HttpClient) if err != nil { config.Logger.VerbosePrintf("Warning: failed to initialize GitHub verifier: %v\n", err) } else { liveVerifier.GitHub = github } if liveVerifier.noVerifierSet() { return nil, fmt.Errorf("no valid Sigstore verifiers could be initialized") } return liveVerifier, nil } func createCustomVerifiers(trustedRoot string, noPublicGood bool) (map[string]*verify.Verifier, error) { customTrustRoots, err := os.ReadFile(trustedRoot) if err != nil { return nil, fmt.Errorf("unable to read file %s: %v", trustedRoot, err) } verifiers := make(map[string]*verify.Verifier) reader := bufio.NewReader(bytes.NewReader(customTrustRoots)) var line []byte var readError error line, readError = reader.ReadBytes('\n') for readError == nil { // Load each trusted root trustedRoot, err := root.NewTrustedRootFromJSON(line) if err != nil { return nil, fmt.Errorf("failed to create custom verifier: %v", err) } // Compare bundle leafCert issuer with trusted root cert authority certAuthorities := trustedRoot.FulcioCertificateAuthorities() for _, certAuthority := range certAuthorities { fulcioCertAuthority, ok := certAuthority.(*root.FulcioCertificateAuthority) if !ok { return nil, fmt.Errorf("trusted root cert authority is not a FulcioCertificateAuthority") } lowestCert, err := getLowestCertInChain(fulcioCertAuthority) if err != nil { return nil, err } // if the custom trusted root issuer is not set, skip it if len(lowestCert.Issuer.Organization) == 0 { continue } issuer := lowestCert.Issuer.Organization[0] // Determine what policy to use with this trusted root. // // Note that we are *only* inferring the policy with the // issuer. We *must* use the trusted root provided. switch issuer { case PublicGoodIssuerOrg: if noPublicGood { return nil, fmt.Errorf("detected public good instance but requested verification without public good instance") } if _, ok := verifiers[PublicGoodIssuerOrg]; ok { // we have already created a public good verifier with this custom trusted root // so we skip it continue } publicGood, err := newPublicGoodVerifierWithTrustedRoot(trustedRoot) if err != nil { return nil, err } verifiers[PublicGoodIssuerOrg] = publicGood case GitHubIssuerOrg: if _, ok := verifiers[GitHubIssuerOrg]; ok { // we have already created a github verifier with this custom trusted root // so we skip it continue } github, err := newGitHubVerifierWithTrustedRoot(trustedRoot) if err != nil { return nil, err } verifiers[GitHubIssuerOrg] = github default: if _, ok := verifiers[issuer]; ok { // we have already created a custom verifier with this custom trusted root // so we skip it continue } // Make best guess at reasonable policy custom, err := newCustomVerifier(trustedRoot) if err != nil { return nil, err } verifiers[issuer] = custom } } line, readError = reader.ReadBytes('\n') } return verifiers, nil } func getBundleIssuer(b *bundle.Bundle) (string, error) { if !b.MinVersion("0.2") { return "", fmt.Errorf("unsupported bundle version: %s", b.MediaType) } verifyContent, err := b.VerificationContent() if err != nil { return "", fmt.Errorf("failed to get bundle verification content: %v", err) } leafCert := verifyContent.Certificate() if leafCert == nil { return "", fmt.Errorf("leaf cert not found") } if len(leafCert.Issuer.Organization) != 1 { return "", fmt.Errorf("expected the leaf certificate issuer to only have one organization") } return leafCert.Issuer.Organization[0], nil } func (v *LiveSigstoreVerifier) chooseVerifier(issuer string) (*verify.Verifier, error) { // if no custom trusted root is set, return either the Public Good or GitHub verifier // If the chosen verifier has not yet been created, create it as a LiveSigstoreVerifier field for use in future calls if v.Custom != nil { custom, ok := v.Custom[issuer] if !ok { return nil, fmt.Errorf("no custom verifier found for issuer \"%s\"", issuer) } return custom, nil } switch issuer { case PublicGoodIssuerOrg: if v.NoPublicGood { return nil, fmt.Errorf("detected public good instance but requested verification without public good instance") } if v.PublicGood == nil { return nil, fmt.Errorf("public good verifier is not available (initialization may have failed)") } return v.PublicGood, nil case GitHubIssuerOrg: return v.GitHub, nil default: return nil, fmt.Errorf("leaf certificate issuer is not recognized") } } func getLowestCertInChain(ca *root.FulcioCertificateAuthority) (*x509.Certificate, error) { if len(ca.Intermediates) > 0 { return ca.Intermediates[0], nil } else if ca.Root != nil { return ca.Root, nil } return nil, fmt.Errorf("certificate authority had no certificates") } func (v *LiveSigstoreVerifier) verify(attestation *api.Attestation, policy verify.PolicyBuilder) (*AttestationProcessingResult, error) { issuer, err := getBundleIssuer(attestation.Bundle) if err != nil { return nil, fmt.Errorf("failed to get bundle issuer: %v", err) } // determine which verifier should attempt verification against the bundle verifier, err := v.chooseVerifier(issuer) if err != nil { return nil, fmt.Errorf("failed to choose verifier based on provided bundle issuer: %v", err) } v.Logger.VerbosePrintf("Attempting verification against issuer \"%s\"\n", issuer) // attempt to verify the attestation result, err := verifier.Verify(attestation.Bundle, policy) // if verification fails, create the error and exit verification early if err != nil { v.Logger.VerbosePrint(v.Logger.ColorScheme.Redf( "Failed to verify against issuer \"%s\" \n\n", issuer, )) return nil, fmt.Errorf("verifying with issuer \"%s\"", issuer) } // if verification is successful, add the result // to the AttestationProcessingResult entry v.Logger.VerbosePrint(v.Logger.ColorScheme.Greenf( "SUCCESS - attestation signature verified with \"%s\"\n", issuer, )) return &AttestationProcessingResult{ Attestation: attestation, VerificationResult: result, }, nil } func (v *LiveSigstoreVerifier) Verify(attestations []*api.Attestation, policy verify.PolicyBuilder) ([]*AttestationProcessingResult, error) { if len(attestations) == 0 { return nil, ErrNoAttestationsVerified } results := make([]*AttestationProcessingResult, len(attestations)) var verifyCount int var lastError error totalAttestations := len(attestations) for i, a := range attestations { v.Logger.VerbosePrintf("Verifying attestation %d/%d against the configured Sigstore trust roots\n", i+1, totalAttestations) apr, err := v.verify(a, policy) if err != nil { lastError = err // move onto the next attestation in the for loop if verification fails continue } // otherwise, add the result to the results slice and increment verifyCount results[verifyCount] = apr verifyCount++ } if verifyCount == 0 { return nil, lastError } // truncate the results slice to only include verified attestations results = results[:verifyCount] return results, nil } func newCustomVerifier(trustedRoot *root.TrustedRoot) (*verify.Verifier, error) { // All we know about this trust root is its configuration so make some // educated guesses as to what the policy should be. verifierConfig := []verify.VerifierOption{} // This requires some independent corroboration of the signing certificate // (e.g. from Sigstore Fulcio) time, one of: // - a signed timestamp from a timestamp authority in the trusted root // - a transparency log entry (e.g. from Sigstore Rekor) verifierConfig = append(verifierConfig, verify.WithObserverTimestamps(1)) // Infer verification options from contents of trusted root if len(trustedRoot.RekorLogs()) > 0 { verifierConfig = append(verifierConfig, verify.WithTransparencyLog(1)) } gv, err := verify.NewVerifier(trustedRoot, verifierConfig...) if err != nil { return nil, fmt.Errorf("failed to create custom verifier: %v", err) } return gv, nil } func newGitHubVerifier(trustDomain string, tufMetadataDir o.Option[string], hc *http.Client) (*verify.Verifier, error) { var tr string opts := GitHubTUFOptions(tufMetadataDir, hc) client, err := tuf.New(opts) if err != nil { return nil, fmt.Errorf("failed to create TUF client: %v", err) } if trustDomain == "" { tr = "trusted_root.json" } else { tr = fmt.Sprintf("%s.trusted_root.json", trustDomain) } jsonBytes, err := client.GetTarget(tr) if err != nil { return nil, err } trustedRoot, err := root.NewTrustedRootFromJSON(jsonBytes) if err != nil { return nil, err } return newGitHubVerifierWithTrustedRoot(trustedRoot) } func newGitHubVerifierWithTrustedRoot(trustedRoot *root.TrustedRoot) (*verify.Verifier, error) { gv, err := verify.NewVerifier(trustedRoot, verify.WithSignedTimestamps(1)) if err != nil { return nil, fmt.Errorf("failed to create GitHub verifier: %v", err) } return gv, nil } func newPublicGoodVerifier(tufMetadataDir o.Option[string], hc *http.Client) (*verify.Verifier, error) { opts := DefaultOptionsWithCacheSetting(tufMetadataDir, hc) client, err := tuf.New(opts) if err != nil { return nil, fmt.Errorf("failed to create TUF client: %v", err) } trustedRoot, err := root.GetTrustedRoot(client) if err != nil { return nil, fmt.Errorf("failed to get trusted root: %v", err) } return newPublicGoodVerifierWithTrustedRoot(trustedRoot) } func newPublicGoodVerifierWithTrustedRoot(trustedRoot *root.TrustedRoot) (*verify.Verifier, error) { sv, err := verify.NewVerifier(trustedRoot, verify.WithSignedCertificateTimestamps(1), verify.WithTransparencyLog(1), verify.WithObserverTimestamps(1)) if err != nil { return nil, fmt.Errorf("failed to create Public Good verifier: %v", err) } return sv, nil } func (v *LiveSigstoreVerifier) noVerifierSet() bool { return v.PublicGood == nil && v.GitHub == nil && len(v.Custom) == 0 }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/verification/attestation_test.go
pkg/cmd/attestation/verification/attestation_test.go
package verification import ( "os" "path/filepath" "testing" protobundle "github.com/sigstore/protobuf-specs/gen/pb-go/bundle/v1" dsse "github.com/sigstore/protobuf-specs/gen/pb-go/dsse" "github.com/sigstore/sigstore-go/pkg/bundle" "github.com/stretchr/testify/require" "github.com/cli/cli/v2/pkg/cmd/attestation/api" ) func TestLoadBundlesFromJSONLinesFile(t *testing.T) { t.Run("with original file", func(t *testing.T) { path := "../test/data/sigstore-js-2.1.0_with_2_bundles.jsonl" attestations, err := loadBundlesFromJSONLinesFile(path) require.NoError(t, err) require.Len(t, attestations, 2) }) t.Run("with extra lines", func(t *testing.T) { // Create a temporary file with extra lines tempDir := t.TempDir() tempFile := filepath.Join(tempDir, "test_with_extra_lines.jsonl") originalContent, err := os.ReadFile("../test/data/sigstore-js-2.1.0_with_2_bundles.jsonl") require.NoError(t, err) extraLines := []byte("\n\n") newContent := append(originalContent, extraLines...) err = os.WriteFile(tempFile, newContent, 0644) require.NoError(t, err) // Test the function with the new file attestations, err := loadBundlesFromJSONLinesFile(tempFile) require.NoError(t, err) require.Len(t, attestations, 2, "Should still load 2 valid attestations") }) } func TestLoadBundlesFromJSONLinesFile_RejectEmptyJSONLFile(t *testing.T) { // Create a temporary file emptyJSONL, err := os.CreateTemp("", "empty.jsonl") require.NoError(t, err) err = emptyJSONL.Close() require.NoError(t, err) attestations, err := loadBundlesFromJSONLinesFile(emptyJSONL.Name()) require.ErrorIs(t, err, ErrEmptyBundleFile) require.Nil(t, attestations) } func TestLoadBundleFromJSONFile(t *testing.T) { path := "../test/data/sigstore-js-2.1.0-bundle.json" attestations, err := loadBundleFromJSONFile(path) require.NoError(t, err) require.Len(t, attestations, 1) } func TestGetLocalAttestations(t *testing.T) { t.Run("with JSON file containing one bundle", func(t *testing.T) { path := "../test/data/sigstore-js-2.1.0-bundle.json" attestations, err := GetLocalAttestations(path) require.NoError(t, err) require.Len(t, attestations, 1) }) t.Run("with JSON lines file containing multiple bundles", func(t *testing.T) { path := "../test/data/sigstore-js-2.1.0_with_2_bundles.jsonl" attestations, err := GetLocalAttestations(path) require.NoError(t, err) require.Len(t, attestations, 2) }) t.Run("with file with unrecognized extension", func(t *testing.T) { path := "../test/data/sigstore-js-2.1.0-bundles.tgz" attestations, err := GetLocalAttestations(path) require.ErrorIs(t, err, ErrUnrecognisedBundleExtension) require.Nil(t, attestations) }) t.Run("with non-existent bundle file and JSON file", func(t *testing.T) { path := "../test/data/not-found-bundle.json" attestations, err := GetLocalAttestations(path) require.ErrorContains(t, err, "could not load content from file path") require.Nil(t, attestations) }) t.Run("with non-existent bundle file and JSON lines file", func(t *testing.T) { path := "../test/data/not-found-bundle.jsonl" attestations, err := GetLocalAttestations(path) require.ErrorContains(t, err, "could not load content from file path") require.Nil(t, attestations) }) t.Run("with missing verification material", func(t *testing.T) { path := "../test/data/github_provenance_demo-0.0.12-py3-none-any-bundle-missing-verification-material.jsonl" _, err := GetLocalAttestations(path) require.ErrorIs(t, err, bundle.ErrMissingVerificationMaterial) }) t.Run("with missing verification certificate", func(t *testing.T) { path := "../test/data/github_provenance_demo-0.0.12-py3-none-any-bundle-missing-cert.jsonl" _, err := GetLocalAttestations(path) require.ErrorIs(t, err, bundle.ErrMissingBundleContent) }) } func TestFilterAttestations(t *testing.T) { attestations := []*api.Attestation{ { Bundle: &bundle.Bundle{ Bundle: &protobundle.Bundle{ Content: &protobundle.Bundle_DsseEnvelope{ DsseEnvelope: &dsse.Envelope{ PayloadType: "application/vnd.in-toto+json", Payload: []byte("{\"predicateType\": \"https://slsa.dev/provenance/v1\"}"), }, }, }, }, }, { Bundle: &bundle.Bundle{ Bundle: &protobundle.Bundle{ Content: &protobundle.Bundle_DsseEnvelope{ DsseEnvelope: &dsse.Envelope{ PayloadType: "application/vnd.something-other-than-in-toto+json", Payload: []byte("{\"predicateType\": \"https://slsa.dev/provenance/v1\"}"), }, }, }, }, }, { Bundle: &bundle.Bundle{ Bundle: &protobundle.Bundle{ Content: &protobundle.Bundle_DsseEnvelope{ DsseEnvelope: &dsse.Envelope{ PayloadType: "application/vnd.in-toto+json", Payload: []byte("{\"predicateType\": \"https://spdx.dev/Document/v2.3\"}"), }, }, }, }, }, } filtered, err := api.FilterAttestations("https://slsa.dev/provenance/v1", attestations) require.Len(t, filtered, 1) require.NoError(t, err) filtered, err = api.FilterAttestations("NonExistentPredicate", attestations) require.Nil(t, filtered) require.Error(t, err) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/verification/tuf_test.go
pkg/cmd/attestation/verification/tuf_test.go
package verification import ( "os" "path/filepath" "testing" o "github.com/cli/cli/v2/pkg/option" "github.com/cli/go-gh/v2/pkg/config" "github.com/stretchr/testify/require" ) func TestGitHubTUFOptionsNoMetadataDir(t *testing.T) { os.Setenv("CODESPACES", "true") opts := GitHubTUFOptions(o.None[string](), nil) require.Equal(t, GitHubTUFMirror, opts.RepositoryBaseURL) require.NotNil(t, opts.Root) require.True(t, opts.DisableLocalCache) require.Equal(t, filepath.Join(config.CacheDir(), ".sigstore", "root"), opts.CachePath) } func TestGitHubTUFOptionsWithMetadataDir(t *testing.T) { opts := GitHubTUFOptions(o.Some("anything"), nil) require.Equal(t, "anything", opts.CachePath) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/verification/extensions.go
pkg/cmd/attestation/verification/extensions.go
package verification import ( "errors" "fmt" "strings" "github.com/sigstore/sigstore-go/pkg/fulcio/certificate" ) var ( GitHubOIDCIssuer = "https://token.actions.githubusercontent.com" GitHubTenantOIDCIssuer = "https://token.actions.%s.ghe.com" ) // VerifyCertExtensions allows us to perform case insensitive comparisons of certificate extensions func VerifyCertExtensions(results []*AttestationProcessingResult, ec EnforcementCriteria) ([]*AttestationProcessingResult, error) { if len(results) == 0 { return nil, errors.New("no attestations processing results") } verified := make([]*AttestationProcessingResult, 0, len(results)) var lastErr error for _, attestation := range results { if err := verifyCertExtensions(*attestation.VerificationResult.Signature.Certificate, ec.Certificate); err != nil { lastErr = err // move onto the next attestation in the for loop if verification fails continue } // otherwise, add the result to the results slice and increment verifyCount verified = append(verified, attestation) } // if we have exited the for loop without verifying any attestations, // return the last error found if len(verified) == 0 { return nil, lastErr } return verified, nil } func verifyCertExtensions(given, expected certificate.Summary) error { if !strings.EqualFold(expected.SourceRepositoryOwnerURI, given.SourceRepositoryOwnerURI) { return fmt.Errorf("expected SourceRepositoryOwnerURI to be %s, got %s", expected.SourceRepositoryOwnerURI, given.SourceRepositoryOwnerURI) } // if repo is set, compare the SourceRepositoryURI fields if expected.SourceRepositoryURI != "" && !strings.EqualFold(expected.SourceRepositoryURI, given.SourceRepositoryURI) { return fmt.Errorf("expected SourceRepositoryURI to be %s, got %s", expected.SourceRepositoryURI, given.SourceRepositoryURI) } // compare the OIDC issuers. If not equal, return an error depending // on if there is a partial match if !strings.EqualFold(expected.Issuer, given.Issuer) { if strings.Index(given.Issuer, expected.Issuer+"/") == 0 { return fmt.Errorf("expected Issuer to be %s, got %s -- if you have a custom OIDC issuer policy for your enterprise, use the --cert-oidc-issuer flag with your expected issuer", expected.Issuer, given.Issuer) } return fmt.Errorf("expected Issuer to be %s, got %s", expected.Issuer, given.Issuer) } if expected.BuildSignerDigest != "" && !strings.EqualFold(expected.BuildSignerDigest, given.BuildSignerDigest) { return fmt.Errorf("expected BuildSignerDigest to be %s, got %s", expected.BuildSignerDigest, given.BuildSignerDigest) } if expected.SourceRepositoryDigest != "" && !strings.EqualFold(expected.SourceRepositoryDigest, given.SourceRepositoryDigest) { return fmt.Errorf("expected SourceRepositoryDigest to be %s, got %s", expected.SourceRepositoryDigest, given.SourceRepositoryDigest) } if expected.SourceRepositoryRef != "" && !strings.EqualFold(expected.SourceRepositoryRef, given.SourceRepositoryRef) { return fmt.Errorf("expected SourceRepositoryRef to be %s, got %s", expected.SourceRepositoryRef, given.SourceRepositoryRef) } return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/verification/attestation.go
pkg/cmd/attestation/verification/attestation.go
package verification import ( "bytes" "encoding/json" "errors" "fmt" "os" "path/filepath" "github.com/cli/cli/v2/pkg/cmd/attestation/api" "github.com/cli/cli/v2/pkg/cmd/attestation/artifact" "github.com/cli/cli/v2/pkg/cmd/attestation/artifact/oci" protobundle "github.com/sigstore/protobuf-specs/gen/pb-go/bundle/v1" "github.com/sigstore/sigstore-go/pkg/bundle" ) const SLSAPredicateV1 = "https://slsa.dev/provenance/v1" var ErrUnrecognisedBundleExtension = errors.New("bundle file extension not supported, must be json or jsonl") var ErrEmptyBundleFile = errors.New("provided bundle file is empty") // GetLocalAttestations returns a slice of attestations read from a local bundle file. func GetLocalAttestations(path string) ([]*api.Attestation, error) { var attestations []*api.Attestation var err error fileExt := filepath.Ext(path) if fileExt == ".json" { attestations, err = loadBundleFromJSONFile(path) } else if fileExt == ".jsonl" { attestations, err = loadBundlesFromJSONLinesFile(path) } else { return nil, ErrUnrecognisedBundleExtension } if err != nil { var pathErr *os.PathError if errors.As(err, &pathErr) { return nil, fmt.Errorf("could not load content from file path %s: %w", path, err) } else if errors.Is(err, bundle.ErrValidation) { return nil, err } return nil, fmt.Errorf("bundle content could not be parsed: %w", err) } return attestations, nil } func loadBundleFromJSONFile(path string) ([]*api.Attestation, error) { b, err := bundle.LoadJSONFromPath(path) if err != nil { return nil, err } return []*api.Attestation{{Bundle: b}}, nil } func loadBundlesFromJSONLinesFile(path string) ([]*api.Attestation, error) { fileContent, err := os.ReadFile(path) if err != nil { return nil, err } attestations := []*api.Attestation{} decoder := json.NewDecoder(bytes.NewReader(fileContent)) for decoder.More() { var b bundle.Bundle b.Bundle = new(protobundle.Bundle) if err := decoder.Decode(&b); err != nil { return nil, err } a := api.Attestation{Bundle: &b} attestations = append(attestations, &a) } if len(attestations) == 0 { return nil, ErrEmptyBundleFile } return attestations, nil } func GetOCIAttestations(client oci.Client, artifact artifact.DigestedArtifact) ([]*api.Attestation, error) { attestations, err := client.GetAttestations(artifact.NameRef(), artifact.DigestWithAlg()) if err != nil { return nil, fmt.Errorf("failed to fetch OCI attestations: %w", err) } if len(attestations) == 0 { return nil, fmt.Errorf("no attestations found in the OCI registry. Retry the command without the --bundle-from-oci flag to check GitHub for the attestation") } return attestations, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/auth/host.go
pkg/cmd/attestation/auth/host.go
package auth import ( "errors" ghauth "github.com/cli/go-gh/v2/pkg/auth" ) var ErrUnsupportedHost = errors.New("An unsupported host was detected. Note that gh attestation does not currently support GHES") func IsHostSupported(host string) error { if ghauth.IsEnterprise(host) { return ErrUnsupportedHost } return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/auth/host_test.go
pkg/cmd/attestation/auth/host_test.go
package auth import ( "testing" ghauth "github.com/cli/go-gh/v2/pkg/auth" "github.com/stretchr/testify/require" ) func TestIsHostSupported(t *testing.T) { testcases := []struct { name string expectedErr bool host string }{ { name: "Default github.com host", expectedErr: false, host: "github.com", }, { name: "Localhost", expectedErr: false, host: "github.localhost", }, { name: "No host set", expectedErr: false, host: "", }, { name: "GHE tenant host", expectedErr: false, host: "some-tenant.ghe.com", }, } for _, tc := range testcases { t.Run(tc.name, func(t *testing.T) { t.Setenv("GH_HOST", tc.host) host, _ := ghauth.DefaultHost() err := IsHostSupported(host) if tc.expectedErr { require.ErrorIs(t, err, ErrUnsupportedHost) } 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/attestation/inspect/inspect.go
pkg/cmd/attestation/inspect/inspect.go
package inspect import ( "fmt" "strconv" "strings" "time" "github.com/cli/cli/v2/internal/ghinstance" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/text" "github.com/cli/cli/v2/pkg/cmd/attestation/api" "github.com/cli/cli/v2/pkg/cmd/attestation/auth" "github.com/cli/cli/v2/pkg/cmd/attestation/io" "github.com/cli/cli/v2/pkg/cmd/attestation/verification" "github.com/cli/cli/v2/pkg/cmdutil" ghauth "github.com/cli/go-gh/v2/pkg/auth" "github.com/digitorus/timestamp" in_toto "github.com/in-toto/attestation/go/v1" "github.com/sigstore/sigstore-go/pkg/bundle" "github.com/sigstore/sigstore-go/pkg/fulcio/certificate" "github.com/sigstore/sigstore-go/pkg/verify" "github.com/MakeNowJust/heredoc" "github.com/spf13/cobra" ) func NewInspectCmd(f *cmdutil.Factory, runF func(*Options) error) *cobra.Command { opts := &Options{} inspectCmd := &cobra.Command{ Use: "inspect <path-to-sigstore-bundle>", Args: cmdutil.ExactArgs(1, "must specify bundle file path"), Hidden: true, Short: "Inspect a Sigstore bundle", Long: heredoc.Docf(` Inspect a Sigstore bundle that has been downloaded to disk. To download bundles associated with your artifact(s), see the %[1]sgh at download%[1]s command. Given a .json or .jsonl file, this command will: - Extract the bundle's statement and predicate - Provide a certificate summary, if present, and indicate whether the cert was issued by GitHub or by Sigstore's Public Good Instance (PGI) - Check the bundles' "authenticity" For our purposes, a bundle is authentic if we have the trusted materials to verify the included certificate(s), transparency log entries, and signed timestamps, and if the included signatures match the provided public key. This command cannot be used to verify a bundle. To verify a bundle, see the %[1]sgh at verify%[1]s command. By default, this command prints a condensed table. To see full results, provide the %[1]s--format=json%[1]s flag. `, "`"), Example: heredoc.Doc(` # Inspect a Sigstore bundle and print the results in table format $ gh attestation inspect <path-to-bundle> # Inspect a Sigstore bundle and print the results in JSON format $ gh attestation inspect <path-to-bundle> --format=json `), PreRunE: func(cmd *cobra.Command, args []string) error { // Create a logger for use throughout the inspect command opts.Logger = io.NewHandler(f.IOStreams) // set the bundle path opts.BundlePath = args[0] // Clean file path options opts.Clean() return nil }, RunE: func(cmd *cobra.Command, args []string) error { // handle tenancy if opts.Hostname == "" { opts.Hostname, _ = ghauth.DefaultHost() } if err := auth.IsHostSupported(opts.Hostname); err != nil { return err } hc, err := f.HttpClient() if err != nil { return err } config := verification.SigstoreConfig{ HttpClient: hc, Logger: opts.Logger, } if ghauth.IsTenancy(opts.Hostname) { hc, err := f.HttpClient() if err != nil { return err } apiClient := api.NewLiveClient(hc, opts.Hostname, opts.Logger) td, err := apiClient.GetTrustDomain() if err != nil { return fmt.Errorf("error getting trust domain, make sure you are authenticated against the host: %w", err) } _, found := ghinstance.TenantName(opts.Hostname) if !found { return fmt.Errorf("invalid hostname provided: '%s'", opts.Hostname) } config.TrustDomain = td } sgVerifier, err := verification.NewLiveSigstoreVerifier(config) if err != nil { return fmt.Errorf("failed to create Sigstore verifier: %w", err) } opts.SigstoreVerifier = sgVerifier if runF != nil { return runF(opts) } if err := runInspect(opts); err != nil { return fmt.Errorf("Failed to inspect the artifact and bundle: %w", err) } return nil }, } inspectCmd.Flags().StringVarP(&opts.Hostname, "hostname", "", "", "Configure host to use") cmdutil.AddFormatFlags(inspectCmd, &opts.exporter) return inspectCmd } type BundleInspectResult struct { InspectedBundles []BundleInspection `json:"inspectedBundles"` } type BundleInspection struct { Authentic bool `json:"authentic"` Certificate CertificateInspection `json:"certificate"` TransparencyLogEntries []TlogEntryInspection `json:"transparencyLogEntries"` SignedTimestamps []time.Time `json:"signedTimestamps"` Statement *in_toto.Statement `json:"statement"` } type CertificateInspection struct { certificate.Summary NotBefore time.Time `json:"notBefore"` NotAfter time.Time `json:"notAfter"` } type TlogEntryInspection struct { IntegratedTime time.Time LogID string } func runInspect(opts *Options) error { attestations, err := verification.GetLocalAttestations(opts.BundlePath) if err != nil { return fmt.Errorf("failed to read attestations") } inspectedBundles := []BundleInspection{} unsafeSigstorePolicy := verify.NewPolicy(verify.WithoutArtifactUnsafe(), verify.WithoutIdentitiesUnsafe()) for _, a := range attestations { inspectedBundle := BundleInspection{} // we ditch the verificationResult to avoid even implying that it is "verified" // you can't meaningfully "verify" a bundle with such an Unsafe policy! _, err := opts.SigstoreVerifier.Verify([]*api.Attestation{a}, unsafeSigstorePolicy) // food for thought for later iterations: // if the err is present, we keep on going because we want to be able to // inspect bundles we might not have trusted materials for. // but maybe we should print the error? if err == nil { inspectedBundle.Authentic = true } entity := a.Bundle verificationContent, err := entity.VerificationContent() if err != nil { return fmt.Errorf("failed to fetch verification content: %w", err) } // summarize cert if present if leafCert := verificationContent.Certificate(); leafCert != nil { certSummary, err := certificate.SummarizeCertificate(leafCert) if err != nil { return fmt.Errorf("failed to summarize certificate: %w", err) } inspectedBundle.Certificate = CertificateInspection{ Summary: certSummary, NotBefore: leafCert.NotBefore, NotAfter: leafCert.NotAfter, } } // parse the sig content and pop the statement sigContent, err := entity.SignatureContent() if err != nil { return fmt.Errorf("failed to fetch signature content: %w", err) } if envelope := sigContent.EnvelopeContent(); envelope != nil { stmt, err := envelope.Statement() if err != nil { return fmt.Errorf("failed to fetch envelope statement: %w", err) } inspectedBundle.Statement = stmt } // fetch the observer timestamps tlogTimestamps, err := dumpTlogs(entity) if err != nil { return fmt.Errorf("failed to dump tlog: %w", err) } inspectedBundle.TransparencyLogEntries = tlogTimestamps signedTimestamps, err := dumpSignedTimestamps(entity) if err != nil { return fmt.Errorf("failed to dump tsa: %w", err) } inspectedBundle.SignedTimestamps = signedTimestamps inspectedBundles = append(inspectedBundles, inspectedBundle) } inspectionResult := BundleInspectResult{InspectedBundles: inspectedBundles} // If the user provides the --format=json flag, print the results in JSON format if opts.exporter != nil { if err = opts.exporter.Write(opts.Logger.IO, inspectionResult); err != nil { return fmt.Errorf("failed to write JSON output") } return nil } printInspectionSummary(opts.Logger, inspectionResult.InspectedBundles) return nil } func printInspectionSummary(logger *io.Handler, bundles []BundleInspection) { logger.Printf("Inspecting bundles…\n") logger.Printf("Found %s:\n---\n", text.Pluralize(len(bundles), "attestation")) bundleSummaries := make([][][]string, len(bundles)) for i, iB := range bundles { bundleSummaries[i] = [][]string{ {"Authentic", formatAuthentic(iB.Authentic, iB.Certificate.CertificateIssuer)}, {"Source Repo", formatNwo(iB.Certificate.SourceRepositoryURI)}, {"PredicateType", iB.Statement.GetPredicateType()}, {"SubjectAlternativeName", iB.Certificate.SubjectAlternativeName}, {"RunInvocationURI", iB.Certificate.RunInvocationURI}, {"CertificateNotBefore", iB.Certificate.NotBefore.Format(time.RFC3339)}, } } // "SubjectAlternativeName" has 22 chars maxNameLength := 22 scheme := logger.ColorScheme for i, bundle := range bundleSummaries { for _, pair := range bundle { colName := pair[0] dots := maxNameLength - len(colName) logger.OutPrintf("%s:%s %s\n", scheme.Bold(colName), strings.Repeat(".", dots), pair[1]) } if i < len(bundleSummaries)-1 { logger.OutPrintln("---") } } } func formatNwo(longUrl string) string { repo, err := ghrepo.FromFullName(longUrl) if err != nil { return longUrl } return ghrepo.FullName(repo) } func formatAuthentic(authentic bool, certIssuer string) string { if strings.HasSuffix(certIssuer, "O=GitHub\\, Inc.") { certIssuer = "(GitHub)" } else if strings.HasSuffix(certIssuer, "O=sigstore.dev") { certIssuer = "(Sigstore PGI)" } else { certIssuer = "(Unknown)" } return strconv.FormatBool(authentic) + " " + certIssuer } func dumpTlogs(entity *bundle.Bundle) ([]TlogEntryInspection, error) { inspectedTlogEntries := []TlogEntryInspection{} entries, err := entity.TlogEntries() if err != nil { return nil, err } for _, entry := range entries { inspectedEntry := TlogEntryInspection{ IntegratedTime: entry.IntegratedTime(), LogID: entry.LogKeyID(), } inspectedTlogEntries = append(inspectedTlogEntries, inspectedEntry) } return inspectedTlogEntries, nil } func dumpSignedTimestamps(entity *bundle.Bundle) ([]time.Time, error) { timestamps := []time.Time{} signedTimestamps, err := entity.Timestamps() if err != nil { return nil, err } for _, signedTsBytes := range signedTimestamps { tsaTime, err := timestamp.ParseResponse(signedTsBytes) if err != nil { return nil, err } timestamps = append(timestamps, tsaTime.Time) } return timestamps, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/inspect/bundle_test.go
pkg/cmd/attestation/inspect/bundle_test.go
package inspect import ( "testing" "github.com/cli/cli/v2/pkg/cmd/attestation/test" "github.com/cli/cli/v2/pkg/cmd/attestation/verification" "github.com/stretchr/testify/require" ) func TestGetOrgAndRepo(t *testing.T) { t.Run("with valid source URL", func(t *testing.T) { sourceURL := "https://github.com/github/gh-attestation" org, repo, err := getOrgAndRepo("", sourceURL) require.Nil(t, err) require.Equal(t, "github", org) require.Equal(t, "gh-attestation", repo) }) t.Run("with invalid source URL", func(t *testing.T) { sourceURL := "hub.com/github/gh-attestation" org, repo, err := getOrgAndRepo("", sourceURL) require.Error(t, err) require.Zero(t, org) require.Zero(t, repo) }) t.Run("with valid source tenant URL", func(t *testing.T) { sourceURL := "https://foo.ghe.com/github/gh-attestation" org, repo, err := getOrgAndRepo("foo", sourceURL) require.Nil(t, err) require.Equal(t, "github", org) require.Equal(t, "gh-attestation", repo) }) } func TestGetAttestationDetail(t *testing.T) { bundlePath := test.NormalizeRelativePath("../test/data/sigstore-js-2.1.0-bundle.json") attestations, err := verification.GetLocalAttestations(bundlePath) require.Len(t, attestations, 1) require.NoError(t, err) attestation := attestations[0] detail, err := getAttestationDetail("", *attestation) require.NoError(t, err) require.Equal(t, "sigstore", detail.OrgName) require.Equal(t, "71096353", detail.OrgID) require.Equal(t, "sigstore-js", detail.RepositoryName) require.Equal(t, "495574555", detail.RepositoryID) require.Equal(t, "https://github.com/sigstore/sigstore-js/actions/runs/6014488666/attempts/1", detail.WorkflowID) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/inspect/inspect_test.go
pkg/cmd/attestation/inspect/inspect_test.go
package inspect import ( "encoding/json" "testing" "github.com/cli/cli/v2/pkg/cmd/attestation/artifact/oci" "github.com/cli/cli/v2/pkg/cmd/attestation/io" "github.com/cli/cli/v2/pkg/cmd/attestation/test" "github.com/cli/cli/v2/pkg/cmd/attestation/verification" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) const ( SigstoreSanValue = "https://github.com/sigstore/sigstore-js/.github/workflows/release.yml@refs/heads/main" SigstoreSanRegex = "^https://github.com/sigstore/sigstore-js/" ) var bundlePath = test.NormalizeRelativePath("../test/data/sigstore-js-2.1.0-bundle.json") func TestRunInspect(t *testing.T) { opts := Options{ BundlePath: bundlePath, Logger: io.NewTestHandler(), OCIClient: oci.MockClient{}, SigstoreVerifier: verification.NewMockSigstoreVerifier(t), } t.Run("with valid bundle and default output", func(t *testing.T) { testIO, _, out, _ := iostreams.Test() opts.Logger = io.NewHandler(testIO) require.Nil(t, runInspect(&opts)) outputStr := string(out.Bytes()[:]) assert.Regexp(t, "PredicateType:......... https://slsa.dev/provenance/v1", outputStr) }) t.Run("with missing bundle path", func(t *testing.T) { customOpts := opts customOpts.BundlePath = test.NormalizeRelativePath("../test/data/non-existent-sigstoreBundle.json") require.Error(t, runInspect(&customOpts)) }) } func TestJSONOutput(t *testing.T) { testIO, _, out, _ := iostreams.Test() opts := Options{ BundlePath: bundlePath, Logger: io.NewHandler(testIO), SigstoreVerifier: verification.NewMockSigstoreVerifier(t), exporter: cmdutil.NewJSONExporter(), } require.Nil(t, runInspect(&opts)) var target BundleInspectResult err := json.Unmarshal(out.Bytes(), &target) assert.Equal(t, "https://github.com/sigstore/sigstore-js", target.InspectedBundles[0].Certificate.SourceRepositoryURI) assert.Equal(t, "https://slsa.dev/provenance/v1", target.InspectedBundles[0].Statement.PredicateType) 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/attestation/inspect/bundle.go
pkg/cmd/attestation/inspect/bundle.go
package inspect import ( "encoding/json" "fmt" "strings" "github.com/cli/cli/v2/pkg/cmd/attestation/api" ) type workflow struct { Repository string `json:"repository"` } type externalParameters struct { Workflow workflow `json:"workflow"` } type githubInfo struct { RepositoryID string `json:"repository_id"` RepositoryOwnerId string `json:"repository_owner_id"` } type internalParameters struct { GitHub githubInfo `json:"github"` } type buildDefinition struct { ExternalParameters externalParameters `json:"externalParameters"` InternalParameters internalParameters `json:"internalParameters"` } type metadata struct { InvocationID string `json:"invocationId"` } type runDetails struct { Metadata metadata `json:"metadata"` } // Predicate captures the predicate of a given attestation type Predicate struct { BuildDefinition buildDefinition `json:"buildDefinition"` RunDetails runDetails `json:"runDetails"` } // AttestationDetail captures attestation source details // that will be returned by the inspect command type AttestationDetail struct { OrgName string `json:"orgName"` OrgID string `json:"orgId"` RepositoryName string `json:"repositoryName"` RepositoryID string `json:"repositoryId"` WorkflowID string `json:"workflowId"` } func getOrgAndRepo(tenant, repoURL string) (string, string, error) { var after string var found bool if tenant == "" { after, found = strings.CutPrefix(repoURL, "https://github.com/") if !found { return "", "", fmt.Errorf("failed to get org and repo from %s", repoURL) } } else { after, found = strings.CutPrefix(repoURL, fmt.Sprintf("https://%s.ghe.com/", tenant)) if !found { return "", "", fmt.Errorf("failed to get org and repo from %s", repoURL) } } parts := strings.Split(after, "/") return parts[0], parts[1], nil } func getAttestationDetail(tenant string, attr api.Attestation) (AttestationDetail, error) { envelope, err := attr.Bundle.Envelope() if err != nil { return AttestationDetail{}, fmt.Errorf("failed to get envelope from bundle: %v", err) } statement, err := envelope.EnvelopeContent().Statement() if err != nil { return AttestationDetail{}, fmt.Errorf("failed to get statement from envelope: %v", err) } var predicate Predicate predicateJson, err := json.Marshal(statement.Predicate) if err != nil { return AttestationDetail{}, fmt.Errorf("failed to marshal predicate: %v", err) } err = json.Unmarshal(predicateJson, &predicate) if err != nil { return AttestationDetail{}, fmt.Errorf("failed to unmarshal predicate: %v", err) } org, repo, err := getOrgAndRepo(tenant, predicate.BuildDefinition.ExternalParameters.Workflow.Repository) if err != nil { return AttestationDetail{}, fmt.Errorf("failed to parse attestation content: %v", err) } return AttestationDetail{ OrgName: org, OrgID: predicate.BuildDefinition.InternalParameters.GitHub.RepositoryOwnerId, RepositoryName: repo, RepositoryID: predicate.BuildDefinition.InternalParameters.GitHub.RepositoryID, WorkflowID: predicate.RunDetails.Metadata.InvocationID, }, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/inspect/inspect_integration_test.go
pkg/cmd/attestation/inspect/inspect_integration_test.go
//go:build integration package inspect import ( "bytes" "fmt" "net/http" "strings" "testing" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/stretchr/testify/assert" ) func TestNewInspectCmd_PrintOutputJSONFormat(t *testing.T) { testIO, _, _, _ := iostreams.Test() f := &cmdutil.Factory{ IOStreams: testIO, HttpClient: func() (*http.Client, error) { return http.DefaultClient, nil }, } t.Run("Print output in JSON format", func(t *testing.T) { var opts *Options cmd := NewInspectCmd(f, func(o *Options) error { opts = o return nil }) argv := strings.Split(fmt.Sprintf("%s --format json", bundlePath), " ") cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err := cmd.ExecuteC() assert.NoError(t, err) assert.Equal(t, bundlePath, opts.BundlePath) assert.NotNil(t, opts.Logger) assert.NotNil(t, opts.exporter) }) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/inspect/options.go
pkg/cmd/attestation/inspect/options.go
package inspect import ( "path/filepath" "github.com/cli/cli/v2/pkg/cmd/attestation/artifact/oci" "github.com/cli/cli/v2/pkg/cmd/attestation/io" "github.com/cli/cli/v2/pkg/cmd/attestation/verification" "github.com/cli/cli/v2/pkg/cmdutil" ) // Options captures the options for the inspect command type Options struct { ArtifactPath string BundlePath string DigestAlgorithm string Logger *io.Handler OCIClient oci.Client SigstoreVerifier verification.SigstoreVerifier exporter cmdutil.Exporter Hostname string Tenant string } // Clean cleans the file path option values func (opts *Options) Clean() { opts.BundlePath = filepath.Clean(opts.BundlePath) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/test/path.go
pkg/cmd/attestation/test/path.go
package test import ( "runtime" "strings" ) func NormalizeRelativePath(posixPath string) string { if runtime.GOOS == "windows" { return strings.ReplaceAll(posixPath, "/", "\\") } return posixPath }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/test/data/data.go
pkg/cmd/attestation/test/data/data.go
package data import ( _ "embed" "testing" "github.com/sigstore/sigstore-go/pkg/bundle" ) //go:embed sigstore-js-2.1.0-bundle.json var SigstoreBundleRaw []byte //go:embed github_release_bundle.json var GitHubReleaseBundleRaw []byte // SigstoreBundle returns a test sigstore-go bundle.Bundle func SigstoreBundle(t *testing.T) *bundle.Bundle { b := &bundle.Bundle{} err := b.UnmarshalJSON(SigstoreBundleRaw) if err != nil { t.Fatalf("failed to unmarshal sigstore bundle: %v", err) } return b } func GitHubReleaseBundle(t *testing.T) *bundle.Bundle { b := &bundle.Bundle{} err := b.UnmarshalJSON(GitHubReleaseBundleRaw) if err != nil { t.Fatalf("failed to unmarshal GitHub release bundle: %v", err) } return b }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/api/client.go
pkg/cmd/attestation/api/client.go
package api import ( "errors" "fmt" "io" "net/http" "strings" "time" "github.com/cenkalti/backoff/v4" "github.com/cli/cli/v2/api" ioconfig "github.com/cli/cli/v2/pkg/cmd/attestation/io" "github.com/golang/snappy" v1 "github.com/sigstore/protobuf-specs/gen/pb-go/bundle/v1" "github.com/sigstore/sigstore-go/pkg/bundle" "golang.org/x/sync/errgroup" "google.golang.org/protobuf/encoding/protojson" ) const ( DefaultLimit = 30 maxLimitForFlag = 1000 maxLimitForFetch = 100 ) // Allow injecting backoff interval in tests. var getAttestationRetryInterval = time.Millisecond * 200 // FetchParams are the parameters for fetching attestations from the GitHub API type FetchParams struct { Digest string Limit int Owner string PredicateType string Repo string Initiator string } func (p *FetchParams) Validate() error { if p.Digest == "" { return fmt.Errorf("digest must be provided") } if p.Limit <= 0 || p.Limit > maxLimitForFlag { return fmt.Errorf("limit must be greater than 0 and less than or equal to %d", maxLimitForFlag) } if p.Repo == "" && p.Owner == "" { return fmt.Errorf("owner or repo must be provided") } return nil } // githubApiClient makes REST calls to the GitHub API type githubApiClient interface { REST(hostname, method, p string, body io.Reader, data interface{}) error RESTWithNext(hostname, method, p string, body io.Reader, data interface{}) (string, error) } // httpClient makes HTTP calls to all non-GitHub API endpoints type httpClient interface { Get(url string) (*http.Response, error) } type Client interface { GetByDigest(params FetchParams) ([]*Attestation, error) GetTrustDomain() (string, error) } type LiveClient struct { githubAPI githubApiClient httpClient httpClient host string logger *ioconfig.Handler } func NewLiveClient(hc *http.Client, host string, l *ioconfig.Handler) *LiveClient { return &LiveClient{ githubAPI: api.NewClientFromHTTP(hc), host: strings.TrimSuffix(host, "/"), httpClient: hc, logger: l, } } // GetByDigest fetches the attestation by digest and either owner or repo // depending on which is provided func (c *LiveClient) GetByDigest(params FetchParams) ([]*Attestation, error) { c.logger.VerbosePrintf("Fetching attestations for artifact digest %s\n\n", params.Digest) attestations, err := c.getAttestations(params) if err != nil { return nil, err } bundles, err := c.fetchBundleFromAttestations(attestations) if err != nil { return nil, fmt.Errorf("failed to fetch bundle with URL: %w", err) } return bundles, nil } func (c *LiveClient) buildRequestURL(params FetchParams) (string, error) { if err := params.Validate(); err != nil { return "", err } var url string if params.Repo != "" { // check if Repo is set first because if Repo has been set, Owner will be set using the value of Repo. // If Repo is not set, the field will remain empty. It will not be populated using the value of Owner. url = fmt.Sprintf(GetAttestationByRepoAndSubjectDigestPath, params.Repo, params.Digest) } else { url = fmt.Sprintf(GetAttestationByOwnerAndSubjectDigestPath, params.Owner, params.Digest) } perPage := params.Limit if perPage > maxLimitForFetch { perPage = maxLimitForFetch } // ref: https://github.com/cli/go-gh/blob/d32c104a9a25c9de3d7c7b07a43ae0091441c858/example_gh_test.go#L96 url = fmt.Sprintf("%s?per_page=%d", url, perPage) if params.PredicateType != "" { url = fmt.Sprintf("%s&predicate_type=%s", url, params.PredicateType) } return url, nil } func (c *LiveClient) getAttestations(params FetchParams) ([]*Attestation, error) { url, err := c.buildRequestURL(params) if err != nil { return nil, err } var attestations []*Attestation var resp AttestationsResponse bo := backoff.NewConstantBackOff(getAttestationRetryInterval) // if no attestation or less than limit, then keep fetching for url != "" && len(attestations) < params.Limit { err := backoff.Retry(func() error { newURL, restErr := c.githubAPI.RESTWithNext(c.host, http.MethodGet, url, nil, &resp) if restErr != nil { if shouldRetry(restErr) { return restErr } return backoff.Permanent(restErr) } url = newURL // filter by the initiator type if params.Initiator != "" { filtered := make([]*Attestation, 0, len(resp.Attestations)) for _, att := range resp.Attestations { if att.Initiator == params.Initiator { filtered = append(filtered, att) } } resp.Attestations = filtered } attestations = append(attestations, resp.Attestations...) return nil }, backoff.WithMaxRetries(bo, 3)) // bail if RESTWithNext errored out if err != nil { return nil, err } } if len(attestations) == 0 { return nil, ErrNoAttestationsFound } if len(attestations) > params.Limit { return attestations[:params.Limit], nil } return attestations, nil } func (c *LiveClient) fetchBundleFromAttestations(attestations []*Attestation) ([]*Attestation, error) { fetched := make([]*Attestation, len(attestations)) g := errgroup.Group{} for i, a := range attestations { g.Go(func() error { if a.Bundle == nil && a.BundleURL == "" { return fmt.Errorf("attestation has no bundle or bundle URL") } // for now, we fall back to the bundle field if the bundle URL is empty if a.BundleURL == "" { c.logger.VerbosePrintf("Bundle URL is empty. Falling back to bundle field\n\n") fetched[i] = &Attestation{ Bundle: a.Bundle, } return nil } // otherwise fetch the bundle with the provided URL b, err := c.getBundle(a.BundleURL) if err != nil { return fmt.Errorf("failed to fetch bundle with URL: %w", err) } fetched[i] = &Attestation{ Bundle: b, } return nil }) } if err := g.Wait(); err != nil { return nil, err } return fetched, nil } func (c *LiveClient) getBundle(url string) (*bundle.Bundle, error) { c.logger.VerbosePrintf("Fetching attestation bundle with bundle URL\n\n") var sgBundle *bundle.Bundle bo := backoff.NewConstantBackOff(getAttestationRetryInterval) err := backoff.Retry(func() error { resp, err := c.httpClient.Get(url) if err != nil { return fmt.Errorf("request to fetch bundle from URL failed: %w", err) } if resp.StatusCode >= 500 && resp.StatusCode <= 599 { return fmt.Errorf("attestation bundle with URL %s returned status code %d", url, resp.StatusCode) } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { return fmt.Errorf("failed to read blob storage response body: %w", err) } var out []byte decompressed, err := snappy.Decode(out, body) if err != nil { return backoff.Permanent(fmt.Errorf("failed to decompress with snappy: %w", err)) } var pbBundle v1.Bundle if err = protojson.Unmarshal(decompressed, &pbBundle); err != nil { return backoff.Permanent(fmt.Errorf("failed to unmarshal to bundle: %w", err)) } c.logger.VerbosePrintf("Successfully fetched bundle\n\n") sgBundle, err = bundle.NewBundle(&pbBundle) if err != nil { return backoff.Permanent(fmt.Errorf("failed to create new bundle: %w", err)) } return nil }, backoff.WithMaxRetries(bo, 3)) return sgBundle, err } func shouldRetry(err error) bool { var httpError api.HTTPError if errors.As(err, &httpError) { if httpError.StatusCode >= 500 && httpError.StatusCode <= 599 { return true } } return false } // GetTrustDomain returns the current trust domain. If the default is used // the empty string is returned func (c *LiveClient) GetTrustDomain() (string, error) { return c.getTrustDomain(MetaPath) } func (c *LiveClient) getTrustDomain(url string) (string, error) { var resp MetaResponse bo := backoff.NewConstantBackOff(getAttestationRetryInterval) err := backoff.Retry(func() error { restErr := c.githubAPI.REST(c.host, http.MethodGet, url, nil, &resp) if restErr != nil { if shouldRetry(restErr) { return restErr } else { return backoff.Permanent(restErr) } } return nil }, backoff.WithMaxRetries(bo, 3)) if err != nil { return "", err } return resp.Domains.ArtifactAttestations.TrustDomain, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/api/mock_githubApiClient_test.go
pkg/cmd/attestation/api/mock_githubApiClient_test.go
package api import ( "encoding/json" "errors" "fmt" "io" "strings" cliAPI "github.com/cli/cli/v2/api" ghAPI "github.com/cli/go-gh/v2/pkg/api" "github.com/stretchr/testify/mock" ) type mockAPIClient struct { OnRESTWithNext func(hostname, method, p string, body io.Reader, data interface{}) (string, error) OnREST func(hostname, method, p string, body io.Reader, data interface{}) error } func (m mockAPIClient) RESTWithNext(hostname, method, p string, body io.Reader, data interface{}) (string, error) { return m.OnRESTWithNext(hostname, method, p, body, data) } func (m mockAPIClient) REST(hostname, method, p string, body io.Reader, data interface{}) error { return m.OnREST(hostname, method, p, body, data) } type mockDataGenerator struct { mock.Mock NumUserAttestations int NumGitHubAttestations int } func (m *mockDataGenerator) OnRESTSuccess(hostname, method, p string, body io.Reader, data interface{}) (string, error) { return m.OnRESTWithNextSuccessHelper(hostname, method, p, body, data, false) } func (m *mockDataGenerator) OnRESTSuccessWithNextPage(hostname, method, p string, body io.Reader, data interface{}) (string, error) { // if path doesn't contain after, it means first time hitting the mock server // so return the first page and return the link header in the response if !strings.Contains(p, "after") { return m.OnRESTWithNextSuccessHelper(hostname, method, p, body, data, true) } // if path contain after, it means second time hitting the mock server and will not return the link header return m.OnRESTWithNextSuccessHelper(hostname, method, p, body, data, false) } // Returns a func that just calls OnRESTSuccessWithNextPage but half the time // it returns a 500 error. func (m *mockDataGenerator) FlakyOnRESTSuccessWithNextPageHandler() func(hostname, method, p string, body io.Reader, data interface{}) (string, error) { // set up the flake counter m.On("FlakyOnRESTSuccessWithNextPage:error").Return() count := 0 return func(hostname, method, p string, body io.Reader, data interface{}) (string, error) { if count%2 == 0 { m.MethodCalled("FlakyOnRESTSuccessWithNextPage:error") count = count + 1 return "", cliAPI.HTTPError{HTTPError: &ghAPI.HTTPError{StatusCode: 500}} } else { count = count + 1 return m.OnRESTSuccessWithNextPage(hostname, method, p, body, data) } } } // always returns a 500 func (m *mockDataGenerator) OnREST500ErrorHandler() func(hostname, method, p string, body io.Reader, data interface{}) (string, error) { m.On("OnREST500Error").Return() return func(hostname, method, p string, body io.Reader, data interface{}) (string, error) { m.MethodCalled("OnREST500Error") return "", cliAPI.HTTPError{HTTPError: &ghAPI.HTTPError{StatusCode: 500}} } } func (m *mockDataGenerator) OnRESTWithNextSuccessHelper(hostname, method, p string, body io.Reader, data interface{}, hasNext bool) (string, error) { atts := make([]*Attestation, m.NumUserAttestations+m.NumGitHubAttestations) for j := 0; j < m.NumUserAttestations; j++ { att := makeTestAttestation() atts[j] = &att } for j := m.NumUserAttestations; j < m.NumUserAttestations+m.NumGitHubAttestations; j++ { att := makeTestReleaseAttestation() atts[j] = &att } resp := AttestationsResponse{ Attestations: atts, } // // Convert the attestations to JSON b, err := json.Marshal(resp) if err != nil { return "", err } err = json.Unmarshal(b, &data) if err != nil { return "", err } if hasNext { // return a link header with the next page return fmt.Sprintf("<%s&after=2>; rel=\"next\"", p), nil } return "", nil } func (m *mockDataGenerator) OnRESTWithNextNoAttestations(hostname, method, p string, body io.Reader, data interface{}) (string, error) { resp := AttestationsResponse{ Attestations: make([]*Attestation, 0), } // // Convert the attestations to JSON b, err := json.Marshal(resp) if err != nil { return "", err } err = json.Unmarshal(b, &data) if err != nil { return "", err } return "", nil } func (m *mockDataGenerator) OnRESTWithNextError(hostname, method, p string, body io.Reader, data interface{}) (string, error) { return "", errors.New("failed to get attestations") } type mockMetaGenerator struct { TrustDomain string } func (m mockMetaGenerator) OnREST(hostname, method, p string, body io.Reader, data interface{}) error { var template = ` { "domains": { "artifact_attestations": { "trust_domain": "%s" } } } ` var jsonString = fmt.Sprintf(template, m.TrustDomain) return json.Unmarshal([]byte(jsonString), &data) } func (m mockMetaGenerator) OnRESTError(hostname, method, p string, body io.Reader, data interface{}) error { return errors.New("test error") }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/api/mock_client.go
pkg/cmd/attestation/api/mock_client.go
package api import ( "fmt" "github.com/cli/cli/v2/pkg/cmd/attestation/test/data" ) func makeTestReleaseAttestation() Attestation { return Attestation{ Bundle: data.GitHubReleaseBundle(nil), BundleURL: "https://example.com", Initiator: "github", } } func makeTestAttestation() Attestation { return Attestation{ Bundle: data.SigstoreBundle(nil), BundleURL: "https://example.com", Initiator: "user", } } type MockClient struct { OnGetByDigest func(params FetchParams) ([]*Attestation, error) OnGetTrustDomain func() (string, error) } func (m MockClient) GetByDigest(params FetchParams) ([]*Attestation, error) { return m.OnGetByDigest(params) } func (m MockClient) GetTrustDomain() (string, error) { return m.OnGetTrustDomain() } func OnGetByDigestSuccess(params FetchParams) ([]*Attestation, error) { att1 := makeTestAttestation() att2 := makeTestAttestation() att3 := makeTestReleaseAttestation() attestations := []*Attestation{&att1, &att2} if params.PredicateType != "" { // "release" is a sentinel value that returns all release attestations (v0.1, v0.2, etc.) // This mimics the GitHub API behavior which handles this server-side if params.PredicateType == "release" { return []*Attestation{&att3}, nil } return FilterAttestations(params.PredicateType, attestations) } return attestations, nil } func OnGetByDigestFailure(params FetchParams) ([]*Attestation, error) { if params.Repo != "" { return nil, fmt.Errorf("failed to fetch attestations from %s", params.Repo) } return nil, fmt.Errorf("failed to fetch attestations from %s", params.Owner) } func NewTestClient() *MockClient { return &MockClient{ OnGetByDigest: OnGetByDigestSuccess, } } func NewFailTestClient() *MockClient { return &MockClient{ OnGetByDigest: OnGetByDigestFailure, } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/api/client_test.go
pkg/cmd/attestation/api/client_test.go
package api import ( "testing" "github.com/cli/cli/v2/pkg/cmd/attestation/io" "github.com/cli/cli/v2/pkg/cmd/attestation/test/data" "github.com/stretchr/testify/require" ) const ( testRepo = "github/example" testOwner = "github" testDigest = "sha256:12313213" ) func NewClientWithMockGHClient(hasNextPage bool) Client { fetcher := mockDataGenerator{ NumUserAttestations: 5, NumGitHubAttestations: 4, } l := io.NewTestHandler() httpClient := &mockHttpClient{} if hasNextPage { return &LiveClient{ githubAPI: mockAPIClient{ OnRESTWithNext: fetcher.OnRESTSuccessWithNextPage, }, httpClient: httpClient, logger: l, } } return &LiveClient{ githubAPI: mockAPIClient{ OnRESTWithNext: fetcher.OnRESTSuccess, }, httpClient: httpClient, logger: l, } } var testFetchParamsWithOwner = FetchParams{ Digest: testDigest, Limit: DefaultLimit, Owner: testOwner, PredicateType: "https://slsa.dev/provenance/v1", Initiator: "user", } var testFetchParamsWithRepo = FetchParams{ Digest: testDigest, Limit: DefaultLimit, Repo: testRepo, PredicateType: "https://slsa.dev/provenance/v1", Initiator: "user", } var testFetchParamsWithRepoWithGitHubInitiator = FetchParams{ Digest: testDigest, Limit: DefaultLimit, Repo: testRepo, Initiator: "github", } type getByTestCase struct { name string params FetchParams limit int expectedAttestations int hasNextPage bool } var getByTestCases = []getByTestCase{ { name: "get by digest with owner", params: testFetchParamsWithOwner, expectedAttestations: 5, }, { name: "get by digest with repo", params: testFetchParamsWithRepo, expectedAttestations: 5, }, { name: "get by digest with attestations greater than limit", params: testFetchParamsWithRepo, limit: 3, expectedAttestations: 3, }, { name: "get by digest with next page", params: testFetchParamsWithRepo, expectedAttestations: 10, hasNextPage: true, }, { name: "greater than limit with next page", params: testFetchParamsWithRepo, limit: 7, expectedAttestations: 7, hasNextPage: true, }, { name: "get by digest with repo and GitHub initiator", params: testFetchParamsWithRepoWithGitHubInitiator, expectedAttestations: 4, }, } func TestGetByDigest(t *testing.T) { for _, tc := range getByTestCases { t.Run(tc.name, func(t *testing.T) { c := NewClientWithMockGHClient(tc.hasNextPage) if tc.limit > 0 { tc.params.Limit = tc.limit } attestations, err := c.GetByDigest(tc.params) require.NoError(t, err) require.Equal(t, tc.expectedAttestations, len(attestations)) bundle := (attestations)[0].Bundle require.Equal(t, bundle.GetMediaType(), "application/vnd.dev.sigstore.bundle.v0.3+json") }) } } func TestGetByDigest_NoAttestationsFound(t *testing.T) { fetcher := mockDataGenerator{ NumUserAttestations: 5, } httpClient := &mockHttpClient{} c := LiveClient{ githubAPI: mockAPIClient{ OnRESTWithNext: fetcher.OnRESTWithNextNoAttestations, }, httpClient: httpClient, logger: io.NewTestHandler(), } attestations, err := c.GetByDigest(testFetchParamsWithRepo) require.Error(t, err) require.IsType(t, ErrNoAttestationsFound, err) require.Nil(t, attestations) } func TestGetByDigest_Error(t *testing.T) { fetcher := mockDataGenerator{ NumUserAttestations: 5, } c := LiveClient{ githubAPI: mockAPIClient{ OnRESTWithNext: fetcher.OnRESTWithNextError, }, logger: io.NewTestHandler(), } attestations, err := c.GetByDigest(testFetchParamsWithRepo) require.Error(t, err) require.Nil(t, attestations) } func TestFetchBundleFromAttestations_BundleURL(t *testing.T) { httpClient := &mockHttpClient{} client := LiveClient{ httpClient: httpClient, logger: io.NewTestHandler(), } att1 := makeTestAttestation() att2 := makeTestAttestation() attestations := []*Attestation{&att1, &att2} fetched, err := client.fetchBundleFromAttestations(attestations) require.NoError(t, err) require.Len(t, fetched, 2) require.NotNil(t, "application/vnd.dev.sigstore.bundle.v0.3+json", fetched[0].Bundle.GetMediaType()) httpClient.AssertNumberOfCalls(t, "OnGetSuccess", 2) } func TestFetchBundleFromAttestations_MissingBundleAndBundleURLFields(t *testing.T) { httpClient := &mockHttpClient{} client := LiveClient{ httpClient: httpClient, logger: io.NewTestHandler(), } // If both the BundleURL and Bundle fields are empty, the function should // return an error indicating that att1 := Attestation{} attestations := []*Attestation{&att1} bundles, err := client.fetchBundleFromAttestations(attestations) require.ErrorContains(t, err, "attestation has no bundle or bundle URL") require.Nil(t, bundles, 2) } func TestFetchBundleFromAttestations_FailOnTheSecondAttestation(t *testing.T) { mockHTTPClient := &failAfterNCallsHttpClient{ // the initial HTTP request will succeed, which returns a bundle for the first attestation // all following HTTP requests will fail, which means the function fails to fetch a bundle // for the second attestation and the function returns an error FailOnCallN: 2, FailOnAllSubsequentCalls: true, } c := &LiveClient{ httpClient: mockHTTPClient, logger: io.NewTestHandler(), } att1 := makeTestAttestation() att2 := makeTestAttestation() attestations := []*Attestation{&att1, &att2} bundles, err := c.fetchBundleFromAttestations(attestations) require.Error(t, err) require.Nil(t, bundles) } func TestFetchBundleFromAttestations_FailAfterRetrying(t *testing.T) { mockHTTPClient := &reqFailHttpClient{} c := &LiveClient{ httpClient: mockHTTPClient, logger: io.NewTestHandler(), } a := makeTestAttestation() attestations := []*Attestation{&a} bundle, err := c.fetchBundleFromAttestations(attestations) require.Error(t, err) require.Nil(t, bundle) mockHTTPClient.AssertNumberOfCalls(t, "OnGetReqFail", 4) } func TestFetchBundleFromAttestations_FallbackToBundleField(t *testing.T) { mockHTTPClient := &mockHttpClient{} c := &LiveClient{ httpClient: mockHTTPClient, logger: io.NewTestHandler(), } // If the bundle URL is empty, the code will fallback to the bundle field a := Attestation{Bundle: data.SigstoreBundle(t)} attestations := []*Attestation{&a} fetched, err := c.fetchBundleFromAttestations(attestations) require.NoError(t, err) require.Equal(t, "application/vnd.dev.sigstore.bundle.v0.3+json", fetched[0].Bundle.GetMediaType()) mockHTTPClient.AssertNotCalled(t, "OnGetSuccess") } // getBundle successfully fetches a bundle on the first HTTP request attempt func TestGetBundle(t *testing.T) { mockHTTPClient := &mockHttpClient{} c := &LiveClient{ httpClient: mockHTTPClient, logger: io.NewTestHandler(), } b, err := c.getBundle("https://mybundleurl.com") require.NoError(t, err) require.Equal(t, "application/vnd.dev.sigstore.bundle.v0.3+json", b.GetMediaType()) mockHTTPClient.AssertNumberOfCalls(t, "OnGetSuccess", 1) } // getBundle retries successfully when the initial HTTP request returns // a 5XX status code func TestGetBundle_SuccessfulRetry(t *testing.T) { mockHTTPClient := &failAfterNCallsHttpClient{ FailOnCallN: 1, FailOnAllSubsequentCalls: false, } c := &LiveClient{ httpClient: mockHTTPClient, logger: io.NewTestHandler(), } b, err := c.getBundle("mybundleurl") require.NoError(t, err) require.Equal(t, "application/vnd.dev.sigstore.bundle.v0.3+json", b.GetMediaType()) mockHTTPClient.AssertNumberOfCalls(t, "OnGetFailAfterNCalls", 2) } // getBundle does not retry when the function fails with a permanent backoff error condition func TestGetBundle_PermanentBackoffFail(t *testing.T) { mockHTTPClient := &invalidBundleClient{} c := &LiveClient{ httpClient: mockHTTPClient, logger: io.NewTestHandler(), } b, err := c.getBundle("mybundleurl") // var permanent *backoff.PermanentError //require.IsType(t, &backoff.PermanentError{}, err) require.Error(t, err) require.Nil(t, b) mockHTTPClient.AssertNumberOfCalls(t, "OnGetInvalidBundle", 1) } // getBundle retries when the HTTP request fails func TestGetBundle_RequestFail(t *testing.T) { mockHTTPClient := &reqFailHttpClient{} c := &LiveClient{ httpClient: mockHTTPClient, logger: io.NewTestHandler(), } b, err := c.getBundle("mybundleurl") require.Error(t, err) require.Nil(t, b) mockHTTPClient.AssertNumberOfCalls(t, "OnGetReqFail", 4) } func TestGetTrustDomain(t *testing.T) { fetcher := mockMetaGenerator{ TrustDomain: "foo", } t.Run("with returned trust domain", func(t *testing.T) { c := LiveClient{ githubAPI: mockAPIClient{ OnREST: fetcher.OnREST, }, logger: io.NewTestHandler(), } td, err := c.GetTrustDomain() require.Nil(t, err) require.Equal(t, "foo", td) }) t.Run("with error", func(t *testing.T) { c := LiveClient{ githubAPI: mockAPIClient{ OnREST: fetcher.OnRESTError, }, logger: io.NewTestHandler(), } td, err := c.GetTrustDomain() require.Equal(t, "", td) require.ErrorContains(t, err, "test error") }) } func TestGetAttestationsRetries(t *testing.T) { getAttestationRetryInterval = 0 fetcher := mockDataGenerator{ NumUserAttestations: 5, } c := &LiveClient{ githubAPI: mockAPIClient{ OnRESTWithNext: fetcher.FlakyOnRESTSuccessWithNextPageHandler(), }, httpClient: &mockHttpClient{}, logger: io.NewTestHandler(), } testFetchParamsWithRepo.Limit = 30 attestations, err := c.GetByDigest(testFetchParamsWithRepo) require.NoError(t, err) // assert the error path was executed; because this is a paged // request, it should have errored twice fetcher.AssertNumberOfCalls(t, "FlakyOnRESTSuccessWithNextPage:error", 2) // but we still successfully got the right data require.Equal(t, len(attestations), 10) bundle := (attestations)[0].Bundle require.Equal(t, bundle.GetMediaType(), "application/vnd.dev.sigstore.bundle.v0.3+json") } // test total retries func TestGetAttestationsMaxRetries(t *testing.T) { getAttestationRetryInterval = 0 fetcher := mockDataGenerator{ NumUserAttestations: 5, } c := &LiveClient{ githubAPI: mockAPIClient{ OnRESTWithNext: fetcher.OnREST500ErrorHandler(), }, logger: io.NewTestHandler(), } _, err := c.GetByDigest(testFetchParamsWithRepo) require.Error(t, err) fetcher.AssertNumberOfCalls(t, "OnREST500Error", 4) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/api/trust_domain.go
pkg/cmd/attestation/api/trust_domain.go
package api const MetaPath = "meta" type ArtifactAttestations struct { TrustDomain string `json:"trust_domain"` } type Domain struct { ArtifactAttestations ArtifactAttestations `json:"artifact_attestations"` } type MetaResponse struct { Domains Domain `json:"domains"` }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/api/attestation.go
pkg/cmd/attestation/api/attestation.go
package api import ( "encoding/json" "errors" "fmt" "github.com/sigstore/sigstore-go/pkg/bundle" ) const ( GetAttestationByRepoAndSubjectDigestPath = "repos/%s/attestations/%s" GetAttestationByOwnerAndSubjectDigestPath = "orgs/%s/attestations/%s" ) var ErrNoAttestationsFound = errors.New("no attestations found") type Attestation struct { Bundle *bundle.Bundle `json:"bundle"` BundleURL string `json:"bundle_url"` Initiator string `json:"initiator"` } type AttestationsResponse struct { Attestations []*Attestation `json:"attestations"` } type IntotoStatement struct { PredicateType string `json:"predicateType"` } func FilterAttestations(predicateType string, attestations []*Attestation) ([]*Attestation, error) { filteredAttestations := []*Attestation{} for _, each := range attestations { dsseEnvelope := each.Bundle.GetDsseEnvelope() if dsseEnvelope != nil { if dsseEnvelope.PayloadType != "application/vnd.in-toto+json" { // Don't fail just because an entry isn't intoto continue } var intotoStatement IntotoStatement if err := json.Unmarshal([]byte(dsseEnvelope.Payload), &intotoStatement); err != nil { // Don't fail just because a single entry can't be unmarshalled continue } if intotoStatement.PredicateType == predicateType { filteredAttestations = append(filteredAttestations, each) } } } if len(filteredAttestations) == 0 { return nil, fmt.Errorf("no attestations found with predicate type: %s", predicateType) } return filteredAttestations, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/api/mock_httpClient_test.go
pkg/cmd/attestation/api/mock_httpClient_test.go
package api import ( "bytes" "fmt" "io" "net/http" "sync" "github.com/cli/cli/v2/pkg/cmd/attestation/test/data" "github.com/golang/snappy" "github.com/stretchr/testify/mock" ) type mockHttpClient struct { mock.Mock } func (m *mockHttpClient) Get(url string) (*http.Response, error) { m.On("OnGetSuccess").Return() m.MethodCalled("OnGetSuccess") var compressed []byte compressed = snappy.Encode(compressed, data.SigstoreBundleRaw) return &http.Response{ StatusCode: 200, Body: io.NopCloser(bytes.NewReader(compressed)), }, nil } type invalidBundleClient struct { mock.Mock } func (m *invalidBundleClient) Get(url string) (*http.Response, error) { m.On("OnGetInvalidBundle").Return() m.MethodCalled("OnGetInvalidBundle") var compressed []byte compressed = snappy.Encode(compressed, []byte("invalid bundle bytes")) return &http.Response{ StatusCode: 200, Body: io.NopCloser(bytes.NewReader(compressed)), }, nil } type reqFailHttpClient struct { mock.Mock } func (m *reqFailHttpClient) Get(url string) (*http.Response, error) { m.On("OnGetReqFail").Return() m.MethodCalled("OnGetReqFail") return &http.Response{ StatusCode: 500, }, fmt.Errorf("failed to fetch with %s", url) } type failAfterNCallsHttpClient struct { mock.Mock mu sync.Mutex FailOnCallN int FailOnAllSubsequentCalls bool NumCalls int } func (m *failAfterNCallsHttpClient) Get(url string) (*http.Response, error) { m.mu.Lock() defer m.mu.Unlock() m.On("OnGetFailAfterNCalls").Return() m.NumCalls++ if m.NumCalls == m.FailOnCallN || (m.NumCalls > m.FailOnCallN && m.FailOnAllSubsequentCalls) { m.MethodCalled("OnGetFailAfterNCalls") return &http.Response{ StatusCode: 500, }, nil } m.MethodCalled("OnGetFailAfterNCalls") var compressed []byte compressed = snappy.Encode(compressed, data.SigstoreBundleRaw) return &http.Response{ StatusCode: 200, Body: io.NopCloser(bytes.NewReader(compressed)), }, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/artifact/file.go
pkg/cmd/attestation/artifact/file.go
package artifact import ( "fmt" "os" "github.com/cli/cli/v2/pkg/cmd/attestation/artifact/digest" ) func digestLocalFileArtifact(filename, digestAlg string) (*DigestedArtifact, error) { data, err := os.Open(filename) if err != nil { return nil, fmt.Errorf("failed to open local artifact: %v", err) } defer data.Close() digest, err := digest.CalculateDigestWithAlgorithm(data, digestAlg) if err != nil { return nil, fmt.Errorf("failed to calculate local artifact digest: %v", err) } return &DigestedArtifact{ URL: fmt.Sprintf("file://%s", filename), digest: digest, digestAlg: digestAlg, }, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/artifact/image.go
pkg/cmd/attestation/artifact/image.go
package artifact import ( "fmt" "github.com/cli/cli/v2/pkg/cmd/attestation/artifact/oci" "github.com/distribution/reference" ) func digestContainerImageArtifact(url string, client oci.Client) (*DigestedArtifact, error) { // try to parse the url as a valid registry reference named, err := reference.Parse(url) if err != nil { // cannot be parsed as a registry reference return nil, fmt.Errorf("artifact %s is not a valid registry reference: %v", url, err) } digest, nameRef, err := client.GetImageDigest(named.String()) if err != nil { return nil, err } return &DigestedArtifact{ URL: fmt.Sprintf("oci://%s", named.String()), digest: digest.Hex, digestAlg: digest.Algorithm, nameRef: nameRef, }, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/artifact/file_test.go
pkg/cmd/attestation/artifact/file_test.go
package artifact import ( "testing" "github.com/cli/cli/v2/pkg/cmd/attestation/test" "github.com/stretchr/testify/require" ) func Test_digestLocalFileArtifact_withRealZip(t *testing.T) { // Path to the test artifact artifactPath := test.NormalizeRelativePath("../../attestation/test/data/github_release_artifact.zip") // Calculate expected digest using the same algorithm as the function under test expectedDigest := "e15b593c6ab8d7725a3cc82226ef816cac6bf9c70eed383bd459295cc65f5ec3" // Call the function under test artifact, err := digestLocalFileArtifact(artifactPath, "sha256") require.NoError(t, err) require.Equal(t, "file://"+artifactPath, artifact.URL) require.Equal(t, expectedDigest, artifact.digest) require.Equal(t, "sha256", artifact.digestAlg) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/artifact/artifact_posix_test.go
pkg/cmd/attestation/artifact/artifact_posix_test.go
//go:build !windows package artifact import ( "testing" "github.com/stretchr/testify/require" ) func TestNormalizeReference(t *testing.T) { testCases := []struct { name string reference string pathSeparator rune expectedResult string expectedType artifactType expectedError bool }{ { name: "file reference without scheme", reference: "/path/to/file", pathSeparator: '/', expectedResult: "/path/to/file", expectedType: fileArtifactType, expectedError: false, }, { name: "file scheme uri with %20", reference: "file:///path/to/file%20with%20spaces", pathSeparator: '/', expectedResult: "/path/to/file with spaces", expectedType: fileArtifactType, expectedError: false, }, { name: "windows file reference without scheme", reference: `c:\path\to\file`, pathSeparator: '\\', expectedResult: `c:\path\to\file`, expectedType: fileArtifactType, expectedError: false, }, { name: "file reference with scheme", reference: "file:///path/to/file", pathSeparator: '/', expectedResult: "/path/to/file", expectedType: fileArtifactType, expectedError: false, }, { name: "windows path", reference: "file:///C:/path/to/file", pathSeparator: '\\', expectedResult: `C:\path\to\file`, expectedType: fileArtifactType, expectedError: false, }, { name: "windows path with backslashes", reference: "file:///C:\\path\\to\\file", pathSeparator: '\\', expectedResult: `C:\path\to\file`, expectedType: fileArtifactType, expectedError: false, }, { name: "oci reference", reference: "oci://example.com/repo:tag", pathSeparator: '/', expectedResult: "example.com/repo:tag", expectedType: ociArtifactType, expectedError: false, }, { name: "oci reference with digest", reference: "oci://example.com/repo@sha256:abcdef1234567890", pathSeparator: '/', expectedResult: "example.com/repo@sha256:abcdef1234567890", expectedType: ociArtifactType, expectedError: false, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { result, artifactType, err := normalizeReference(tc.reference, tc.pathSeparator) if tc.expectedError { require.Error(t, err) } else { require.NoError(t, err) require.Equal(t, tc.expectedResult, result) require.Equal(t, tc.expectedType, artifactType) } }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/artifact/image_test.go
pkg/cmd/attestation/artifact/image_test.go
package artifact import ( "fmt" "testing" "github.com/cli/cli/v2/pkg/cmd/attestation/artifact/oci" "github.com/stretchr/testify/require" ) func TestDigestContainerImageArtifact(t *testing.T) { expectedDigest := "1234567890abcdef" client := oci.MockClient{} url := "example.com/repo:tag" digestedArtifact, err := digestContainerImageArtifact(url, client) require.NoError(t, err) require.Equal(t, fmt.Sprintf("oci://%s", url), digestedArtifact.URL) require.Equal(t, expectedDigest, digestedArtifact.digest) require.Equal(t, "sha256", digestedArtifact.digestAlg) } func TestParseImageRefFailure(t *testing.T) { client := oci.ReferenceFailClient{} url := "example.com/repo:tag" _, err := digestContainerImageArtifact(url, client) require.Error(t, err) } func TestFetchImageFailure(t *testing.T) { testcase := []struct { name string client oci.Client expectedErr error }{ { name: "Fail to authorize with registry", client: oci.AuthFailClient{}, expectedErr: oci.ErrRegistryAuthz, }, { name: "Fail to fetch image due to denial", client: oci.DeniedClient{}, expectedErr: oci.ErrDenied, }, } for _, tc := range testcase { url := "example.com/repo:tag" _, err := digestContainerImageArtifact(url, tc.client) require.ErrorIs(t, err, tc.expectedErr) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/artifact/artifact_windows_test.go
pkg/cmd/attestation/artifact/artifact_windows_test.go
//go:build windows package artifact import ( "testing" "github.com/stretchr/testify/require" ) func TestNormalizeReference(t *testing.T) { testCases := []struct { name string reference string pathSeparator rune expectedResult string expectedType artifactType expectedError bool }{ { name: "windows file reference without scheme", reference: `c:\path\to\file`, pathSeparator: '\\', expectedResult: `c:\path\to\file`, expectedType: fileArtifactType, expectedError: false, }, { name: "windows path", reference: "file:///C:/path/to/file", pathSeparator: '\\', expectedResult: `C:\path\to\file`, expectedType: fileArtifactType, expectedError: false, }, { name: "windows path with backslashes", reference: "file:///C:\\path\\to\\file", pathSeparator: '\\', expectedResult: `C:\path\to\file`, expectedType: fileArtifactType, expectedError: false, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { result, artifactType, err := normalizeReference(tc.reference, tc.pathSeparator) if tc.expectedError { require.Error(t, err) } else { require.NoError(t, err) require.Equal(t, tc.expectedResult, result) require.Equal(t, tc.expectedType, artifactType) } }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/artifact/artifact.go
pkg/cmd/attestation/artifact/artifact.go
package artifact import ( "fmt" "net/url" "os" "path/filepath" "strings" "github.com/google/go-containerregistry/pkg/name" "github.com/cli/cli/v2/pkg/cmd/attestation/artifact/oci" ) type artifactType int const ( ociArtifactType artifactType = iota fileArtifactType ) // DigestedArtifact abstracts the software artifact being verified type DigestedArtifact struct { URL string digest string digestAlg string nameRef name.Reference } func normalizeReference(reference string, pathSeparator rune) (normalized string, artifactType artifactType, err error) { switch { case strings.HasPrefix(reference, "oci://"): return reference[6:], ociArtifactType, nil case strings.HasPrefix(reference, "file://"): uri, err := url.ParseRequestURI(reference) if err != nil { return "", 0, fmt.Errorf("failed to parse reference URI: %v", err) } var path string if pathSeparator == '/' { // Unix paths use forward slashes like URIs, so no need to modify path = uri.Path } else { // Windows paths should be normalized to use backslashes path = strings.ReplaceAll(uri.Path, "/", string(pathSeparator)) // Remove leading slash from Windows paths if present if strings.HasPrefix(path, string(pathSeparator)) { path = path[1:] } } return filepath.Clean(path), fileArtifactType, nil } // Treat any other reference as a local file path return filepath.Clean(reference), fileArtifactType, nil } func NewDigestedArtifactForRelease(digest string, digestAlg string) (artifact *DigestedArtifact) { return &DigestedArtifact{ digest: digest, digestAlg: digestAlg, } } func NewDigestedArtifact(client oci.Client, reference, digestAlg string) (artifact *DigestedArtifact, err error) { normalized, artifactType, err := normalizeReference(reference, os.PathSeparator) if err != nil { return nil, err } if artifactType == ociArtifactType { // TODO: should we allow custom digestAlg for OCI artifacts? return digestContainerImageArtifact(normalized, client) } return digestLocalFileArtifact(normalized, digestAlg) } // Digest returns the artifact's digest func (a *DigestedArtifact) Digest() string { return a.digest } // Algorithm returns the artifact's algorithm func (a *DigestedArtifact) Algorithm() string { return a.digestAlg } // DigestWithAlg returns the digest:algorithm of the artifact func (a *DigestedArtifact) DigestWithAlg() string { return fmt.Sprintf("%s:%s", a.digestAlg, a.digest) } func (a *DigestedArtifact) NameRef() name.Reference { return a.nameRef }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/artifact/digest/digest.go
pkg/cmd/attestation/artifact/digest/digest.go
package digest import ( "crypto/sha256" "crypto/sha512" "encoding/hex" "fmt" "hash" "io" ) const ( SHA256DigestAlgorithm = "sha256" SHA512DigestAlgorithm = "sha512" ) var ( errUnsupportedAlgorithm = fmt.Errorf("unsupported digest algorithm") validDigestAlgorithms = [...]string{SHA256DigestAlgorithm, SHA512DigestAlgorithm} ) // IsValidDigestAlgorithm returns true if the provided algorithm is supported func IsValidDigestAlgorithm(alg string) bool { for _, a := range validDigestAlgorithms { if a == alg { return true } } return false } // ValidDigestAlgorithms returns a list of supported digest algorithms func ValidDigestAlgorithms() []string { return validDigestAlgorithms[:] } func CalculateDigestWithAlgorithm(r io.Reader, alg string) (string, error) { var h hash.Hash switch alg { case SHA256DigestAlgorithm: h = sha256.New() case SHA512DigestAlgorithm: h = sha512.New() default: return "", errUnsupportedAlgorithm } if _, err := io.Copy(h, r); err != nil { return "", fmt.Errorf("failed to calculate digest: %v", err) } digest := h.Sum(nil) return hex.EncodeToString(digest), nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/artifact/digest/digest_test.go
pkg/cmd/attestation/artifact/digest/digest_test.go
package digest import ( "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestArtifactDigestWithAlgorithm(t *testing.T) { testString := "deadbeef" sha512TestDigest := "113a3bc783d851fc0373214b19ea7be9fa3de541ecb9fe026d52c603e8ea19c174cc0e9705f8b90d312212c0c3a6d8453ddfb3e3141409cf4bedc8ef033590b4" sha256TestDigest := "2baf1f40105d9501fe319a8ec463fdf4325a2a5df445adf3f572f626253678c9" t.Run("sha256", func(t *testing.T) { reader := strings.NewReader(testString) digest, err := CalculateDigestWithAlgorithm(reader, "sha256") assert.Nil(t, err) assert.Equal(t, sha256TestDigest, digest) }) t.Run("sha512", func(t *testing.T) { reader := strings.NewReader(testString) digest, err := CalculateDigestWithAlgorithm(reader, "sha512") assert.Nil(t, err) assert.Equal(t, sha512TestDigest, digest) }) t.Run("fail with sha384", func(t *testing.T) { reader := strings.NewReader(testString) _, err := CalculateDigestWithAlgorithm(reader, "sha384") require.Error(t, err) require.ErrorAs(t, err, &errUnsupportedAlgorithm) }) } func TestValidDigestAlgorithms(t *testing.T) { t.Run("includes sha256", func(t *testing.T) { assert.Contains(t, ValidDigestAlgorithms(), "sha256") }) t.Run("includes sha512", func(t *testing.T) { assert.Contains(t, ValidDigestAlgorithms(), "sha512") }) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/artifact/oci/client.go
pkg/cmd/attestation/artifact/oci/client.go
package oci import ( "errors" "fmt" "io" "strings" "github.com/google/go-containerregistry/pkg/authn" "github.com/google/go-containerregistry/pkg/name" "github.com/sigstore/sigstore-go/pkg/bundle" "github.com/cli/cli/v2/pkg/cmd/attestation/api" v1 "github.com/google/go-containerregistry/pkg/v1" "github.com/google/go-containerregistry/pkg/v1/remote" "github.com/google/go-containerregistry/pkg/v1/remote/transport" ) var ErrDenied = errors.New("the provided token was denied access to the requested resource, please check the token's expiration and repository access") var ErrRegistryAuthz = errors.New("remote registry authorization failed, please authenticate with the registry and try again") type Client interface { GetImageDigest(imgName string) (*v1.Hash, name.Reference, error) GetAttestations(name name.Reference, digest string) ([]*api.Attestation, error) } func checkForUnauthorizedOrDeniedErr(err transport.Error) error { for _, diagnostic := range err.Errors { switch diagnostic.Code { case transport.UnauthorizedErrorCode: return ErrRegistryAuthz case transport.DeniedErrorCode: return ErrDenied } } return nil } type LiveClient struct { parseReference func(string, ...name.Option) (name.Reference, error) get func(name.Reference, ...remote.Option) (*remote.Descriptor, error) } func (c LiveClient) ParseReference(ref string) (name.Reference, error) { return c.parseReference(ref) } // where name is formed like ghcr.io/github/my-image-repo func (c LiveClient) GetImageDigest(imgName string) (*v1.Hash, name.Reference, error) { name, err := c.parseReference(imgName) if err != nil { return nil, nil, fmt.Errorf("failed to create image tag: %v", err) } // The user must already be authenticated with the container registry // The authn.DefaultKeychain argument indicates that Get should checks the // user's configuration for the registry credentials desc, err := c.get(name, remote.WithAuthFromKeychain(authn.DefaultKeychain)) if err != nil { var transportErr *transport.Error if errors.As(err, &transportErr) { if accessErr := checkForUnauthorizedOrDeniedErr(*transportErr); accessErr != nil { return nil, nil, accessErr } } return nil, nil, fmt.Errorf("failed to fetch remote image: %v", err) } return &desc.Digest, name, nil } func (c LiveClient) GetAttestations(ref name.Reference, digest string) ([]*api.Attestation, error) { attestations := make([]*api.Attestation, 0) transportOpts := []remote.Option{remote.WithAuthFromKeychain(authn.DefaultKeychain)} referrers, err := remote.Referrers(ref.Context().Digest(digest), transportOpts...) if err != nil { return attestations, fmt.Errorf("error getting referrers: %w", err) } refManifest, err := referrers.IndexManifest() if err != nil { return attestations, fmt.Errorf("error getting referrers manifest: %w", err) } for _, refDesc := range refManifest.Manifests { if !strings.HasPrefix(refDesc.ArtifactType, "application/vnd.dev.sigstore.bundle") { continue } refImg, err := remote.Image(ref.Context().Digest(refDesc.Digest.String()), remote.WithAuthFromKeychain(authn.DefaultKeychain)) if err != nil { return attestations, fmt.Errorf("error getting referrer image: %w", err) } layers, err := refImg.Layers() if err != nil { return attestations, fmt.Errorf("error getting referrer image: %w", err) } if len(layers) > 0 { layer0, err := layers[0].Uncompressed() if err != nil { return attestations, fmt.Errorf("error getting referrer image: %w", err) } defer layer0.Close() bundleBytes, err := io.ReadAll(layer0) if err != nil { return attestations, fmt.Errorf("error getting referrer image: %w", err) } b := &bundle.Bundle{} err = b.UnmarshalJSON(bundleBytes) if err != nil { return attestations, fmt.Errorf("error unmarshalling bundle: %w", err) } a := api.Attestation{Bundle: b} attestations = append(attestations, &a) } else { return attestations, fmt.Errorf("error getting referrer image: no layers found") } } return attestations, nil } // Unlike other parts of this command set, we cannot pass a custom HTTP client // to the go-containerregistry library. This means we have limited visibility // into the HTTP requests being made to container registries. func NewLiveClient() *LiveClient { return &LiveClient{ parseReference: name.ParseReference, get: remote.Get, } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false