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/attestation/artifact/oci/mock_client.go
pkg/cmd/attestation/artifact/oci/mock_client.go
package oci import ( "fmt" "github.com/cli/cli/v2/pkg/cmd/attestation/api" "github.com/cli/cli/v2/pkg/cmd/attestation/test/data" "github.com/google/go-containerregistry/pkg/name" v1 "github.com/google/go-containerregistry/pkg/v1" ) func makeTestAttestation() api.Attestation { return api.Attestation{Bundle: data.SigstoreBundle(nil)} } type MockClient struct{} func (c MockClient) GetImageDigest(imgName string) (*v1.Hash, name.Reference, error) { return &v1.Hash{ Hex: "1234567890abcdef", Algorithm: "sha256", }, nil, nil } func (c MockClient) GetAttestations(name name.Reference, digest string) ([]*api.Attestation, error) { att1 := makeTestAttestation() att2 := makeTestAttestation() return []*api.Attestation{&att1, &att2}, nil } type ReferenceFailClient struct{} func (c ReferenceFailClient) GetImageDigest(imgName string) (*v1.Hash, name.Reference, error) { return nil, nil, fmt.Errorf("failed to parse reference") } func (c ReferenceFailClient) GetAttestations(name name.Reference, digest string) ([]*api.Attestation, error) { return nil, nil } type AuthFailClient struct{} func (c AuthFailClient) GetImageDigest(imgName string) (*v1.Hash, name.Reference, error) { return nil, nil, ErrRegistryAuthz } func (c AuthFailClient) GetAttestations(name name.Reference, digest string) ([]*api.Attestation, error) { return nil, nil } type DeniedClient struct{} func (c DeniedClient) GetImageDigest(imgName string) (*v1.Hash, name.Reference, error) { return nil, nil, ErrDenied } func (c DeniedClient) GetAttestations(name name.Reference, digest string) ([]*api.Attestation, error) { return nil, nil } type NoAttestationsClient struct{} func (c NoAttestationsClient) GetImageDigest(imgName string) (*v1.Hash, name.Reference, error) { return &v1.Hash{ Hex: "1234567890abcdef", Algorithm: "sha256", }, nil, nil } func (c NoAttestationsClient) GetAttestations(name name.Reference, digest string) ([]*api.Attestation, error) { return nil, nil } type FailedToFetchAttestationsClient struct{} func (c FailedToFetchAttestationsClient) GetImageDigest(imgName string) (*v1.Hash, name.Reference, error) { return &v1.Hash{ Hex: "1234567890abcdef", Algorithm: "sha256", }, nil, nil } func (c FailedToFetchAttestationsClient) GetAttestations(name name.Reference, digest string) ([]*api.Attestation, error) { return nil, fmt.Errorf("failed to fetch attestations") }
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_test.go
pkg/cmd/attestation/artifact/oci/client_test.go
package oci import ( "fmt" "testing" "github.com/google/go-containerregistry/pkg/name" 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" "github.com/stretchr/testify/require" ) func TestGetImageDigest_Success(t *testing.T) { expectedDigest := v1.Hash{ Hex: "1234567890abcdef", Algorithm: "sha256", } c := LiveClient{ parseReference: func(string, ...name.Option) (name.Reference, error) { return name.Tag{}, nil }, get: func(name.Reference, ...remote.Option) (*remote.Descriptor, error) { d := remote.Descriptor{} d.Digest = expectedDigest return &d, nil }, } digest, nameRef, err := c.GetImageDigest("test") require.NoError(t, err) require.Equal(t, &expectedDigest, digest) require.Equal(t, name.Tag{}, nameRef) } func TestGetImageDigest_ReferenceFail(t *testing.T) { c := LiveClient{ parseReference: func(string, ...name.Option) (name.Reference, error) { return nil, fmt.Errorf("failed to parse reference") }, get: func(name.Reference, ...remote.Option) (*remote.Descriptor, error) { return nil, nil }, } digest, nameRef, err := c.GetImageDigest("test") require.Error(t, err) require.Nil(t, digest) require.Nil(t, nameRef) } func TestGetImageDigest_AuthFail(t *testing.T) { c := LiveClient{ parseReference: func(string, ...name.Option) (name.Reference, error) { return name.Tag{}, nil }, get: func(name.Reference, ...remote.Option) (*remote.Descriptor, error) { return nil, &transport.Error{Errors: []transport.Diagnostic{{Code: transport.UnauthorizedErrorCode}}} }, } digest, nameRef, err := c.GetImageDigest("test") require.Error(t, err) require.ErrorIs(t, err, ErrRegistryAuthz) require.Nil(t, digest) require.Nil(t, nameRef) } func TestGetImageDigest_Denied(t *testing.T) { c := LiveClient{ parseReference: func(string, ...name.Option) (name.Reference, error) { return name.Tag{}, nil }, get: func(name.Reference, ...remote.Option) (*remote.Descriptor, error) { return nil, &transport.Error{Errors: []transport.Diagnostic{{Code: transport.DeniedErrorCode}}} }, } digest, nameRef, err := c.GetImageDigest("test") require.Error(t, err) require.ErrorIs(t, err, ErrDenied) require.Nil(t, digest) require.Nil(t, nameRef) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/trustedroot/trustedroot.go
pkg/cmd/attestation/trustedroot/trustedroot.go
package trustedroot import ( "bytes" "encoding/json" "fmt" "net/http" "os" "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" o "github.com/cli/cli/v2/pkg/option" ghauth "github.com/cli/go-gh/v2/pkg/auth" "github.com/MakeNowJust/heredoc" "github.com/sigstore/sigstore-go/pkg/tuf" "github.com/spf13/cobra" ) type Options struct { TufUrl string TufRootPath string VerifyOnly bool Hostname string TrustDomain string } type tufClientInstantiator func(o *tuf.Options) (*tuf.Client, error) func NewTrustedRootCmd(f *cmdutil.Factory, runF func(*Options) error) *cobra.Command { opts := &Options{} trustedRootCmd := cobra.Command{ Use: "trusted-root [--tuf-url <url> --tuf-root <file-path>] [--verify-only]", Args: cobra.ExactArgs(0), Short: "Output trusted_root.jsonl contents, likely for offline verification", Long: heredoc.Docf(` Output contents for a trusted_root.jsonl file, likely for offline verification. When using %[1]sgh attestation verify%[1]s, if your machine is on the internet, this will happen automatically. But to do offline verification, you need to supply a trusted root file with %[1]s--custom-trusted-root%[1]s; this command will help you fetch a %[1]strusted_root.jsonl%[1]s file for that purpose. You can call this command without any flags to get a trusted root file covering the Sigstore Public Good Instance as well as GitHub's Sigstore instance. Otherwise you can use %[1]s--tuf-url%[1]s to specify the URL of a custom TUF repository mirror, and %[1]s--tuf-root%[1]s should be the path to the %[1]sroot.json%[1]s file that you securely obtained out-of-band. If you just want to verify the integrity of your local TUF repository, and don't want the contents of a trusted_root.jsonl file, use %[1]s--verify-only%[1]s. `, "`"), Example: heredoc.Doc(` # Get a trusted_root.jsonl for both Sigstore Public Good and GitHub's instance $ gh attestation trusted-root `), RunE: func(cmd *cobra.Command, args []string) error { 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 } if ghauth.IsTenancy(opts.Hostname) { c, err := f.Config() if err != nil { return err } if !c.Authentication().HasActiveToken(opts.Hostname) { return fmt.Errorf("not authenticated with %s", opts.Hostname) } logger := io.NewHandler(f.IOStreams) apiClient := api.NewLiveClient(hc, opts.Hostname, logger) td, err := apiClient.GetTrustDomain() if err != nil { return err } opts.TrustDomain = td } if runF != nil { return runF(opts) } if err := getTrustedRoot(tuf.New, opts, hc); err != nil { return fmt.Errorf("Failed to verify the TUF repository: %w", err) } return nil }, } cmdutil.DisableAuthCheck(&trustedRootCmd) trustedRootCmd.Flags().StringVarP(&opts.TufUrl, "tuf-url", "", "", "URL to the TUF repository mirror") trustedRootCmd.Flags().StringVarP(&opts.TufRootPath, "tuf-root", "", "", "Path to the TUF root.json file on disk") trustedRootCmd.MarkFlagsRequiredTogether("tuf-url", "tuf-root") trustedRootCmd.Flags().BoolVarP(&opts.VerifyOnly, "verify-only", "", false, "Don't output trusted_root.jsonl contents") trustedRootCmd.Flags().StringVarP(&opts.Hostname, "hostname", "", "", "Configure host to use") return &trustedRootCmd } type tufConfig struct { tufOptions *tuf.Options targets []string } func getTrustedRoot(makeTUF tufClientInstantiator, opts *Options, hc *http.Client) error { var tufOptions []tufConfig var defaultTR = "trusted_root.json" tufOpt := verification.DefaultOptionsWithCacheSetting(o.None[string](), hc) // Disable local caching, so we get up-to-date response from TUF repository tufOpt.CacheValidity = 0 // Target will be either the default trusted root, or the trust domain-qualified one ghTR := defaultTR if opts.TrustDomain != "" { ghTR = fmt.Sprintf("%s.%s", opts.TrustDomain, defaultTR) } if opts.TufUrl != "" && opts.TufRootPath != "" { tufRoot, err := os.ReadFile(opts.TufRootPath) if err != nil { return fmt.Errorf("failed to read root file %s: %v", opts.TufRootPath, err) } tufOpt.Root = tufRoot tufOpt.RepositoryBaseURL = opts.TufUrl tufOptions = append(tufOptions, tufConfig{ tufOptions: tufOpt, targets: []string{ghTR}, }) } else { // Get from both Sigstore public good and GitHub private instance tufOptions = append(tufOptions, tufConfig{ tufOptions: tufOpt, targets: []string{defaultTR}, }) tufOpt = verification.GitHubTUFOptions(o.None[string](), hc) tufOpt.CacheValidity = 0 tufOptions = append(tufOptions, tufConfig{ tufOptions: tufOpt, targets: []string{ghTR}, }) } for _, tufOpt := range tufOptions { tufClient, err := makeTUF(tufOpt.tufOptions) if err != nil { return fmt.Errorf("failed to create TUF client: %v", err) } for _, target := range tufOpt.targets { t, err := tufClient.GetTarget(target) if err != nil { return fmt.Errorf("failed to retrieve trusted root %s via TUF: %w", target, err) } output := new(bytes.Buffer) err = json.Compact(output, t) if err != nil { return err } if !opts.VerifyOnly { fmt.Println(output) } else { fmt.Printf("Local TUF repository for %s updated and verified\n", tufOpt.tufOptions.RepositoryBaseURL) } } } return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/trustedroot/trustedroot_test.go
pkg/cmd/attestation/trustedroot/trustedroot_test.go
package trustedroot import ( "bytes" "fmt" "net/http" "strings" "testing" "github.com/sigstore/sigstore-go/pkg/tuf" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/cli/cli/v2/internal/config" "github.com/cli/cli/v2/internal/gh" ghmock "github.com/cli/cli/v2/internal/gh/mock" "github.com/cli/cli/v2/pkg/cmd/attestation/api" "github.com/cli/cli/v2/pkg/cmd/attestation/test" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" ) func TestNewTrustedRootCmd(t *testing.T) { testIO, _, _, _ := iostreams.Test() f := &cmdutil.Factory{ IOStreams: testIO, Config: func() (gh.Config, error) { return &ghmock.ConfigMock{}, nil }, HttpClient: func() (*http.Client, error) { reg := &httpmock.Registry{} client := &http.Client{} httpmock.ReplaceTripper(client, reg) return client, nil }, } testcases := []struct { name string cli string wantsErr bool }{ { name: "Happy path", cli: "", wantsErr: false, }, { name: "Happy path", cli: "--verify-only", wantsErr: false, }, { name: "Custom TUF happy path", cli: "--tuf-url https://tuf-repo.github.com --tuf-root ../verification/embed/tuf-repo.github.com/root.json", wantsErr: false, }, { name: "Missing tuf-root flag", cli: "--tuf-url https://tuf-repo.github.com", wantsErr: true, }, } for _, tc := range testcases { t.Run(tc.name, func(t *testing.T) { cmd := NewTrustedRootCmd(f, func(_ *Options) error { return nil }) argv := []string{} if tc.cli != "" { 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) }) } } func TestNewTrustedRootWithTenancy(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)) httpClientFunc := func() (*http.Client, error) { reg := &testReg client := &http.Client{} httpmock.ReplaceTripper(client, reg) return client, nil } cli := "--hostname foo-bar.ghe.com" t.Run("Host with NO auth configured", func(t *testing.T) { f := &cmdutil.Factory{ IOStreams: testIO, Config: func() (gh.Config, error) { return &ghmock.ConfigMock{ AuthenticationFunc: func() gh.AuthConfig { return &stubAuthConfig{hasActiveToken: false} }, }, nil }, HttpClient: httpClientFunc, } cmd := NewTrustedRootCmd(f, func(_ *Options) error { return nil }) argv := strings.Split(cli, " ") cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err := cmd.ExecuteC() assert.Error(t, err) assert.ErrorContains(t, err, "not authenticated") }) t.Run("Host with auth configured", func(t *testing.T) { f := &cmdutil.Factory{ IOStreams: testIO, Config: func() (gh.Config, error) { return &ghmock.ConfigMock{ AuthenticationFunc: func() gh.AuthConfig { return &stubAuthConfig{hasActiveToken: true} }, }, nil }, HttpClient: httpClientFunc, } cmd := NewTrustedRootCmd(f, func(_ *Options) error { return nil }) argv := strings.Split(cli, " ") cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err := cmd.ExecuteC() assert.NoError(t, err) }) } var newTUFErrClient tufClientInstantiator = func(o *tuf.Options) (*tuf.Client, error) { return nil, fmt.Errorf("failed to create TUF client") } func TestGetTrustedRoot(t *testing.T) { mirror := "https://tuf-repo.github.com" root := test.NormalizeRelativePath("../verification/embed/tuf-repo.github.com/root.json") opts := &Options{ TufUrl: mirror, TufRootPath: root, } reg := &httpmock.Registry{} client := &http.Client{} httpmock.ReplaceTripper(client, reg) t.Run("failed to create TUF root", func(t *testing.T) { err := getTrustedRoot(newTUFErrClient, opts, client) require.Error(t, err) require.ErrorContains(t, err, "failed to create TUF client") }) t.Run("fails because the root cannot be found", func(t *testing.T) { opts.TufRootPath = test.NormalizeRelativePath("./does/not/exist/root.json") err := getTrustedRoot(tuf.New, opts, client) require.Error(t, err) require.ErrorContains(t, err, "failed to read root file") }) } type stubAuthConfig struct { config.AuthConfig hasActiveToken bool } var _ gh.AuthConfig = (*stubAuthConfig)(nil) func (c *stubAuthConfig) HasActiveToken(host string) bool { return c.hasActiveToken }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/io/handler.go
pkg/cmd/attestation/io/handler.go
package io import ( "fmt" "strings" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/utils" ) type Handler struct { ColorScheme *iostreams.ColorScheme IO *iostreams.IOStreams debugEnabled bool } func NewHandler(io *iostreams.IOStreams) *Handler { enabled, _ := utils.IsDebugEnabled() return &Handler{ ColorScheme: io.ColorScheme(), IO: io, debugEnabled: enabled, } } func NewTestHandler() *Handler { testIO, _, _, _ := iostreams.Test() return NewHandler(testIO) } // Printf writes the formatted arguments to the stderr writer. func (h *Handler) Printf(f string, v ...interface{}) (int, error) { if !h.IO.IsStdoutTTY() { return 0, nil } return fmt.Fprintf(h.IO.ErrOut, f, v...) } func (h *Handler) OutPrintf(f string, v ...interface{}) (int, error) { return fmt.Fprintf(h.IO.Out, f, v...) } // Println writes the arguments to the stderr writer with a newline at the end. func (h *Handler) Println(v ...interface{}) (int, error) { if !h.IO.IsStdoutTTY() { return 0, nil } return fmt.Fprintln(h.IO.ErrOut, v...) } func (h *Handler) OutPrintln(v ...interface{}) (int, error) { return fmt.Fprintln(h.IO.Out, v...) } func (h *Handler) VerbosePrint(msg string) (int, error) { if !h.debugEnabled || !h.IO.IsStdoutTTY() { return 0, nil } return fmt.Fprintln(h.IO.ErrOut, msg) } func (h *Handler) VerbosePrintf(f string, v ...interface{}) (int, error) { if !h.debugEnabled || !h.IO.IsStdoutTTY() { return 0, nil } return fmt.Fprintf(h.IO.ErrOut, f, v...) } func (h *Handler) PrintBulletPoints(rows [][]string) (int, error) { if !h.IO.IsStdoutTTY() { return 0, nil } maxColLen := 0 for _, row := range rows { if len(row[0]) > maxColLen { maxColLen = len(row[0]) } } info := "" for _, row := range rows { dots := strings.Repeat(".", maxColLen-len(row[0])) info += fmt.Sprintf("%s:%s %s\n", row[0], dots, row[1]) } return fmt.Fprintln(h.IO.ErrOut, info) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/download/metadata.go
pkg/cmd/attestation/download/metadata.go
package download import ( "encoding/json" "errors" "fmt" "os" "runtime" "strings" "github.com/cli/cli/v2/pkg/cmd/attestation/api" ) var ErrAttestationFileCreation = fmt.Errorf("failed to write attestations to file") type MetadataStore interface { createMetadataFile(artifactDigest string, attestationsResp []*api.Attestation) (string, error) } type LiveStore struct { outputPath string } func (s *LiveStore) createJSONLinesFilePath(artifact string) string { if runtime.GOOS == "windows" { // Colons are special characters in Windows and cannot be used in file names. // Replace them with dashes to avoid issues. artifact = strings.ReplaceAll(artifact, ":", "-") } path := fmt.Sprintf("%s.jsonl", artifact) if s.outputPath != "" { return fmt.Sprintf("%s/%s", s.outputPath, path) } return path } func (s *LiveStore) createMetadataFile(artifactDigest string, attestationsResp []*api.Attestation) (string, error) { metadataFilePath := s.createJSONLinesFilePath(artifactDigest) f, err := os.Create(metadataFilePath) if err != nil { return "", errors.Join(ErrAttestationFileCreation, fmt.Errorf("failed to create file: %v", err)) } for _, resp := range attestationsResp { bundle := resp.Bundle attBytes, err := json.Marshal(bundle) if err != nil { if err = f.Close(); err != nil { return "", errors.Join(ErrAttestationFileCreation, fmt.Errorf("failed to close file while marshalling JSON: %v", err)) } return "", errors.Join(ErrAttestationFileCreation, fmt.Errorf("failed to marshall attestation to JSON while writing to file: %v", err)) } withNewline := fmt.Sprintf("%s\n", attBytes) _, err = f.Write([]byte(withNewline)) if err != nil { if err = f.Close(); err != nil { return "", errors.Join(ErrAttestationFileCreation, fmt.Errorf("failed to close file while handling write error: %v", err)) } return "", errors.Join(ErrAttestationFileCreation, fmt.Errorf("failed to write attestations: %v", err)) } } if err = f.Close(); err != nil { return "", errors.Join(ErrAttestationFileCreation, fmt.Errorf("failed to close file after writing attestations: %v", err)) } return metadataFilePath, nil } func NewLiveStore(outputPath string) *LiveStore { return &LiveStore{ outputPath: outputPath, } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/download/metadata_test.go
pkg/cmd/attestation/download/metadata_test.go
package download import ( "bufio" "fmt" "os" "path" "runtime" "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/stretchr/testify/require" ) type MockStore struct { OnCreateMetadataFile func(artifactDigest string, attestationsResp []*api.Attestation) (string, error) } func (s *MockStore) createMetadataFile(artifact string, attestationsResp []*api.Attestation) (string, error) { return s.OnCreateMetadataFile(artifact, attestationsResp) } func OnCreateMetadataFileFailure(artifactDigest string, attestationsResp []*api.Attestation) (string, error) { return "", fmt.Errorf("failed to create trusted metadata file") } func TestCreateJSONLinesFilePath(t *testing.T) { tempDir := t.TempDir() artifact, err := artifact.NewDigestedArtifact(oci.MockClient{}, "../test/data/sigstore-js-2.1.0.tgz", "sha512") require.NoError(t, err) var expectedFileName string if runtime.GOOS == "windows" { expectedFileName = fmt.Sprintf("%s-%s.jsonl", artifact.Algorithm(), artifact.Digest()) } else { expectedFileName = fmt.Sprintf("%s.jsonl", artifact.DigestWithAlg()) } testCases := []struct { name string outputPath string expected string }{ { name: "with output path", outputPath: tempDir, expected: path.Join(tempDir, expectedFileName), }, { name: "with nested output path", outputPath: path.Join(tempDir, "subdir"), expected: path.Join(tempDir, "subdir", expectedFileName), }, { name: "with output path with beginning slash", outputPath: path.Join("/", tempDir, "subdir"), expected: path.Join("/", tempDir, "subdir", expectedFileName), }, { name: "without output path", outputPath: "", expected: expectedFileName, }, } for _, tc := range testCases { store := LiveStore{ tc.outputPath, } actualPath := store.createJSONLinesFilePath(artifact.DigestWithAlg()) require.Equal(t, tc.expected, actualPath) } } func countLines(path string) (int, error) { f, err := os.Open(path) if err != nil { return 0, err } defer f.Close() counter := 0 scanner := bufio.NewScanner(f) for scanner.Scan() { counter += 1 } return counter, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/download/options_test.go
pkg/cmd/attestation/download/options_test.go
package download import ( "fmt" "testing" "github.com/stretchr/testify/require" ) func TestAreFlagsValid(t *testing.T) { tests := []struct { name string limit int }{ { name: "Limit is too low", limit: 0, }, { name: "Limit is too high", limit: 1001, }, } for _, tc := range tests { opts := Options{ Limit: tc.limit, } err := opts.AreFlagsValid() require.Error(t, err) expectedErrMsg := fmt.Sprintf("limit %d not allowed, must be between 1 and 1000", tc.limit) require.ErrorContains(t, err, expectedErrMsg) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/download/options.go
pkg/cmd/attestation/download/options.go
package download import ( "fmt" "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" ) const ( minLimit = 1 maxLimit = 1000 ) type Options struct { APIClient api.Client ArtifactPath string DigestAlgorithm string Logger *io.Handler Limit int Store MetadataStore OCIClient oci.Client Owner string PredicateType string Repo string Hostname string } func (opts *Options) AreFlagsValid() error { // Check that limit is between 1 and 1000 if opts.Limit < minLimit || opts.Limit > maxLimit { return fmt.Errorf("limit %d not allowed, must be between %d and %d", opts.Limit, minLimit, maxLimit) } return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/download/download_test.go
pkg/cmd/attestation/download/download_test.go
package download import ( "bytes" "fmt" "net/http" "runtime" "strings" "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/io" "github.com/cli/cli/v2/pkg/cmd/attestation/test" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) var artifactPath = test.NormalizeRelativePath("../test/data/sigstore-js-2.1.0.tgz") func expectedFilePath(tempDir string, digestWithAlg string) string { var filename string if runtime.GOOS == "windows" { filename = fmt.Sprintf("%s.jsonl", strings.ReplaceAll(digestWithAlg, ":", "-")) } else { filename = fmt.Sprintf("%s.jsonl", digestWithAlg) } return test.NormalizeRelativePath(fmt.Sprintf("%s/%s", tempDir, filename)) } func TestNewDownloadCmd(t *testing.T) { testIO, _, _, _ := iostreams.Test() f := &cmdutil.Factory{ IOStreams: testIO, HttpClient: func() (*http.Client, error) { reg := &httpmock.Registry{} client := &http.Client{} httpmock.ReplaceTripper(client, reg) return client, nil }, } store := &LiveStore{ outputPath: t.TempDir(), } testcases := []struct { name string cli string wants Options wantsErr bool }{ { name: "Invalid digest-alg flag", cli: fmt.Sprintf("%s --owner sigstore --digest-alg sha384", artifactPath), wants: Options{ ArtifactPath: artifactPath, APIClient: api.NewTestClient(), OCIClient: oci.MockClient{}, DigestAlgorithm: "sha384", Owner: "sigstore", Store: store, Limit: 30, }, wantsErr: true, }, { name: "Missing digest-alg flag", cli: fmt.Sprintf("%s --owner sigstore", artifactPath), wants: Options{ ArtifactPath: artifactPath, APIClient: api.NewTestClient(), OCIClient: oci.MockClient{}, DigestAlgorithm: "sha256", Owner: "sigstore", Store: store, Limit: 30, }, wantsErr: false, }, { name: "Missing owner and repo flags", cli: artifactPath, wants: Options{ ArtifactPath: artifactPath, APIClient: api.NewTestClient(), OCIClient: oci.MockClient{}, DigestAlgorithm: "sha256", Owner: "sigstore", Store: store, Limit: 30, }, wantsErr: true, }, { name: "Has both owner and repo flags", cli: fmt.Sprintf("%s --owner sigstore --repo sigstore/sigstore-js", artifactPath), wants: Options{ ArtifactPath: artifactPath, APIClient: api.NewTestClient(), OCIClient: oci.MockClient{}, DigestAlgorithm: "sha256", Owner: "sigstore", Store: store, Repo: "sigstore/sigstore-js", Limit: 30, }, wantsErr: true, }, { name: "Uses default limit flag", cli: fmt.Sprintf("%s --owner sigstore", artifactPath), wants: Options{ ArtifactPath: artifactPath, APIClient: api.NewTestClient(), OCIClient: oci.MockClient{}, DigestAlgorithm: "sha256", Owner: "sigstore", Store: store, Limit: 30, }, wantsErr: false, }, { name: "Uses custom limit flag", cli: fmt.Sprintf("%s --owner sigstore --limit 101", artifactPath), wants: Options{ ArtifactPath: artifactPath, APIClient: api.NewTestClient(), OCIClient: oci.MockClient{}, DigestAlgorithm: "sha256", Owner: "sigstore", Store: store, Limit: 101, }, wantsErr: false, }, { name: "Uses invalid limit flag", cli: fmt.Sprintf("%s --owner sigstore --limit 0", artifactPath), wants: Options{ ArtifactPath: artifactPath, APIClient: api.NewTestClient(), OCIClient: oci.MockClient{}, DigestAlgorithm: "sha256", Owner: "sigstore", Store: store, Limit: 0, }, wantsErr: true, }, } for _, tc := range testcases { t.Run(tc.name, func(t *testing.T) { var opts *Options cmd := NewDownloadCmd(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.DigestAlgorithm, opts.DigestAlgorithm) assert.Equal(t, tc.wants.Limit, opts.Limit) assert.Equal(t, tc.wants.Owner, opts.Owner) assert.Equal(t, tc.wants.Repo, opts.Repo) assert.NotNil(t, opts.APIClient) assert.NotNil(t, opts.OCIClient) assert.NotNil(t, opts.Logger) assert.NotNil(t, opts.Store) }) } } func TestRunDownload(t *testing.T) { tempDir := t.TempDir() store := &LiveStore{ outputPath: tempDir, } baseOpts := Options{ ArtifactPath: artifactPath, APIClient: api.NewTestClient(), OCIClient: oci.MockClient{}, DigestAlgorithm: "sha512", Owner: "sigstore", Store: store, Limit: 30, Logger: io.NewTestHandler(), } t.Run("fetch and store attestations successfully with owner", func(t *testing.T) { err := runDownload(&baseOpts) require.NoError(t, err) artifact, err := artifact.NewDigestedArtifact(baseOpts.OCIClient, baseOpts.ArtifactPath, baseOpts.DigestAlgorithm) require.NoError(t, err) expectedFilePath := expectedFilePath(tempDir, artifact.DigestWithAlg()) require.FileExists(t, expectedFilePath) actualLineCount, err := countLines(expectedFilePath) require.NoError(t, err) expectedLineCount := 2 require.Equal(t, expectedLineCount, actualLineCount) }) t.Run("fetch and store attestations successfully with repo", func(t *testing.T) { opts := baseOpts opts.Owner = "" opts.Repo = "sigstore/sigstore-js" err := runDownload(&opts) require.NoError(t, err) artifact, err := artifact.NewDigestedArtifact(opts.OCIClient, opts.ArtifactPath, opts.DigestAlgorithm) require.NoError(t, err) expectedFilePath := expectedFilePath(tempDir, artifact.DigestWithAlg()) require.FileExists(t, expectedFilePath) actualLineCount, err := countLines(expectedFilePath) require.NoError(t, err) expectedLineCount := 2 require.Equal(t, expectedLineCount, actualLineCount) }) t.Run("download OCI image attestations successfully", func(t *testing.T) { opts := baseOpts opts.ArtifactPath = "oci://ghcr.io/github/test" err := runDownload(&opts) require.NoError(t, err) artifact, err := artifact.NewDigestedArtifact(opts.OCIClient, opts.ArtifactPath, opts.DigestAlgorithm) require.NoError(t, err) expectedFilePath := expectedFilePath(tempDir, artifact.DigestWithAlg()) require.FileExists(t, expectedFilePath) actualLineCount, err := countLines(expectedFilePath) require.NoError(t, err) expectedLineCount := 2 require.Equal(t, expectedLineCount, actualLineCount) }) t.Run("cannot find artifact", func(t *testing.T) { opts := baseOpts opts.ArtifactPath = "../test/data/not-real.zip" err := runDownload(&opts) require.Error(t, err) }) t.Run("no attestations found", func(t *testing.T) { opts := baseOpts opts.APIClient = api.MockClient{ OnGetByDigest: func(params api.FetchParams) ([]*api.Attestation, error) { return nil, api.ErrNoAttestationsFound }, } err := runDownload(&opts) require.NoError(t, err) artifact, err := artifact.NewDigestedArtifact(opts.OCIClient, opts.ArtifactPath, opts.DigestAlgorithm) require.NoError(t, err) require.NoFileExists(t, artifact.DigestWithAlg()) }) t.Run("failed to fetch attestations", func(t *testing.T) { opts := baseOpts opts.APIClient = api.MockClient{ OnGetByDigest: func(params api.FetchParams) ([]*api.Attestation, error) { return nil, fmt.Errorf("failed to fetch attestations") }, } err := runDownload(&opts) require.Error(t, err) }) t.Run("cannot download OCI artifact", func(t *testing.T) { opts := baseOpts opts.ArtifactPath = "oci://ghcr.io/github/test" opts.OCIClient = oci.ReferenceFailClient{} err := runDownload(&opts) require.Error(t, err) require.ErrorContains(t, err, "failed to digest artifact") }) t.Run("with missing API client", func(t *testing.T) { customOpts := baseOpts customOpts.APIClient = nil require.Error(t, runDownload(&customOpts)) }) t.Run("fail to write attestations to metadata file", func(t *testing.T) { opts := baseOpts opts.Store = &MockStore{ OnCreateMetadataFile: OnCreateMetadataFileFailure, } err := runDownload(&opts) require.Error(t, err) require.ErrorAs(t, err, &ErrAttestationFileCreation) }) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/attestation/download/download.go
pkg/cmd/attestation/download/download.go
package download import ( "errors" "fmt" "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/cmdutil" ghauth "github.com/cli/go-gh/v2/pkg/auth" "github.com/MakeNowJust/heredoc" "github.com/spf13/cobra" ) func NewDownloadCmd(f *cmdutil.Factory, runF func(*Options) error) *cobra.Command { opts := &Options{} downloadCmd := &cobra.Command{ Use: "download [<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: "Download an artifact's attestations for offline use", Long: heredoc.Docf(` ### NOTE: This feature is currently in public preview, and subject to change. Download attestations associated with an artifact for offline use. The command requires either: * 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) In addition, the command requires either: * the %[1]s--repo%[1]s flag (e.g. --repo github/example). * the %[1]s--owner%[1]s flag (e.g. --owner github), or The %[1]s--repo%[1]s flag value must match the name of the GitHub repository that the artifact is linked with. The %[1]s--owner%[1]s flag value must match the name of the GitHub organization that the artifact's linked repository belongs to. Any associated bundle(s) will be written to a file in the current directory named after the artifact's digest. For example, if the digest is "sha256:1234", the file will be named "sha256:1234.jsonl". Colons are special characters on Windows and cannot be used in file names. To accommodate, a dash will be used to separate the algorithm from the digest in the attestations file name. For example, if the digest is "sha256:1234", the file will be named "sha256-1234.jsonl". `, "`"), Example: heredoc.Doc(` # Download attestations for a local artifact linked with an organization $ gh attestation download example.bin -o github # Download attestations for a local artifact linked with a repository $ gh attestation download example.bin -R github/example # Download attestations for an OCI image linked with an organization $ gh attestation download oci://example.com/foo/bar:latest -o github `), // 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 download command opts.Logger = io.NewHandler(f.IOStreams) // set the artifact path opts.ArtifactPath = args[0] // check that the provided flags are valid if err := opts.AreFlagsValid(); err != nil { return err } return nil }, RunE: func(cmd *cobra.Command, args []string) error { hc, err := f.HttpClient() if err != nil { return err } if opts.Hostname == "" { opts.Hostname, _ = ghauth.DefaultHost() } if err := auth.IsHostSupported(opts.Hostname); err != nil { return err } opts.APIClient = api.NewLiveClient(hc, opts.Hostname, opts.Logger) opts.OCIClient = oci.NewLiveClient() opts.Store = NewLiveStore("") if runF != nil { return runF(opts) } if err := runDownload(opts); err != nil { return fmt.Errorf("Failed to download the artifact's bundle(s): %v", err) } return nil }, } downloadCmd.Flags().StringVarP(&opts.Owner, "owner", "o", "", "GitHub organization to scope attestation lookup by") downloadCmd.Flags().StringVarP(&opts.Repo, "repo", "R", "", "Repository name in the format <owner>/<repo>") downloadCmd.MarkFlagsMutuallyExclusive("owner", "repo") downloadCmd.MarkFlagsOneRequired("owner", "repo") downloadCmd.Flags().StringVarP(&opts.PredicateType, "predicate-type", "", "", "Filter attestations by provided predicate type") cmdutil.StringEnumFlag(downloadCmd, &opts.DigestAlgorithm, "digest-alg", "d", "sha256", []string{"sha256", "sha512"}, "The algorithm used to compute a digest of the artifact") downloadCmd.Flags().IntVarP(&opts.Limit, "limit", "L", api.DefaultLimit, "Maximum number of attestations to fetch") downloadCmd.Flags().StringVarP(&opts.Hostname, "hostname", "", "", "Configure host to use") return downloadCmd } func runDownload(opts *Options) error { artifact, err := artifact.NewDigestedArtifact(opts.OCIClient, opts.ArtifactPath, opts.DigestAlgorithm) if err != nil { return fmt.Errorf("failed to digest artifact: %v", err) } opts.Logger.VerbosePrintf("Downloading trusted metadata for artifact %s\n\n", opts.ArtifactPath) if opts.APIClient == nil { return fmt.Errorf("no APIClient provided") } params := api.FetchParams{ Digest: artifact.DigestWithAlg(), Limit: opts.Limit, Owner: opts.Owner, Repo: opts.Repo, } attestations, err := opts.APIClient.GetByDigest(params) if err != nil { if errors.Is(err, api.ErrNoAttestationsFound) { fmt.Fprintf(opts.Logger.IO.Out, "No attestations found for %s\n", opts.ArtifactPath) return nil } return fmt.Errorf("failed to fetch attestations: %v", err) } // Apply predicate type filter to returned attestations if opts.PredicateType != "" { filteredAttestations, err := api.FilterAttestations(opts.PredicateType, attestations) if err != nil { return fmt.Errorf("failed to filter attestations: %v", err) } attestations = filteredAttestations } metadataFilePath, err := opts.Store.createMetadataFile(artifact.DigestWithAlg(), attestations) if err != nil { return fmt.Errorf("failed to write attestation: %v", err) } fmt.Fprintf(opts.Logger.IO.Out, "Wrote attestations to file %s.\nAny previous content has been overwritten\n\n", metadataFilePath) fmt.Fprint(opts.Logger.IO.Out, opts.Logger.ColorScheme.Greenf( "The trusted metadata is now available at %s\n", metadataFilePath, ), ) return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/workflow/workflow.go
pkg/cmd/workflow/workflow.go
package workflow import ( cmdDisable "github.com/cli/cli/v2/pkg/cmd/workflow/disable" cmdEnable "github.com/cli/cli/v2/pkg/cmd/workflow/enable" cmdList "github.com/cli/cli/v2/pkg/cmd/workflow/list" cmdRun "github.com/cli/cli/v2/pkg/cmd/workflow/run" cmdView "github.com/cli/cli/v2/pkg/cmd/workflow/view" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/spf13/cobra" ) func NewCmdWorkflow(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "workflow <command>", Short: "View details about GitHub Actions workflows", Long: "List, view, and run workflows in GitHub Actions.", GroupID: "actions", } cmdutil.EnableRepoOverride(cmd, f) cmd.AddCommand(cmdList.NewCmdList(f, nil)) cmd.AddCommand(cmdEnable.NewCmdEnable(f, nil)) cmd.AddCommand(cmdDisable.NewCmdDisable(f, nil)) cmd.AddCommand(cmdView.NewCmdView(f, nil)) cmd.AddCommand(cmdRun.NewCmdRun(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/workflow/list/list_test.go
pkg/cmd/workflow/list/list_test.go
package list import ( "bytes" "fmt" "io" "net/http" "testing" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/workflow/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" ) func TestNewCmdList(t *testing.T) { tests := []struct { name string cli string wants ListOptions wantsErr bool }{ { name: "no arguments", wants: ListOptions{ Limit: defaultLimit, }, }, { name: "all flag", cli: "--all", wants: ListOptions{ Limit: defaultLimit, All: true, }, }, { name: "limit flag", cli: "--limit 100", wants: ListOptions{ Limit: 100, }, }, { name: "invalid limit flag", cli: "--limit 0", wantsErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() f := &cmdutil.Factory{ IOStreams: ios, } argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts *ListOptions cmd := NewCmdList(f, func(opts *ListOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(io.Discard) cmd.SetErr(io.Discard) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) return } assert.NoError(t, err) assert.Equal(t, tt.wants.Limit, gotOpts.Limit) assert.Equal(t, tt.wants.All, gotOpts.All) }) } } func TestListRun(t *testing.T) { workflows := []shared.Workflow{ { Name: "Go", State: shared.Active, ID: 707, }, { Name: "Linter", State: shared.Active, ID: 666, }, { Name: "Release", State: shared.DisabledManually, ID: 451, }, } payload := shared.WorkflowsPayload{Workflows: workflows} tests := []struct { name string opts *ListOptions wantErr bool wantOut string wantErrOut string stubs func(*httpmock.Registry) tty bool }{ { name: "lists worrkflows nontty", opts: &ListOptions{ Limit: defaultLimit, }, wantOut: "Go\tactive\t707\nLinter\tactive\t666\n", }, { name: "lists workflows tty", opts: &ListOptions{ Limit: defaultLimit, }, tty: true, wantOut: "NAME STATE ID\nGo active 707\nLinter active 666\n", }, { name: "lists workflows with limit tty", opts: &ListOptions{ Limit: 1, }, tty: true, wantOut: "NAME STATE ID\nGo active 707\n", }, { name: "show all workflows tty", opts: &ListOptions{ Limit: defaultLimit, All: true, }, tty: true, wantOut: "NAME STATE ID\nGo active 707\nLinter active 666\nRelease disabled_manually 451\n", }, { name: "no results nontty", opts: &ListOptions{ Limit: defaultLimit, }, stubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(shared.WorkflowsPayload{}), ) }, wantErr: true, }, { name: "paginates workflows nontty", opts: &ListOptions{ Limit: 101, }, stubs: func(reg *httpmock.Registry) { workflows := []shared.Workflow{} var flowID int64 for flowID = 0; flowID < 103; flowID++ { workflows = append(workflows, shared.Workflow{ ID: flowID, Name: fmt.Sprintf("flow %d", flowID), State: shared.Active, }) } reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(shared.WorkflowsPayload{ Workflows: workflows[0:100], })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(shared.WorkflowsPayload{ Workflows: workflows[100:], })) }, wantOut: longOutput, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { reg := &httpmock.Registry{} defer reg.Verify(t) if tt.stubs == nil { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(payload), ) } else { tt.stubs(reg) } tt.opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } ios, _, stdout, stderr := iostreams.Test() ios.SetStdoutTTY(tt.tty) tt.opts.IO = ios tt.opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.FromFullName("OWNER/REPO") } err := listRun(tt.opts) if tt.wantErr { assert.Error(t, err) } else { assert.NoError(t, err) } assert.Equal(t, tt.wantOut, stdout.String()) assert.Equal(t, tt.wantErrOut, stderr.String()) }) } } const longOutput = "flow 0\tactive\t0\nflow 1\tactive\t1\nflow 2\tactive\t2\nflow 3\tactive\t3\nflow 4\tactive\t4\nflow 5\tactive\t5\nflow 6\tactive\t6\nflow 7\tactive\t7\nflow 8\tactive\t8\nflow 9\tactive\t9\nflow 10\tactive\t10\nflow 11\tactive\t11\nflow 12\tactive\t12\nflow 13\tactive\t13\nflow 14\tactive\t14\nflow 15\tactive\t15\nflow 16\tactive\t16\nflow 17\tactive\t17\nflow 18\tactive\t18\nflow 19\tactive\t19\nflow 20\tactive\t20\nflow 21\tactive\t21\nflow 22\tactive\t22\nflow 23\tactive\t23\nflow 24\tactive\t24\nflow 25\tactive\t25\nflow 26\tactive\t26\nflow 27\tactive\t27\nflow 28\tactive\t28\nflow 29\tactive\t29\nflow 30\tactive\t30\nflow 31\tactive\t31\nflow 32\tactive\t32\nflow 33\tactive\t33\nflow 34\tactive\t34\nflow 35\tactive\t35\nflow 36\tactive\t36\nflow 37\tactive\t37\nflow 38\tactive\t38\nflow 39\tactive\t39\nflow 40\tactive\t40\nflow 41\tactive\t41\nflow 42\tactive\t42\nflow 43\tactive\t43\nflow 44\tactive\t44\nflow 45\tactive\t45\nflow 46\tactive\t46\nflow 47\tactive\t47\nflow 48\tactive\t48\nflow 49\tactive\t49\nflow 50\tactive\t50\nflow 51\tactive\t51\nflow 52\tactive\t52\nflow 53\tactive\t53\nflow 54\tactive\t54\nflow 55\tactive\t55\nflow 56\tactive\t56\nflow 57\tactive\t57\nflow 58\tactive\t58\nflow 59\tactive\t59\nflow 60\tactive\t60\nflow 61\tactive\t61\nflow 62\tactive\t62\nflow 63\tactive\t63\nflow 64\tactive\t64\nflow 65\tactive\t65\nflow 66\tactive\t66\nflow 67\tactive\t67\nflow 68\tactive\t68\nflow 69\tactive\t69\nflow 70\tactive\t70\nflow 71\tactive\t71\nflow 72\tactive\t72\nflow 73\tactive\t73\nflow 74\tactive\t74\nflow 75\tactive\t75\nflow 76\tactive\t76\nflow 77\tactive\t77\nflow 78\tactive\t78\nflow 79\tactive\t79\nflow 80\tactive\t80\nflow 81\tactive\t81\nflow 82\tactive\t82\nflow 83\tactive\t83\nflow 84\tactive\t84\nflow 85\tactive\t85\nflow 86\tactive\t86\nflow 87\tactive\t87\nflow 88\tactive\t88\nflow 89\tactive\t89\nflow 90\tactive\t90\nflow 91\tactive\t91\nflow 92\tactive\t92\nflow 93\tactive\t93\nflow 94\tactive\t94\nflow 95\tactive\t95\nflow 96\tactive\t96\nflow 97\tactive\t97\nflow 98\tactive\t98\nflow 99\tactive\t99\nflow 100\tactive\t100\n"
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/workflow/list/list.go
pkg/cmd/workflow/list/list.go
package list import ( "fmt" "net/http" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/tableprinter" "github.com/cli/cli/v2/pkg/cmd/workflow/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) const defaultLimit = 50 type ListOptions struct { IO *iostreams.IOStreams HttpClient func() (*http.Client, error) BaseRepo func() (ghrepo.Interface, error) Exporter cmdutil.Exporter All bool Limit int } var workflowFields = []string{ "id", "name", "path", "state", } func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Command { opts := &ListOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, } cmd := &cobra.Command{ Use: "list", Short: "List workflows", Long: "List workflow files, hiding disabled workflows by default.", Aliases: []string{"ls"}, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { // support `-R, --repo` override opts.BaseRepo = f.BaseRepo if opts.Limit < 1 { return cmdutil.FlagErrorf("invalid limit: %v", opts.Limit) } if runF != nil { return runF(opts) } return listRun(opts) }, } cmd.Flags().IntVarP(&opts.Limit, "limit", "L", defaultLimit, "Maximum number of workflows to fetch") cmd.Flags().BoolVarP(&opts.All, "all", "a", false, "Include disabled workflows") cmdutil.AddJSONFlags(cmd, &opts.Exporter, workflowFields) return cmd } func listRun(opts *ListOptions) error { repo, err := opts.BaseRepo() if err != nil { return err } httpClient, err := opts.HttpClient() if err != nil { return fmt.Errorf("could not create http client: %w", err) } client := api.NewClientFromHTTP(httpClient) opts.IO.StartProgressIndicator() workflows, err := shared.GetWorkflows(client, repo, opts.Limit) opts.IO.StopProgressIndicator() if err != nil { return fmt.Errorf("could not get workflows: %w", err) } var filteredWorkflows []shared.Workflow if opts.All { filteredWorkflows = workflows } else { for _, workflow := range workflows { if !workflow.Disabled() { filteredWorkflows = append(filteredWorkflows, workflow) } } } if len(filteredWorkflows) == 0 { return cmdutil.NewNoResultsError("no workflows 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, filteredWorkflows) } cs := opts.IO.ColorScheme() tp := tableprinter.New(opts.IO, tableprinter.WithHeader("Name", "State", "ID")) for _, workflow := range filteredWorkflows { tp.AddField(workflow.Name) tp.AddField(string(workflow.State)) tp.AddField(fmt.Sprintf("%d", workflow.ID), tableprinter.WithColor(cs.Cyan)) tp.EndRow() } return tp.Render() }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/workflow/view/view.go
pkg/cmd/workflow/view/view.go
package view import ( "fmt" "net/http" "net/url" "strings" "time" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/browser" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/tableprinter" "github.com/cli/cli/v2/internal/text" runShared "github.com/cli/cli/v2/pkg/cmd/run/shared" "github.com/cli/cli/v2/pkg/cmd/workflow/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/pkg/markdown" "github.com/spf13/cobra" ) type ViewOptions struct { HttpClient func() (*http.Client, error) IO *iostreams.IOStreams BaseRepo func() (ghrepo.Interface, error) Browser browser.Browser Prompter iprompter Selector string Ref string Web bool Prompt bool Raw bool YAML bool now time.Time } type iprompter interface { Select(string, string, []string) (int, error) } func NewCmdView(f *cmdutil.Factory, runF func(*ViewOptions) error) *cobra.Command { opts := &ViewOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, Browser: f.Browser, Prompter: f.Prompter, now: time.Now(), } cmd := &cobra.Command{ Use: "view [<workflow-id> | <workflow-name> | <filename>]", Short: "View the summary of a workflow", Args: cobra.MaximumNArgs(1), Example: heredoc.Doc(` # Interactively select a workflow to view $ gh workflow view # View a specific workflow $ gh workflow view 0451 `), RunE: func(cmd *cobra.Command, args []string) error { // support `-R, --repo` override opts.BaseRepo = f.BaseRepo opts.Raw = !opts.IO.IsStdoutTTY() if len(args) > 0 { opts.Selector = args[0] } else if !opts.IO.CanPrompt() { return cmdutil.FlagErrorf("workflow argument required when not running interactively") } else { opts.Prompt = true } if !opts.YAML && opts.Ref != "" { return cmdutil.FlagErrorf("`--yaml` required when specifying `--ref`") } if runF != nil { return runF(opts) } return runView(opts) }, } cmd.Flags().BoolVarP(&opts.Web, "web", "w", false, "Open workflow in the browser") cmd.Flags().BoolVarP(&opts.YAML, "yaml", "y", false, "View the workflow yaml file") cmd.Flags().StringVarP(&opts.Ref, "ref", "r", "", "The branch or tag name which contains the version of the workflow file you'd like to view") _ = cmdutil.RegisterBranchCompletionFlags(f.GitClient, cmd, "ref") return cmd } func runView(opts *ViewOptions) error { c, err := opts.HttpClient() if err != nil { return fmt.Errorf("could not build http client: %w", err) } client := api.NewClientFromHTTP(c) repo, err := opts.BaseRepo() if err != nil { return err } var workflow *shared.Workflow states := []shared.WorkflowState{shared.Active} workflow, err = shared.ResolveWorkflow(opts.Prompter, opts.IO, client, repo, opts.Prompt, opts.Selector, states) if err != nil { return err } if opts.Web { var address string if opts.YAML { ref := opts.Ref if ref == "" { opts.IO.StartProgressIndicator() ref, err = api.RepoDefaultBranch(client, repo) opts.IO.StopProgressIndicator() if err != nil { return err } } address = ghrepo.GenerateRepoURL(repo, "blob/%s/%s", url.QueryEscape(ref), url.QueryEscape(workflow.Path)) } else { address = ghrepo.GenerateRepoURL(repo, "actions/workflows/%s", url.QueryEscape(workflow.Base())) } if opts.IO.IsStdoutTTY() { fmt.Fprintf(opts.IO.Out, "Opening %s in your browser.\n", text.DisplayURL(address)) } return opts.Browser.Browse(address) } opts.IO.DetectTerminalTheme() if err := opts.IO.StartPager(); err == nil { defer opts.IO.StopPager() } else { fmt.Fprintf(opts.IO.ErrOut, "failed to start pager: %v\n", err) } if opts.YAML { err = viewWorkflowContent(opts, client, repo, workflow, opts.Ref) } else { err = viewWorkflowInfo(opts, client, repo, workflow) } if err != nil { return err } return nil } func viewWorkflowContent(opts *ViewOptions, client *api.Client, repo ghrepo.Interface, workflow *shared.Workflow, ref string) error { yamlBytes, err := shared.GetWorkflowContent(client, repo, *workflow, ref) if err != nil { if s, ok := err.(api.HTTPError); ok && s.StatusCode == 404 { if ref != "" { return fmt.Errorf("could not find workflow file %s on %s, try specifying a different ref", workflow.Base(), ref) } return fmt.Errorf("could not find workflow file %s, try specifying a branch or tag using `--ref`", workflow.Base()) } return fmt.Errorf("could not get workflow file content: %w", err) } yaml := string(yamlBytes) if !opts.Raw { cs := opts.IO.ColorScheme() out := opts.IO.Out fileName := workflow.Base() fmt.Fprintf(out, "%s - %s\n", cs.Bold(workflow.Name), cs.Muted(fileName)) fmt.Fprintf(out, "ID: %s", cs.Cyanf("%d", workflow.ID)) codeBlock := fmt.Sprintf("```yaml\n%s\n```", yaml) rendered, err := markdown.Render(codeBlock, markdown.WithTheme(opts.IO.TerminalTheme()), markdown.WithoutIndentation(), markdown.WithWrap(0)) if err != nil { return err } _, err = fmt.Fprint(opts.IO.Out, rendered) return err } if _, err := fmt.Fprint(opts.IO.Out, yaml); err != nil { return err } if !strings.HasSuffix(yaml, "\n") { _, err := fmt.Fprint(opts.IO.Out, "\n") return err } return nil } func viewWorkflowInfo(opts *ViewOptions, client *api.Client, repo ghrepo.Interface, workflow *shared.Workflow) error { wr, err := runShared.GetRuns(client, repo, &runShared.FilterOptions{ WorkflowID: workflow.ID, WorkflowName: workflow.Name, }, 5) if err != nil { return fmt.Errorf("failed to get runs: %w", err) } out := opts.IO.Out cs := opts.IO.ColorScheme() // Header filename := workflow.Base() fmt.Fprintf(out, "%s - %s\n", cs.Bold(workflow.Name), cs.Cyan(filename)) fmt.Fprintf(out, "ID: %s\n\n", cs.Cyanf("%d", workflow.ID)) // Runs fmt.Fprintf(out, "Total runs %d\n", wr.TotalCount) if wr.TotalCount != 0 { fmt.Fprintln(out, "Recent runs") } headers := make([]string, 0, 8) if opts.Raw { headers = append(headers, "STATUS", "CONCLUSION") } else { headers = append(headers, "") } headers = append(headers, "TITLE", "WORKFLOW", "BRANCH", "EVENT") if opts.Raw { headers = append(headers, "ELAPSED") } headers = append(headers, "ID") tp := tableprinter.New(opts.IO, tableprinter.WithHeader(headers...)) for _, run := range wr.WorkflowRuns { if opts.Raw { tp.AddField(string(run.Status)) tp.AddField(string(run.Conclusion)) } else { symbol, symbolColor := runShared.Symbol(cs, run.Status, run.Conclusion) tp.AddField(symbol, tableprinter.WithColor(symbolColor)) } tp.AddField(run.Title(), tableprinter.WithColor(cs.Bold)) tp.AddField(run.WorkflowName()) tp.AddField(run.HeadBranch, tableprinter.WithColor(cs.Bold)) tp.AddField(string(run.Event)) if opts.Raw { tp.AddField(run.Duration(opts.now).String()) } tp.AddField(fmt.Sprintf("%d", run.ID), tableprinter.WithColor(cs.Cyan)) tp.EndRow() } err = tp.Render() if err != nil { return err } fmt.Fprintln(out) // Footer if wr.TotalCount != 0 { fmt.Fprintf(out, "To see more runs for this workflow, try: gh run list --workflow %s\n", filename) } fmt.Fprintf(out, "To see the YAML for this workflow, try: gh workflow view %s --yaml\n", filename) return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/workflow/view/view_test.go
pkg/cmd/workflow/view/view_test.go
package view import ( "bytes" "io" "net/http" "testing" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/browser" "github.com/cli/cli/v2/internal/ghrepo" runShared "github.com/cli/cli/v2/pkg/cmd/run/shared" "github.com/cli/cli/v2/pkg/cmd/workflow/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" ) func TestNewCmdView(t *testing.T) { tests := []struct { name string cli string tty bool wants ViewOptions wantsErr bool }{ { name: "blank tty", tty: true, wants: ViewOptions{ Prompt: true, }, }, { name: "blank nontty", wantsErr: true, }, { name: "arg tty", cli: "123", tty: true, wants: ViewOptions{ Selector: "123", }, }, { name: "arg nontty", cli: "123", wants: ViewOptions{ Selector: "123", Raw: true, }, }, { name: "web tty", cli: "--web", tty: true, wants: ViewOptions{ Prompt: true, Web: true, }, }, { name: "web nontty", cli: "-w 123", wants: ViewOptions{ Raw: true, Web: true, Selector: "123", }, }, { name: "yaml tty", cli: "--yaml", tty: true, wants: ViewOptions{ Prompt: true, YAML: true, }, }, { name: "yaml nontty", cli: "-y 123", wants: ViewOptions{ Raw: true, YAML: true, Selector: "123", }, }, { name: "ref tty", cli: "--ref 456", tty: true, wantsErr: true, }, { name: "ref nontty", cli: "123 -r 456", wantsErr: true, }, { name: "yaml ref tty", cli: "--yaml --ref 456", tty: true, wants: ViewOptions{ Prompt: true, YAML: true, Ref: "456", }, }, { name: "yaml ref nontty", cli: "123 -y -r 456", wants: ViewOptions{ Raw: true, YAML: true, Ref: "456", Selector: "123", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() ios.SetStdinTTY(tt.tty) ios.SetStdoutTTY(tt.tty) f := &cmdutil.Factory{ IOStreams: ios, } argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts *ViewOptions cmd := NewCmdView(f, func(opts *ViewOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(io.Discard) cmd.SetErr(io.Discard) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) return } assert.NoError(t, err) assert.Equal(t, tt.wants.Selector, gotOpts.Selector) assert.Equal(t, tt.wants.Ref, gotOpts.Ref) assert.Equal(t, tt.wants.Web, gotOpts.Web) assert.Equal(t, tt.wants.Prompt, gotOpts.Prompt) assert.Equal(t, tt.wants.Raw, gotOpts.Raw) assert.Equal(t, tt.wants.YAML, gotOpts.YAML) }) } } func TestViewRun(t *testing.T) { aWorkflow := shared.Workflow{ Name: "a workflow", ID: 123, Path: ".github/workflows/flow.yml", State: shared.Active, } aWorkflowContent := `{"content":"bmFtZTogYSB3b3JrZmxvdwo="}` aWorkflowInfo := heredoc.Doc(` a workflow - flow.yml ID: 123 Total runs 10 Recent runs TITLE WORKFLOW BRANCH EVENT ID X cool commit a workflow trunk push 1 * cool commit a workflow trunk push 2 ✓ cool commit a workflow trunk push 3 X cool commit a workflow trunk push 4 To see more runs for this workflow, try: gh run list --workflow flow.yml To see the YAML for this workflow, try: gh workflow view flow.yml --yaml `) tests := []struct { name string opts *ViewOptions httpStubs func(*httpmock.Registry) tty bool wantOut string wantErrOut string wantErr bool }{ { name: "no enabled workflows", tty: true, opts: &ViewOptions{ Prompt: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(shared.WorkflowsPayload{})) }, wantErrOut: "could not fetch workflows for OWNER/REPO: no workflows are enabled", wantErr: true, }, { name: "web", tty: true, opts: &ViewOptions{ Selector: "123", Web: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(aWorkflow), ) }, wantOut: "Opening https://github.com/OWNER/REPO/actions/workflows/flow.yml in your browser.\n", }, { name: "web notty", tty: false, opts: &ViewOptions{ Selector: "123", Web: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(aWorkflow), ) }, wantOut: "", }, { name: "web with yaml", tty: true, opts: &ViewOptions{ Selector: "123", YAML: true, Web: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(aWorkflow), ) reg.Register( httpmock.GraphQL(`query RepositoryInfo\b`), httpmock.StringResponse(`{ "data": { "repository": { "defaultBranchRef": { "name": "trunk" } } } }`), ) }, wantOut: "Opening https://github.com/OWNER/REPO/blob/trunk/.github/workflows/flow.yml in your browser.\n", }, { name: "web with yaml and ref", tty: true, opts: &ViewOptions{ Selector: "123", Ref: "base", YAML: true, Web: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(aWorkflow), ) }, wantOut: "Opening https://github.com/OWNER/REPO/blob/base/.github/workflows/flow.yml in your browser.\n", }, { name: "workflow with yaml", tty: true, opts: &ViewOptions{ Selector: "123", YAML: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(aWorkflow), ) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/contents/.github/workflows/flow.yml"), httpmock.StringResponse(aWorkflowContent), ) }, wantOut: "a workflow - flow.yml\nID: 123\n\nname: a workflow\n\n\n", }, { name: "workflow with yaml notty", tty: false, opts: &ViewOptions{ Selector: "123", YAML: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(aWorkflow), ) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/contents/.github/workflows/flow.yml"), httpmock.StringResponse(aWorkflowContent), ) }, wantOut: "a workflow - flow.yml\nID: 123\n\nname: a workflow\n\n\n", }, { name: "workflow with yaml not found", tty: true, opts: &ViewOptions{ Selector: "123", YAML: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(aWorkflow), ) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/contents/.github/workflows/flow.yml"), httpmock.StatusStringResponse(404, "not Found"), ) }, wantErr: true, wantErrOut: "could not find workflow file flow.yml, try specifying a branch or tag using `--ref`", }, { name: "workflow with yaml and ref", tty: true, opts: &ViewOptions{ Selector: "123", Ref: "456", YAML: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(aWorkflow), ) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/contents/.github/workflows/flow.yml"), httpmock.StringResponse(aWorkflowContent), ) }, wantOut: "a workflow - flow.yml\nID: 123\n\nname: a workflow\n\n\n", }, { name: "workflow info", tty: true, opts: &ViewOptions{ Selector: "123", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(aWorkflow), ) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123/runs"), httpmock.JSONResponse(runShared.RunsPayload{ TotalCount: 10, WorkflowRuns: runShared.TestRuns[0:4], }), ) }, wantOut: aWorkflowInfo, }, { name: "workflow info notty", tty: true, opts: &ViewOptions{ Selector: "123", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(aWorkflow), ) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123/runs"), httpmock.JSONResponse(runShared.RunsPayload{ TotalCount: 10, WorkflowRuns: runShared.TestRuns[0:4], }), ) }, wantOut: aWorkflowInfo, }, } for _, tt := range tests { reg := &httpmock.Registry{} tt.httpStubs(reg) tt.opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(tt.tty) ios.SetStdinTTY(tt.tty) tt.opts.IO = ios tt.opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.FromFullName("OWNER/REPO") } browser := &browser.Stub{} tt.opts.Browser = browser t.Run(tt.name, func(t *testing.T) { err := runView(tt.opts) if tt.wantErr { assert.Error(t, err) assert.Equal(t, tt.wantErrOut, 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/workflow/run/run_test.go
pkg/cmd/workflow/run/run_test.go
package run import ( "bytes" "encoding/base64" "encoding/json" "fmt" "io" "net/http" "os" "testing" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/pkg/cmd/workflow/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" ) func TestNewCmdRun(t *testing.T) { tests := []struct { name string cli string tty bool wants RunOptions wantsErr bool errMsg string stdin string }{ { name: "blank nontty", wantsErr: true, errMsg: "workflow ID, name, or filename required when not running interactively", }, { name: "blank tty", tty: true, wants: RunOptions{ Prompt: true, }, }, { name: "ref flag", tty: true, cli: "--ref 12345abc", wants: RunOptions{ Prompt: true, Ref: "12345abc", }, }, { name: "both STDIN and input fields", stdin: "some json", cli: "workflow.yml -fhey=there --json", errMsg: "only one of STDIN or -f/-F can be passed", wantsErr: true, }, { name: "-f args", tty: true, cli: `workflow.yml -fhey=there -fname="dana scully"`, wants: RunOptions{ Selector: "workflow.yml", RawFields: []string{"hey=there", "name=dana scully"}, }, }, { name: "-F args", tty: true, cli: `workflow.yml -Fhey=there -Fname="dana scully" -Ffile=@cool.txt`, wants: RunOptions{ Selector: "workflow.yml", MagicFields: []string{"hey=there", "name=dana scully", "file=@cool.txt"}, }, }, { name: "-F/-f arg mix", tty: true, cli: `workflow.yml -fhey=there -Fname="dana scully" -Ffile=@cool.txt`, wants: RunOptions{ Selector: "workflow.yml", RawFields: []string{"hey=there"}, MagicFields: []string{`name=dana scully`, "file=@cool.txt"}, }, }, { name: "json on STDIN", cli: "workflow.yml --json", stdin: `{"cool":"yeah"}`, wants: RunOptions{ JSON: true, JSONInput: `{"cool":"yeah"}`, Selector: "workflow.yml", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, stdin, _, _ := iostreams.Test() if tt.stdin == "" { ios.SetStdinTTY(tt.tty) } else { stdin.WriteString(tt.stdin) } ios.SetStdoutTTY(tt.tty) f := &cmdutil.Factory{ IOStreams: ios, } argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts *RunOptions cmd := NewCmdRun(f, func(opts *RunOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(io.Discard) cmd.SetErr(io.Discard) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) if tt.errMsg != "" { assert.Equal(t, tt.errMsg, err.Error()) } return } assert.NoError(t, err) assert.Equal(t, tt.wants.Selector, gotOpts.Selector) assert.Equal(t, tt.wants.Prompt, gotOpts.Prompt) assert.Equal(t, tt.wants.JSONInput, gotOpts.JSONInput) assert.Equal(t, tt.wants.JSON, gotOpts.JSON) assert.Equal(t, tt.wants.Ref, gotOpts.Ref) assert.ElementsMatch(t, tt.wants.RawFields, gotOpts.RawFields) assert.ElementsMatch(t, tt.wants.MagicFields, gotOpts.MagicFields) }) } } func Test_magicFieldValue(t *testing.T) { f, err := os.CreateTemp(t.TempDir(), "gh-test") if err != nil { t.Fatal(err) } defer f.Close() fmt.Fprint(f, "file contents") ios, _, _, _ := iostreams.Test() type args struct { v string opts RunOptions } tests := []struct { name string args args want interface{} wantErr bool }{ { name: "string", args: args{v: "hello"}, want: "hello", wantErr: false, }, { name: "file", args: args{ v: "@" + f.Name(), opts: RunOptions{IO: ios}, }, want: "file contents", wantErr: false, }, { name: "file error", args: args{ v: "@", opts: RunOptions{IO: ios}, }, want: nil, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := magicFieldValue(tt.args.v, tt.args.opts) if (err != nil) != tt.wantErr { t.Errorf("magicFieldValue() error = %v, wantErr %v", err, tt.wantErr) return } if tt.wantErr { return } assert.Equal(t, tt.want, got) }) } } func Test_findInputs(t *testing.T) { tests := []struct { name string YAML []byte wantErr bool errMsg string wantOut []WorkflowInput }{ { name: "blank", YAML: []byte{}, wantErr: true, errMsg: "invalid YAML file", }, { name: "no event specified", YAML: []byte("name: workflow"), wantErr: true, errMsg: "invalid workflow: no 'on' key", }, { name: "not workflow_dispatch", YAML: []byte("name: workflow\non: pull_request"), wantErr: true, errMsg: "unable to manually run a workflow without a workflow_dispatch event", }, { name: "bad inputs", YAML: []byte("name: workflow\non:\n workflow_dispatch:\n inputs: lol "), wantErr: true, errMsg: "could not decode workflow inputs: yaml: unmarshal errors:\n line 4: cannot unmarshal !!str `lol` into map[string]run.WorkflowInput", }, { name: "short syntax", YAML: []byte("name: workflow\non: workflow_dispatch"), wantOut: []WorkflowInput{}, }, { name: "array of events", YAML: []byte("name: workflow\non: [pull_request, workflow_dispatch]\n"), wantOut: []WorkflowInput{}, }, { name: "inputs", YAML: []byte(`name: workflow on: workflow_dispatch: inputs: foo: required: true description: good foo bar: default: boo baz: description: it's baz quux: required: true default: "cool" jobs: yell: runs-on: ubuntu-latest steps: - name: echo run: | echo "echo"`), wantOut: []WorkflowInput{ { Name: "bar", Default: "boo", }, { Name: "baz", Description: "it's baz", }, { Name: "foo", Required: true, Description: "good foo", }, { Name: "quux", Required: true, Default: "cool", }, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result, err := findInputs(tt.YAML) if tt.wantErr { assert.Error(t, err) if err != nil { assert.Equal(t, tt.errMsg, err.Error()) } return } else { assert.NoError(t, err) } assert.Equal(t, tt.wantOut, result) }) } } func TestRun(t *testing.T) { noInputsYAMLContent := []byte(` name: minimal workflow on: workflow_dispatch jobs: yell: runs-on: ubuntu-latest steps: - name: do a yell run: | echo "AUUUGH!" `) encodedNoInputsYAMLContent := base64.StdEncoding.EncodeToString(noInputsYAMLContent) yamlContent := []byte(` name: a workflow on: workflow_dispatch: inputs: greeting: default: hi description: a greeting name: required: true description: a name jobs: greet: runs-on: ubuntu-latest steps: - name: perform the greet run: | echo "${{ github.event.inputs.greeting}}, ${{ github.events.inputs.name }}!"`) encodedYAMLContent := base64.StdEncoding.EncodeToString(yamlContent) yamlContentChoiceIp := []byte(` name: choice inputs on: workflow_dispatch: inputs: name: type: choice description: Who to greet default: monalisa options: - monalisa - cschleiden favourite-animal: type: choice description: What's your favourite animal required: true options: - dog - cat jobs: greet: runs-on: ubuntu-latest steps: - name: Send greeting run: echo "${{ github.event.inputs.message }} ${{ fromJSON('["", "🥳"]')[github.event.inputs.use-emoji == 'true'] }} ${{ github.event.inputs.name }}"`) encodedYAMLContentChoiceIp := base64.StdEncoding.EncodeToString(yamlContentChoiceIp) yamlContentMissingChoiceIp := []byte(` name: choice missing inputs on: workflow_dispatch: inputs: name: type: choice description: Who to greet options: jobs: greet: runs-on: ubuntu-latest steps: - name: Send greeting run: echo "${{ github.event.inputs.message }} ${{ fromJSON('["", "🥳"]')[github.event.inputs.use-emoji == 'true'] }} ${{ github.event.inputs.name }}"`) encodedYAMLContentMissingChoiceIp := base64.StdEncoding.EncodeToString(yamlContentMissingChoiceIp) stubs := func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/workflow.yml"), httpmock.JSONResponse(shared.Workflow{ Path: ".github/workflows/workflow.yml", ID: 12345, })) reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/actions/workflows/12345/dispatches"), httpmock.StatusStringResponse(204, "cool")) } tests := []struct { name string opts *RunOptions tty bool wantErr bool errOut string wantOut string wantBody map[string]interface{} httpStubs func(*httpmock.Registry) promptStubs func(*prompter.MockPrompter) }{ { name: "bad JSON", opts: &RunOptions{ Selector: "workflow.yml", JSONInput: `{"bad":"corrupt"`, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/workflow.yml"), httpmock.JSONResponse(shared.Workflow{ Path: ".github/workflows/workflow.yml", })) }, wantErr: true, errOut: "could not parse provided JSON: unexpected end of JSON input", }, { name: "good JSON", tty: true, opts: &RunOptions{ Selector: "workflow.yml", JSONInput: `{"name":"scully"}`, }, wantBody: map[string]interface{}{ "inputs": map[string]interface{}{ "name": "scully", }, "ref": "trunk", }, httpStubs: stubs, wantOut: "✓ Created workflow_dispatch event for workflow.yml at trunk\n\nTo see runs for this workflow, try: gh run list --workflow=\"workflow.yml\"\n", }, { name: "nontty good JSON", opts: &RunOptions{ Selector: "workflow.yml", JSONInput: `{"name":"scully"}`, }, wantBody: map[string]interface{}{ "inputs": map[string]interface{}{ "name": "scully", }, "ref": "trunk", }, httpStubs: stubs, }, { name: "nontty good input fields", opts: &RunOptions{ Selector: "workflow.yml", RawFields: []string{`name=scully`}, MagicFields: []string{`greeting=hey`}, }, wantBody: map[string]interface{}{ "inputs": map[string]interface{}{ "name": "scully", "greeting": "hey", }, "ref": "trunk", }, httpStubs: stubs, }, { name: "respects ref", tty: true, opts: &RunOptions{ Selector: "workflow.yml", JSONInput: `{"name":"scully"}`, Ref: "good-branch", }, wantBody: map[string]interface{}{ "inputs": map[string]interface{}{ "name": "scully", }, "ref": "good-branch", }, httpStubs: stubs, wantOut: "✓ Created workflow_dispatch event for workflow.yml at good-branch\n\nTo see runs for this workflow, try: gh run list --workflow=\"workflow.yml\"\n", }, { // TODO this test is somewhat silly; it's more of a placeholder in case I decide to handle the API error more elegantly name: "good JSON, missing required input", tty: true, opts: &RunOptions{ Selector: "workflow.yml", JSONInput: `{"greeting":"hello there"}`, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/workflow.yml"), httpmock.JSONResponse(shared.Workflow{ Path: ".github/workflows/workflow.yml", ID: 12345, })) reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/actions/workflows/12345/dispatches"), httpmock.StatusStringResponse(422, "missing something")) }, wantErr: true, errOut: "could not create workflow dispatch event: HTTP 422 (https://api.github.com/repos/OWNER/REPO/actions/workflows/12345/dispatches)", }, { name: "yaml file extension", tty: false, opts: &RunOptions{ Selector: "workflow.yaml", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/workflow.yaml"), httpmock.StatusStringResponse(200, `{"id": 12345}`)) reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/actions/workflows/12345/dispatches"), httpmock.StatusStringResponse(204, "")) }, wantBody: map[string]interface{}{ "inputs": map[string]interface{}{}, "ref": "trunk", }, wantErr: false, }, { // TODO this test is somewhat silly; it's more of a placeholder in case I decide to handle the API error more elegantly name: "input fields, missing required", opts: &RunOptions{ Selector: "workflow.yml", RawFields: []string{`greeting="hello there"`}, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/workflow.yml"), httpmock.JSONResponse(shared.Workflow{ Path: ".github/workflows/workflow.yml", ID: 12345, })) reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/actions/workflows/12345/dispatches"), httpmock.StatusStringResponse(422, "missing something")) }, wantErr: true, errOut: "could not create workflow dispatch event: HTTP 422 (https://api.github.com/repos/OWNER/REPO/actions/workflows/12345/dispatches)", }, { name: "prompt, no workflows enabled", tty: true, opts: &RunOptions{ Prompt: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(shared.WorkflowsPayload{ Workflows: []shared.Workflow{ { Name: "disabled", State: shared.DisabledManually, ID: 102, }, }, })) }, wantErr: true, errOut: "no workflows are enabled on this repository", }, { name: "prompt, no workflows", tty: true, opts: &RunOptions{ Prompt: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(shared.WorkflowsPayload{ Workflows: []shared.Workflow{}, })) }, wantErr: true, errOut: "could not fetch workflows for OWNER/REPO: no workflows are enabled", }, { name: "prompt, minimal yaml", tty: true, opts: &RunOptions{ Prompt: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(shared.WorkflowsPayload{ Workflows: []shared.Workflow{ { Name: "minimal workflow", ID: 1, State: shared.Active, Path: ".github/workflows/minimal.yml", }, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/contents/.github/workflows/minimal.yml"), httpmock.JSONResponse(struct{ Content string }{ Content: encodedNoInputsYAMLContent, })) reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/actions/workflows/1/dispatches"), httpmock.StatusStringResponse(204, "cool")) }, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterSelect("Select a workflow", []string{"minimal workflow (minimal.yml)"}, func(_, _ string, opts []string) (int, error) { return 0, nil }) }, wantBody: map[string]interface{}{ "inputs": map[string]interface{}{}, "ref": "trunk", }, wantOut: "✓ Created workflow_dispatch event for minimal.yml at trunk\n\nTo see runs for this workflow, try: gh run list --workflow=\"minimal.yml\"\n", }, { name: "prompt", tty: true, opts: &RunOptions{ Prompt: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(shared.WorkflowsPayload{ Workflows: []shared.Workflow{ { Name: "a workflow", ID: 12345, State: shared.Active, Path: ".github/workflows/workflow.yml", }, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/contents/.github/workflows/workflow.yml"), httpmock.JSONResponse(struct{ Content string }{ Content: encodedYAMLContent, })) reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/actions/workflows/12345/dispatches"), httpmock.StatusStringResponse(204, "cool")) }, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterSelect("Select a workflow", []string{"a workflow (workflow.yml)"}, func(_, _ string, opts []string) (int, error) { return 0, nil }) pm.RegisterInput("greeting", func(_, _ string) (string, error) { return "hi", nil }) pm.RegisterInput("name (required)", func(_, _ string) (string, error) { return "scully", nil }) }, wantBody: map[string]interface{}{ "inputs": map[string]interface{}{ "name": "scully", "greeting": "hi", }, "ref": "trunk", }, wantOut: "✓ Created workflow_dispatch event for workflow.yml at trunk\n\nTo see runs for this workflow, try: gh run list --workflow=\"workflow.yml\"\n", }, { name: "prompt, workflow choice input", tty: true, opts: &RunOptions{ Prompt: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(shared.WorkflowsPayload{ Workflows: []shared.Workflow{ { Name: "choice inputs", ID: 12345, State: shared.Active, Path: ".github/workflows/workflow.yml", }, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/contents/.github/workflows/workflow.yml"), httpmock.JSONResponse(struct{ Content string }{ Content: encodedYAMLContentChoiceIp, })) reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/actions/workflows/12345/dispatches"), httpmock.StatusStringResponse(204, "cool")) }, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterSelect("Select a workflow", []string{"choice inputs (workflow.yml)"}, func(_, _ string, opts []string) (int, error) { return 0, nil }) pm.RegisterSelect("favourite-animal (required)", []string{"dog", "cat"}, func(_, _ string, opts []string) (int, error) { return 0, nil }) pm.RegisterSelect("name", []string{"monalisa", "cschleiden"}, func(_, _ string, opts []string) (int, error) { return 0, nil }) }, wantBody: map[string]interface{}{ "inputs": map[string]interface{}{ "name": "monalisa", "favourite-animal": "dog", }, "ref": "trunk", }, wantOut: "✓ Created workflow_dispatch event for workflow.yml at trunk\n\nTo see runs for this workflow, try: gh run list --workflow=\"workflow.yml\"\n", }, { name: "prompt, workflow choice missing input", tty: true, opts: &RunOptions{ Prompt: true, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(shared.WorkflowsPayload{ Workflows: []shared.Workflow{ { Name: "choice missing inputs", ID: 12345, State: shared.Active, Path: ".github/workflows/workflow.yml", }, }, })) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/contents/.github/workflows/workflow.yml"), httpmock.JSONResponse(struct{ Content string }{ Content: encodedYAMLContentMissingChoiceIp, })) reg.Register( httpmock.REST("POST", "repos/OWNER/REPO/actions/workflows/12345/dispatches"), httpmock.StatusStringResponse(204, "cool")) }, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterSelect("Select a workflow", []string{"choice missing inputs (workflow.yml)"}, func(_, _ string, opts []string) (int, error) { return 0, nil }) pm.RegisterSelect("name", []string{}, func(_, _ string, opts []string) (int, error) { return 0, nil }) }, wantErr: true, errOut: "workflow input \"name\" is of type choice, but has no options", }, } for _, tt := range tests { reg := &httpmock.Registry{} if tt.httpStubs != nil { tt.httpStubs(reg) } tt.opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } ios, _, stdout, _ := iostreams.Test() ios.SetStdinTTY(tt.tty) ios.SetStdoutTTY(tt.tty) tt.opts.IO = ios tt.opts.BaseRepo = func() (ghrepo.Interface, error) { return api.InitRepoHostname(&api.Repository{ Name: "REPO", Owner: api.RepositoryOwner{Login: "OWNER"}, DefaultBranchRef: api.BranchRef{Name: "trunk"}, }, "github.com"), nil } t.Run(tt.name, func(t *testing.T) { pm := prompter.NewMockPrompter(t) tt.opts.Prompter = pm if tt.promptStubs != nil { tt.promptStubs(pm) } err := runRun(tt.opts) if tt.wantErr { assert.Error(t, err) assert.Equal(t, tt.errOut, err.Error()) return } assert.NoError(t, err) assert.Equal(t, tt.wantOut, stdout.String()) reg.Verify(t) if len(reg.Requests) > 0 { lastRequest := reg.Requests[len(reg.Requests)-1] if lastRequest.Method == "POST" { 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.wantBody, reqBody) } } }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/workflow/run/run.go
pkg/cmd/workflow/run/run.go
package run import ( "bytes" "encoding/json" "errors" "fmt" "io" "net/http" "reflect" "sort" "strings" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/workflow/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" "gopkg.in/yaml.v3" ) type RunOptions struct { HttpClient func() (*http.Client, error) IO *iostreams.IOStreams BaseRepo func() (ghrepo.Interface, error) Prompter iprompter Selector string Ref string JSONInput string JSON bool MagicFields []string RawFields []string Prompt bool } type iprompter interface { Input(string, string) (string, error) Select(string, string, []string) (int, error) } func NewCmdRun(f *cmdutil.Factory, runF func(*RunOptions) error) *cobra.Command { opts := &RunOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, Prompter: f.Prompter, } cmd := &cobra.Command{ Use: "run [<workflow-id> | <workflow-name>]", Short: "Run a workflow by creating a workflow_dispatch event", Long: heredoc.Docf(` Create a %[1]sworkflow_dispatch%[1]s event for a given workflow. This command will trigger GitHub Actions to run a given workflow file. The given workflow file must support an %[1]son.workflow_dispatch%[1]s trigger in order to be run in this way. If the workflow file supports inputs, they can be specified in a few ways: - Interactively - Via %[1]s-f/--raw-field%[1]s or %[1]s-F/--field%[1]s flags - As JSON, via standard input `, "`"), Example: heredoc.Doc(` # Have gh prompt you for what workflow you'd like to run and interactively collect inputs $ gh workflow run # Run the workflow file 'triage.yml' at the remote's default branch $ gh workflow run triage.yml # Run the workflow file 'triage.yml' at a specified ref $ gh workflow run triage.yml --ref my-branch # Run the workflow file 'triage.yml' with command line inputs $ gh workflow run triage.yml -f name=scully -f greeting=hello # Run the workflow file 'triage.yml' with JSON via standard input $ echo '{"name":"scully", "greeting":"hello"}' | gh workflow run triage.yml --json `), Args: func(cmd *cobra.Command, args []string) error { if len(opts.MagicFields)+len(opts.RawFields) > 0 && len(args) == 0 { return cmdutil.FlagErrorf("workflow argument required when passing -f or -F") } return nil }, RunE: func(cmd *cobra.Command, args []string) error { // support `-R, --repo` override opts.BaseRepo = f.BaseRepo inputFieldsPassed := len(opts.MagicFields)+len(opts.RawFields) > 0 if len(args) > 0 { opts.Selector = args[0] } else if !opts.IO.CanPrompt() { return cmdutil.FlagErrorf("workflow ID, name, or filename required when not running interactively") } else { opts.Prompt = true } if opts.JSON && !opts.IO.IsStdinTTY() { jsonIn, err := io.ReadAll(opts.IO.In) if err != nil { return errors.New("failed to read from STDIN") } opts.JSONInput = string(jsonIn) } else if opts.JSON { return cmdutil.FlagErrorf("--json specified but nothing on STDIN") } if opts.Selector == "" { if opts.JSONInput != "" { return cmdutil.FlagErrorf("workflow argument required when passing JSON") } } else { if opts.JSON && inputFieldsPassed { return cmdutil.FlagErrorf("only one of STDIN or -f/-F can be passed") } } if runF != nil { return runF(opts) } return runRun(opts) }, } cmd.Flags().StringVarP(&opts.Ref, "ref", "r", "", "Branch or tag name which contains the version of the workflow file you'd like to run") cmd.Flags().StringArrayVarP(&opts.MagicFields, "field", "F", nil, "Add a string parameter in `key=value` format, respecting @ syntax (see \"gh help api\").") cmd.Flags().StringArrayVarP(&opts.RawFields, "raw-field", "f", nil, "Add a string parameter in `key=value` format") cmd.Flags().BoolVar(&opts.JSON, "json", false, "Read workflow inputs as JSON via STDIN") _ = cmdutil.RegisterBranchCompletionFlags(f.GitClient, cmd, "ref") return cmd } // TODO copypasta from gh api func parseField(f string) (string, string, error) { idx := strings.IndexRune(f, '=') if idx == -1 { return f, "", fmt.Errorf("field %q requires a value separated by an '=' sign", f) } return f[0:idx], f[idx+1:], nil } // TODO MODIFIED copypasta from gh api func magicFieldValue(v string, opts RunOptions) (string, error) { if strings.HasPrefix(v, "@") { fileBytes, err := opts.IO.ReadUserFile(v[1:]) if err != nil { return "", err } return string(fileBytes), nil } return v, nil } // TODO copypasta from gh api func parseFields(opts RunOptions) (map[string]string, error) { params := make(map[string]string) for _, f := range opts.RawFields { key, value, err := parseField(f) if err != nil { return params, err } params[key] = value } for _, f := range opts.MagicFields { key, strValue, err := parseField(f) if err != nil { return params, err } value, err := magicFieldValue(strValue, opts) if err != nil { return params, fmt.Errorf("error parsing %q value: %w", key, err) } params[key] = value } return params, nil } type InputAnswer struct { providedInputs map[string]string } func (ia *InputAnswer) WriteAnswer(name string, value interface{}) error { if s, ok := value.(string); ok { ia.providedInputs[name] = s return nil } // TODO i hate this; this is to make tests work: if rv, ok := value.(reflect.Value); ok { ia.providedInputs[name] = rv.String() return nil } return fmt.Errorf("unexpected value type: %v", value) } func collectInputs(p iprompter, yamlContent []byte) (map[string]string, error) { inputs, err := findInputs(yamlContent) if err != nil { return nil, err } providedInputs := map[string]string{} if len(inputs) == 0 { return providedInputs, nil } for _, input := range inputs { var answer string if input.Type == "choice" { name := input.Name if input.Required { name += " (required)" } selected, err := p.Select(name, input.Default, input.Options) if err != nil { return nil, err } answer = input.Options[selected] } else if input.Required { for answer == "" { answer, err = p.Input(input.Name+" (required)", input.Default) if err != nil { break } } } else { answer, err = p.Input(input.Name, input.Default) } if err != nil { return nil, err } providedInputs[input.Name] = answer } return providedInputs, nil } func runRun(opts *RunOptions) error { c, err := opts.HttpClient() if err != nil { return fmt.Errorf("could not build http client: %w", err) } client := api.NewClientFromHTTP(c) repo, err := opts.BaseRepo() if err != nil { return err } ref := opts.Ref if ref == "" { ref, err = api.RepoDefaultBranch(client, repo) if err != nil { return fmt.Errorf("unable to determine default branch for %s: %w", ghrepo.FullName(repo), err) } } states := []shared.WorkflowState{shared.Active} workflow, err := shared.ResolveWorkflow(opts.Prompter, opts.IO, client, repo, opts.Prompt, opts.Selector, states) if err != nil { var fae shared.FilteredAllError if errors.As(err, &fae) { return errors.New("no workflows are enabled on this repository") } return err } providedInputs := map[string]string{} if len(opts.MagicFields)+len(opts.RawFields) > 0 { providedInputs, err = parseFields(*opts) if err != nil { return err } } else if opts.JSONInput != "" { err := json.Unmarshal([]byte(opts.JSONInput), &providedInputs) if err != nil { return fmt.Errorf("could not parse provided JSON: %w", err) } } else if opts.Prompt { yamlContent, err := shared.GetWorkflowContent(client, repo, *workflow, ref) if err != nil { return fmt.Errorf("unable to fetch workflow file content: %w", err) } providedInputs, err = collectInputs(opts.Prompter, yamlContent) if err != nil { return err } } path := fmt.Sprintf("repos/%s/actions/workflows/%d/dispatches", ghrepo.FullName(repo), workflow.ID) requestByte, err := json.Marshal(map[string]interface{}{ "ref": ref, "inputs": providedInputs, }) if err != nil { return fmt.Errorf("failed to serialize workflow inputs: %w", err) } body := bytes.NewReader(requestByte) err = client.REST(repo.RepoHost(), "POST", path, body, nil) if err != nil { return fmt.Errorf("could not create workflow dispatch event: %w", err) } if opts.IO.IsStdoutTTY() { out := opts.IO.Out cs := opts.IO.ColorScheme() fmt.Fprintf(out, "%s Created workflow_dispatch event for %s at %s\n", cs.SuccessIcon(), cs.Cyan(workflow.Base()), cs.Bold(ref)) fmt.Fprintln(out) fmt.Fprintf(out, "To see runs for this workflow, try: %s\n", cs.Boldf("gh run list --workflow=%q", workflow.Base())) } return nil } type WorkflowInput struct { Name string Required bool Default string Description string Type string Options []string } func findInputs(yamlContent []byte) ([]WorkflowInput, error) { var rootNode yaml.Node err := yaml.Unmarshal(yamlContent, &rootNode) if err != nil { return nil, fmt.Errorf("unable to parse workflow YAML: %w", err) } if len(rootNode.Content) != 1 { return nil, errors.New("invalid YAML file") } var onKeyNode *yaml.Node var dispatchKeyNode *yaml.Node var inputsKeyNode *yaml.Node var inputsMapNode *yaml.Node // TODO this is pretty hideous for _, node := range rootNode.Content[0].Content { if onKeyNode != nil { if node.Kind == yaml.MappingNode { for _, node := range node.Content { if dispatchKeyNode != nil { for _, node := range node.Content { if inputsKeyNode != nil { inputsMapNode = node break } if node.Value == "inputs" { inputsKeyNode = node } } break } if node.Value == "workflow_dispatch" { dispatchKeyNode = node } } } else if node.Kind == yaml.SequenceNode { for _, node := range node.Content { if node.Value == "workflow_dispatch" { dispatchKeyNode = node break } } } else if node.Kind == yaml.ScalarNode { if node.Value == "workflow_dispatch" { dispatchKeyNode = node break } } break } if strings.EqualFold(node.Value, "on") { onKeyNode = node } } if onKeyNode == nil { return nil, errors.New("invalid workflow: no 'on' key") } if dispatchKeyNode == nil { return nil, errors.New("unable to manually run a workflow without a workflow_dispatch event") } out := []WorkflowInput{} m := map[string]WorkflowInput{} if inputsKeyNode == nil || inputsMapNode == nil { return out, nil } err = inputsMapNode.Decode(&m) if err != nil { return nil, fmt.Errorf("could not decode workflow inputs: %w", err) } for name, input := range m { if input.Type == "choice" && len(input.Options) == 0 { return nil, fmt.Errorf("workflow input %q is of type choice, but has no options", name) } out = append(out, WorkflowInput{ Name: name, Default: input.Default, Description: input.Description, Required: input.Required, Options: input.Options, Type: input.Type, }) } sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) return out, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/workflow/disable/disable_test.go
pkg/cmd/workflow/disable/disable_test.go
package disable import ( "bytes" "io" "net/http" "testing" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/pkg/cmd/workflow/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" ) func TestNewCmdDisable(t *testing.T) { tests := []struct { name string cli string tty bool wants DisableOptions wantsErr bool }{ { name: "blank tty", tty: true, wants: DisableOptions{ Prompt: true, }, }, { name: "blank nontty", wantsErr: true, }, { name: "arg tty", cli: "123", tty: true, wants: DisableOptions{ Selector: "123", }, }, { name: "arg nontty", cli: "123", wants: DisableOptions{ Selector: "123", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() ios.SetStdinTTY(tt.tty) ios.SetStdoutTTY(tt.tty) f := &cmdutil.Factory{ IOStreams: ios, } argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts *DisableOptions cmd := NewCmdDisable(f, func(opts *DisableOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(io.Discard) cmd.SetErr(io.Discard) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) return } assert.NoError(t, err) assert.Equal(t, tt.wants.Selector, gotOpts.Selector) assert.Equal(t, tt.wants.Prompt, gotOpts.Prompt) }) } } func TestDisableRun(t *testing.T) { tests := []struct { name string opts *DisableOptions httpStubs func(*httpmock.Registry) promptStubs func(*prompter.MockPrompter) tty bool wantOut string wantErrOut string wantErr bool }{ { name: "tty no arg", opts: &DisableOptions{ Prompt: true, }, tty: true, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(shared.WorkflowsPayload{ Workflows: []shared.Workflow{ shared.AWorkflow, shared.DisabledWorkflow, shared.AnotherWorkflow, }, })) reg.Register( httpmock.REST("PUT", "repos/OWNER/REPO/actions/workflows/789/disable"), httpmock.StatusStringResponse(204, "{}")) }, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterSelect("Select a workflow", []string{"a workflow (flow.yml)", "another workflow (another.yml)"}, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "another workflow (another.yml)") }) }, wantOut: "✓ Disabled another workflow\n", }, { name: "tty name arg", opts: &DisableOptions{ Selector: "a workflow", }, tty: true, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(shared.WorkflowsPayload{ Workflows: []shared.Workflow{ shared.AWorkflow, shared.DisabledWorkflow, shared.AnotherWorkflow, }, })) reg.Register( httpmock.REST("PUT", "repos/OWNER/REPO/actions/workflows/123/disable"), httpmock.StatusStringResponse(204, "{}")) }, wantOut: "✓ Disabled a workflow\n", }, { name: "tty name arg nonunique", opts: &DisableOptions{ Selector: "another workflow", }, tty: true, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(shared.WorkflowsPayload{ Workflows: []shared.Workflow{ shared.AWorkflow, shared.DisabledWorkflow, shared.AnotherWorkflow, shared.YetAnotherWorkflow, shared.AnotherDisabledWorkflow, }, })) reg.Register( httpmock.REST("PUT", "repos/OWNER/REPO/actions/workflows/1011/disable"), httpmock.StatusStringResponse(204, "{}")) }, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterSelect("Which workflow do you mean?", []string{"another workflow (another.yml)", "another workflow (yetanother.yml)"}, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "another workflow (yetanother.yml)") }) }, wantOut: "✓ Disabled another workflow\n", }, { name: "tty ID arg", opts: &DisableOptions{ Selector: "123", }, tty: true, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.AWorkflow)) reg.Register( httpmock.REST("PUT", "repos/OWNER/REPO/actions/workflows/123/disable"), httpmock.StatusStringResponse(204, "{}")) }, wantOut: "✓ Disabled a workflow\n", }, { name: "nontty ID arg", opts: &DisableOptions{ Selector: "123", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/123"), httpmock.JSONResponse(shared.AWorkflow)) reg.Register( httpmock.REST("PUT", "repos/OWNER/REPO/actions/workflows/123/disable"), httpmock.StatusStringResponse(204, "{}")) }, }, { name: "nontty name arg", opts: &DisableOptions{ Selector: "a workflow", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(shared.WorkflowsPayload{ Workflows: []shared.Workflow{ shared.AWorkflow, shared.DisabledWorkflow, shared.AnotherWorkflow, shared.AnotherDisabledWorkflow, shared.UniqueDisabledWorkflow, }, })) reg.Register( httpmock.REST("PUT", "repos/OWNER/REPO/actions/workflows/123/disable"), httpmock.StatusStringResponse(204, "{}")) }, }, { name: "nontty name arg nonunique", opts: &DisableOptions{ Selector: "another workflow", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/another%20workflow"), httpmock.StatusStringResponse(404, "not found")) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(shared.WorkflowsPayload{ Workflows: []shared.Workflow{ shared.AWorkflow, shared.DisabledWorkflow, shared.AnotherWorkflow, shared.YetAnotherWorkflow, shared.AnotherDisabledWorkflow, shared.UniqueDisabledWorkflow, }, })) }, wantErr: true, wantErrOut: "could not resolve to a unique workflow; found: another.yml yetanother.yml", }, } for _, tt := range tests { reg := &httpmock.Registry{} tt.httpStubs(reg) tt.opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(tt.tty) ios.SetStdinTTY(tt.tty) tt.opts.IO = ios tt.opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.FromFullName("OWNER/REPO") } t.Run(tt.name, func(t *testing.T) { pm := prompter.NewMockPrompter(t) tt.opts.Prompter = pm if tt.promptStubs != nil { tt.promptStubs(pm) } err := runDisable(tt.opts) if tt.wantErr { assert.Error(t, err) assert.Equal(t, tt.wantErrOut, 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/workflow/disable/disable.go
pkg/cmd/workflow/disable/disable.go
package disable import ( "errors" "fmt" "net/http" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/workflow/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type DisableOptions struct { HttpClient func() (*http.Client, error) IO *iostreams.IOStreams BaseRepo func() (ghrepo.Interface, error) Prompter iprompter Selector string Prompt bool } type iprompter interface { Select(string, string, []string) (int, error) } func NewCmdDisable(f *cmdutil.Factory, runF func(*DisableOptions) error) *cobra.Command { opts := &DisableOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, Prompter: f.Prompter, } cmd := &cobra.Command{ Use: "disable [<workflow-id> | <workflow-name>]", Short: "Disable a workflow", Long: "Disable a workflow, preventing it from running or showing up when listing workflows.", Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { // support `-R, --repo` override opts.BaseRepo = f.BaseRepo if len(args) > 0 { opts.Selector = args[0] } else if !opts.IO.CanPrompt() { return cmdutil.FlagErrorf("workflow ID or name required when not running interactively") } else { opts.Prompt = true } if runF != nil { return runF(opts) } return runDisable(opts) }, } return cmd } func runDisable(opts *DisableOptions) error { c, err := opts.HttpClient() if err != nil { return fmt.Errorf("could not build http client: %w", err) } client := api.NewClientFromHTTP(c) repo, err := opts.BaseRepo() if err != nil { return err } states := []shared.WorkflowState{shared.Active} workflow, err := shared.ResolveWorkflow( opts.Prompter, opts.IO, client, repo, opts.Prompt, opts.Selector, states) if err != nil { var fae shared.FilteredAllError if errors.As(err, &fae) { return errors.New("there are no enabled workflows to disable") } return err } path := fmt.Sprintf("repos/%s/actions/workflows/%d/disable", ghrepo.FullName(repo), workflow.ID) err = client.REST(repo.RepoHost(), "PUT", path, nil, nil) if err != nil { return fmt.Errorf("failed to disable workflow: %w", err) } if opts.IO.CanPrompt() { cs := opts.IO.ColorScheme() fmt.Fprintf(opts.IO.Out, "%s Disabled %s\n", cs.SuccessIconWithColor(cs.Red), cs.Bold(workflow.Name)) } return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/workflow/enable/enable.go
pkg/cmd/workflow/enable/enable.go
package enable import ( "errors" "fmt" "net/http" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/workflow/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type EnableOptions struct { HttpClient func() (*http.Client, error) IO *iostreams.IOStreams BaseRepo func() (ghrepo.Interface, error) Prompter iprompter Selector string Prompt bool } type iprompter interface { Select(string, string, []string) (int, error) } func NewCmdEnable(f *cmdutil.Factory, runF func(*EnableOptions) error) *cobra.Command { opts := &EnableOptions{ IO: f.IOStreams, HttpClient: f.HttpClient, Prompter: f.Prompter, } cmd := &cobra.Command{ Use: "enable [<workflow-id> | <workflow-name>]", Short: "Enable a workflow", Long: "Enable a workflow, allowing it to be run and show up when listing workflows.", Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { // support `-R, --repo` override opts.BaseRepo = f.BaseRepo if len(args) > 0 { opts.Selector = args[0] } else if !opts.IO.CanPrompt() { return cmdutil.FlagErrorf("workflow ID or name required when not running interactively") } else { opts.Prompt = true } if runF != nil { return runF(opts) } return runEnable(opts) }, } return cmd } func runEnable(opts *EnableOptions) error { c, err := opts.HttpClient() if err != nil { return fmt.Errorf("could not build http client: %w", err) } client := api.NewClientFromHTTP(c) repo, err := opts.BaseRepo() if err != nil { return err } states := []shared.WorkflowState{shared.DisabledManually, shared.DisabledInactivity} workflow, err := shared.ResolveWorkflow(opts.Prompter, opts.IO, client, repo, opts.Prompt, opts.Selector, states) if err != nil { var fae shared.FilteredAllError if errors.As(err, &fae) { return errors.New("there are no disabled workflows to enable") } return err } path := fmt.Sprintf("repos/%s/actions/workflows/%d/enable", ghrepo.FullName(repo), workflow.ID) err = client.REST(repo.RepoHost(), "PUT", path, nil, nil) if err != nil { return fmt.Errorf("failed to enable workflow: %w", err) } if opts.IO.CanPrompt() { cs := opts.IO.ColorScheme() fmt.Fprintf(opts.IO.Out, "%s Enabled %s\n", cs.SuccessIcon(), cs.Bold(workflow.Name)) } return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/workflow/enable/enable_test.go
pkg/cmd/workflow/enable/enable_test.go
package enable import ( "bytes" "io" "net/http" "testing" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/pkg/cmd/workflow/shared" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" ) func TestNewCmdEnable(t *testing.T) { tests := []struct { name string cli string tty bool wants EnableOptions wantsErr bool }{ { name: "blank tty", tty: true, wants: EnableOptions{ Prompt: true, }, }, { name: "blank nontty", wantsErr: true, }, { name: "arg tty", cli: "123", tty: true, wants: EnableOptions{ Selector: "123", }, }, { name: "arg nontty", cli: "123", wants: EnableOptions{ Selector: "123", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, _, _ := iostreams.Test() ios.SetStdinTTY(tt.tty) ios.SetStdoutTTY(tt.tty) f := &cmdutil.Factory{ IOStreams: ios, } argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts *EnableOptions cmd := NewCmdEnable(f, func(opts *EnableOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(io.Discard) cmd.SetErr(io.Discard) _, err = cmd.ExecuteC() if tt.wantsErr { assert.Error(t, err) return } assert.NoError(t, err) assert.Equal(t, tt.wants.Selector, gotOpts.Selector) assert.Equal(t, tt.wants.Prompt, gotOpts.Prompt) }) } } func TestEnableRun(t *testing.T) { tests := []struct { name string opts *EnableOptions httpStubs func(*httpmock.Registry) promptStubs func(*prompter.MockPrompter) tty bool wantOut string wantErrOut string wantErr bool }{ { name: "tty no arg", opts: &EnableOptions{ Prompt: true, }, tty: true, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(shared.WorkflowsPayload{ Workflows: []shared.Workflow{ shared.AWorkflow, shared.DisabledWorkflow, shared.AnotherWorkflow, }, })) reg.Register( httpmock.REST("PUT", "repos/OWNER/REPO/actions/workflows/456/enable"), httpmock.StatusStringResponse(204, "{}")) }, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterSelect("Select a workflow", []string{"a disabled workflow (disabled.yml)"}, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "a disabled workflow (disabled.yml)") }) }, wantOut: "✓ Enabled a disabled workflow\n", }, { name: "tty name arg", opts: &EnableOptions{ Selector: "terrible workflow", }, tty: true, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(shared.WorkflowsPayload{ Workflows: []shared.Workflow{ shared.AWorkflow, shared.DisabledWorkflow, shared.UniqueDisabledWorkflow, shared.AnotherWorkflow, }, })) reg.Register( httpmock.REST("PUT", "repos/OWNER/REPO/actions/workflows/1314/enable"), httpmock.StatusStringResponse(204, "{}")) }, wantOut: "✓ Enabled terrible workflow\n", }, { name: "tty name arg nonunique", opts: &EnableOptions{ Selector: "a disabled workflow", }, tty: true, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(shared.WorkflowsPayload{ Workflows: []shared.Workflow{ shared.AWorkflow, shared.DisabledWorkflow, shared.AnotherWorkflow, shared.AnotherDisabledWorkflow, }, })) reg.Register( httpmock.REST("PUT", "repos/OWNER/REPO/actions/workflows/1213/enable"), httpmock.StatusStringResponse(204, "{}")) }, promptStubs: func(pm *prompter.MockPrompter) { pm.RegisterSelect("Which workflow do you mean?", []string{"a disabled workflow (disabled.yml)", "a disabled workflow (anotherDisabled.yml)"}, func(_, _ string, opts []string) (int, error) { return prompter.IndexFor(opts, "a disabled workflow (anotherDisabled.yml)") }) }, wantOut: "✓ Enabled a disabled workflow\n", }, { name: "tty name arg inactivity workflow", opts: &EnableOptions{ Selector: "a disabled inactivity workflow", }, tty: true, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(shared.WorkflowsPayload{ Workflows: []shared.Workflow{ shared.AWorkflow, shared.DisabledInactivityWorkflow, shared.UniqueDisabledWorkflow, shared.AnotherWorkflow, }, })) reg.Register( httpmock.REST("PUT", "repos/OWNER/REPO/actions/workflows/1206/enable"), httpmock.StatusStringResponse(204, "{}")) }, wantOut: "✓ Enabled a disabled inactivity workflow\n", }, { name: "tty ID arg", opts: &EnableOptions{ Selector: "456", }, tty: true, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/456"), httpmock.JSONResponse(shared.DisabledWorkflow)) reg.Register( httpmock.REST("PUT", "repos/OWNER/REPO/actions/workflows/456/enable"), httpmock.StatusStringResponse(204, "{}")) }, wantOut: "✓ Enabled a disabled workflow\n", }, { name: "nontty ID arg", opts: &EnableOptions{ Selector: "456", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/456"), httpmock.JSONResponse(shared.DisabledWorkflow)) reg.Register( httpmock.REST("PUT", "repos/OWNER/REPO/actions/workflows/456/enable"), httpmock.StatusStringResponse(204, "{}")) }, }, { name: "nontty name arg", opts: &EnableOptions{ Selector: "terrible workflow", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(shared.WorkflowsPayload{ Workflows: []shared.Workflow{ shared.AWorkflow, shared.DisabledWorkflow, shared.AnotherWorkflow, shared.AnotherDisabledWorkflow, shared.UniqueDisabledWorkflow, }, })) reg.Register( httpmock.REST("PUT", "repos/OWNER/REPO/actions/workflows/1314/enable"), httpmock.StatusStringResponse(204, "{}")) }, }, { name: "nontty name arg inactivity workflow", opts: &EnableOptions{ Selector: "a disabled inactivity workflow", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(shared.WorkflowsPayload{ Workflows: []shared.Workflow{ shared.AWorkflow, shared.DisabledInactivityWorkflow, shared.UniqueDisabledWorkflow, shared.AnotherWorkflow, }, })) reg.Register( httpmock.REST("PUT", "repos/OWNER/REPO/actions/workflows/1206/enable"), httpmock.StatusStringResponse(204, "{}")) }, }, { name: "nontty name arg nonunique", opts: &EnableOptions{ Selector: "a disabled workflow", }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.JSONResponse(shared.WorkflowsPayload{ Workflows: []shared.Workflow{ shared.AWorkflow, shared.DisabledWorkflow, shared.AnotherWorkflow, shared.AnotherDisabledWorkflow, shared.UniqueDisabledWorkflow, }, })) }, wantErr: true, wantErrOut: "could not resolve to a unique workflow; found: disabled.yml anotherDisabled.yml", }, } for _, tt := range tests { reg := &httpmock.Registry{} tt.httpStubs(reg) tt.opts.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } ios, _, stdout, _ := iostreams.Test() ios.SetStdoutTTY(tt.tty) ios.SetStdinTTY(tt.tty) tt.opts.IO = ios tt.opts.BaseRepo = func() (ghrepo.Interface, error) { return ghrepo.FromFullName("OWNER/REPO") } t.Run(tt.name, func(t *testing.T) { pm := prompter.NewMockPrompter(t) tt.opts.Prompter = pm if tt.promptStubs != nil { tt.promptStubs(pm) } err := runEnable(tt.opts) if tt.wantErr { assert.Error(t, err) assert.Equal(t, tt.wantErrOut, 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/workflow/shared/shared_test.go
pkg/cmd/workflow/shared/shared_test.go
package shared import ( "errors" "fmt" "net/http" "net/url" "strings" "testing" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/httpmock" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ghAPI "github.com/cli/go-gh/v2/pkg/api" ) func TestFindWorkflow(t *testing.T) { badRequestURL, err := url.Parse("https://api.github.com/repos/OWNER/REPO/actions/workflows/nonexistentWorkflow.yml") if err != nil { t.Fatal(err) } tests := []struct { name string workflowSelector string repo ghrepo.Interface httpStubs func(*httpmock.Registry) states []WorkflowState expectedWorkflow Workflow expectedHTTPError *api.HTTPError expectedError error }{ { name: "When the workflow selector is empty, it returns an error", workflowSelector: "", repo: ghrepo.New("OWNER", "REPO"), expectedError: errors.New("empty workflow selector"), }, { name: "When the workflow selector is a number, it returns the workflow with that ID", workflowSelector: "1", repo: ghrepo.New("OWNER", "REPO"), httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/1"), httpmock.StatusJSONResponse(200, Workflow{ ID: 1, }), ) }, expectedWorkflow: Workflow{ ID: 1, }, }, { name: "When the workflow selector is a file, it returns the workflow with that path", workflowSelector: "workflowFile.yml", repo: ghrepo.New("OWNER", "REPO"), httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows/workflowFile.yml"), httpmock.StatusJSONResponse(200, Workflow{ ID: 1, Name: "Some Workflow", Path: ".github/workflows/workflowFile.yml", }), ) }, expectedWorkflow: Workflow{ ID: 1, Name: "Some Workflow", Path: ".github/workflows/workflowFile.yml", }, }, { name: "When the workflow selector is a workflow that doesn't exist, it returns the workflow not found error", workflowSelector: "nonexistentWorkflow.yml", repo: ghrepo.New("OWNER", "REPO"), httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", strings.TrimPrefix(badRequestURL.Path, "/")), httpmock.StatusJSONResponse(404, Workflow{}), ) }, expectedHTTPError: &api.HTTPError{ HTTPError: &ghAPI.HTTPError{ Message: "workflow nonexistentWorkflow.yml not found on the default branch", StatusCode: 404, RequestURL: badRequestURL, }, }, }, { name: "When the workflow selector is a file but the server errors, it returns that error", workflowSelector: "nonexistentWorkflow.yml", repo: ghrepo.New("OWNER", "REPO"), httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", strings.TrimPrefix(badRequestURL.Path, "/")), httpmock.StatusStringResponse(500, "server error"), ) }, expectedHTTPError: &api.HTTPError{ HTTPError: &ghAPI.HTTPError{ Errors: []ghAPI.HTTPErrorItem{ { Message: "server error", }, }, StatusCode: 500, RequestURL: badRequestURL, }, }, }, { name: "When the workflow selector is a name and the state is active, it returns that workflow", workflowSelector: "Workflow Name", repo: ghrepo.New("OWNER", "REPO"), states: []WorkflowState{Active}, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.StatusJSONResponse(200, WorkflowsPayload{ Workflows: []Workflow{ { ID: 1, Name: "Workflow Name", State: Active, }, }}), ) }, expectedWorkflow: Workflow{ ID: 1, Name: "Workflow Name", State: "active", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { reg := &httpmock.Registry{} if tt.httpStubs != nil { tt.httpStubs(reg) } client := api.NewClientFromHTTP(&http.Client{Transport: reg}) workflow, err := FindWorkflow(client, tt.repo, tt.workflowSelector, tt.states) if tt.expectedError != nil { require.Error(t, err) assert.Equal(t, tt.expectedError, err) } else if tt.expectedHTTPError != nil { var httpErr api.HTTPError require.ErrorAs(t, err, &httpErr) assert.Equal(t, tt.expectedHTTPError.Error(), httpErr.Error()) } else { require.NoError(t, err) assert.Equal(t, tt.expectedWorkflow, workflow[0]) } }) } } type ErrorTransport struct { Err error } func (t *ErrorTransport) RoundTrip(req *http.Request) (*http.Response, error) { return nil, t.Err } func TestFindWorkflow_nonHTTPError(t *testing.T) { t.Run("When the client fails to instantiate, it returns the error", func(t *testing.T) { client := api.NewClientFromHTTP(&http.Client{Transport: &ErrorTransport{Err: errors.New("non-HTTP error")}}) repo := ghrepo.New("OWNER", "REPO") workflow, err := FindWorkflow(client, repo, "1", nil) require.Error(t, err) assert.ErrorContains(t, err, "non-HTTP error") assert.Nil(t, workflow) }) } func Test_getWorkflowsByName_filtering(t *testing.T) { tests := []struct { name string workflowName string repo ghrepo.Interface states []WorkflowState httpStubs func(*httpmock.Registry) expectedWorkflows []Workflow expectedErrorMsg string }{ { name: "When no workflows match, no workflows are returned", workflowName: "Unmatched Workflow Name", repo: ghrepo.New("OWNER", "REPO"), states: []WorkflowState{Active}, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.StatusJSONResponse(200, WorkflowsPayload{ Workflows: []Workflow{ { ID: 1, Name: "Workflow Name", State: Active, }, { ID: 2, Name: "Workflow Name", State: DisabledInactivity, }, { ID: 3, Name: "Workflow Name", State: Active, }, }, }), ) }, expectedWorkflows: []Workflow(nil), }, { name: "When there are more than one workflow with the same name, only the ones matching the provided state are returned", workflowName: "Workflow Name", repo: ghrepo.New("OWNER", "REPO"), states: []WorkflowState{Active}, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.StatusJSONResponse(200, WorkflowsPayload{ Workflows: []Workflow{ { ID: 1, Name: "Workflow Name", State: Active, }, { ID: 2, Name: "Workflow Name", State: DisabledInactivity, }, { ID: 3, Name: "Workflow Name", State: Active, }, }, }), ) }, expectedWorkflows: []Workflow{ { ID: 1, Name: "Workflow Name", State: Active, }, { ID: 3, Name: "Workflow Name", State: Active, }, }, }, { name: "When GetWorkflows errors", repo: ghrepo.New("OWNER", "REPO"), httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.StatusStringResponse(500, ""), ) }, expectedErrorMsg: "couldn't fetch workflows for OWNER/REPO", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { reg := &httpmock.Registry{} if tt.httpStubs != nil { tt.httpStubs(reg) } client := api.NewClientFromHTTP(&http.Client{Transport: reg}) workflows, err := getWorkflowsByName(client, tt.repo, tt.workflowName, tt.states) if tt.expectedErrorMsg != "" { require.Error(t, err) assert.ErrorContains(t, err, tt.expectedErrorMsg) } else { require.NoError(t, err) assert.Equal(t, tt.expectedWorkflows, workflows) } }) } } func TestGetWorkflows(t *testing.T) { tests := []struct { name string repo ghrepo.Interface limit int httpStubs func(*httpmock.Registry) expectedWorkflows []Workflow expectedError error }{ { name: "When the repo has no workflows, it returns an empty slice", repo: ghrepo.New("OWNER", "REPO"), httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.StatusJSONResponse(200, WorkflowsPayload{ Workflows: []Workflow{}, }), ) }, expectedWorkflows: []Workflow{}, }, { name: "When the api returns workflows, it returns those workflows", repo: ghrepo.New("OWNER", "REPO"), httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.StatusJSONResponse(200, WorkflowsPayload{ Workflows: []Workflow{ { Name: "Workflow 1", }, { Name: "Workflow 2", }, }, }), ) }, expectedWorkflows: []Workflow{ { Name: "Workflow 1", }, { Name: "Workflow 2", }, }, }, { name: "When the api return paginates, it returns the workflows from all the pages", repo: ghrepo.New("OWNER", "REPO"), limit: 0, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.StatusJSONResponse(200, WorkflowsPayload{ Workflows: generateWorkflows(t, 100, 1), }), ) reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.StatusJSONResponse(200, WorkflowsPayload{ Workflows: generateWorkflows(t, 50, 2), }), ) }, expectedWorkflows: append(generateWorkflows(t, 100, 1), generateWorkflows(t, 50, 2)...), }, { name: "When the limit is set to fewer workflows than the api returns, it returns the number of workflows specified by the limit", repo: ghrepo.New("OWNER", "REPO"), limit: 2, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.REST("GET", "repos/OWNER/REPO/actions/workflows"), httpmock.StatusJSONResponse(200, WorkflowsPayload{ Workflows: generateWorkflows(t, 100, 1), }), ) }, expectedWorkflows: generateWorkflows(t, 2, 1), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { reg := &httpmock.Registry{} if tt.httpStubs != nil { tt.httpStubs(reg) } client := api.NewClientFromHTTP(&http.Client{Transport: reg}) workflows, err := GetWorkflows(client, tt.repo, tt.limit) if tt.expectedError != nil { require.Error(t, err) assert.Equal(t, tt.expectedError, err) } else { require.NoError(t, err) assert.Equal(t, tt.expectedWorkflows, workflows) } }) } } // generateWorkflows returns an slice of workflows with the given count, labeled // with the page number of testing pagination. // The page number is used to generate unique Names and IDs for each workflow. func generateWorkflows(t *testing.T, workflowCount int, pageNum int) []Workflow { t.Helper() workflows := []Workflow{} for i := 0; i < workflowCount; i++ { workflows = append(workflows, Workflow{ Name: fmt.Sprintf("Workflow-%d-%d", pageNum, i), ID: int64(i) + int64(pageNum-1)*100, }) } return workflows }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/workflow/shared/shared.go
pkg/cmd/workflow/shared/shared.go
package shared import ( "bytes" "encoding/base64" "errors" "fmt" "io" "net/url" "path" "strconv" "strings" "github.com/cli/cli/v2/api" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/go-gh/v2/pkg/asciisanitizer" "golang.org/x/text/transform" ) const ( Active WorkflowState = "active" DisabledManually WorkflowState = "disabled_manually" DisabledInactivity WorkflowState = "disabled_inactivity" ) type iprompter interface { Select(string, string, []string) (int, error) } type WorkflowState string type Workflow struct { Name string ID int64 Path string State WorkflowState } type WorkflowsPayload struct { Workflows []Workflow } func (w *Workflow) Disabled() bool { return w.State != Active } func (w *Workflow) Base() string { return path.Base(w.Path) } func (w *Workflow) ExportData(fields []string) map[string]interface{} { return cmdutil.StructExportData(w, fields) } func GetWorkflows(client *api.Client, repo ghrepo.Interface, limit int) ([]Workflow, error) { perPage := limit page := 1 if limit > 100 || limit == 0 { perPage = 100 } workflows := []Workflow{} for { if limit > 0 && len(workflows) == limit { break } var result WorkflowsPayload path := fmt.Sprintf("repos/%s/actions/workflows?per_page=%d&page=%d", ghrepo.FullName(repo), perPage, page) err := client.REST(repo.RepoHost(), "GET", path, nil, &result) if err != nil { return nil, err } for _, workflow := range result.Workflows { workflows = append(workflows, workflow) if limit > 0 && len(workflows) == limit { break } } if len(result.Workflows) < perPage { break } page++ } return workflows, nil } type FilteredAllError struct { error } func selectWorkflow(p iprompter, workflows []Workflow, promptMsg string, states []WorkflowState) (*Workflow, error) { filtered := []Workflow{} candidates := []string{} for _, workflow := range workflows { for _, state := range states { if workflow.State == state { filtered = append(filtered, workflow) candidates = append(candidates, fmt.Sprintf("%s (%s)", workflow.Name, workflow.Base())) break } } } if len(candidates) == 0 { return nil, FilteredAllError{errors.New("")} } selected, err := p.Select(promptMsg, "", candidates) if err != nil { return nil, err } return &filtered[selected], nil } // FindWorkflow looks up a workflow either by numeric database ID, file name, or its Name field func FindWorkflow(client *api.Client, repo ghrepo.Interface, workflowSelector string, states []WorkflowState) ([]Workflow, error) { if workflowSelector == "" { return nil, errors.New("empty workflow selector") } if _, err := strconv.Atoi(workflowSelector); err == nil || isWorkflowFile(workflowSelector) { workflow, err := getWorkflowByID(client, repo, workflowSelector) if err != nil { var httpErr api.HTTPError if errors.As(err, &httpErr) { if httpErr.StatusCode == 404 { httpErr.Message = fmt.Sprintf("workflow %s not found on the default branch", workflowSelector) } return nil, httpErr } return nil, err } return []Workflow{*workflow}, nil } return getWorkflowsByName(client, repo, workflowSelector, states) } func GetWorkflow(client *api.Client, repo ghrepo.Interface, workflowID int64) (*Workflow, error) { return getWorkflowByID(client, repo, strconv.FormatInt(workflowID, 10)) } func isWorkflowFile(f string) bool { name := strings.ToLower(f) return strings.HasSuffix(name, ".yml") || strings.HasSuffix(name, ".yaml") } // ID can be either a numeric database ID or the workflow file name func getWorkflowByID(client *api.Client, repo ghrepo.Interface, ID string) (*Workflow, error) { var workflow Workflow path := fmt.Sprintf("repos/%s/actions/workflows/%s", ghrepo.FullName(repo), url.PathEscape(ID)) if err := client.REST(repo.RepoHost(), "GET", path, nil, &workflow); err != nil { return nil, err } return &workflow, nil } func getWorkflowsByName(client *api.Client, repo ghrepo.Interface, name string, states []WorkflowState) ([]Workflow, error) { workflows, err := GetWorkflows(client, repo, 0) if err != nil { return nil, fmt.Errorf("couldn't fetch workflows for %s: %w", ghrepo.FullName(repo), err) } var filtered []Workflow for _, workflow := range workflows { if !strings.EqualFold(workflow.Name, name) { continue } for _, state := range states { if workflow.State == state { filtered = append(filtered, workflow) break } } } return filtered, nil } func ResolveWorkflow(p iprompter, io *iostreams.IOStreams, client *api.Client, repo ghrepo.Interface, prompt bool, workflowSelector string, states []WorkflowState) (*Workflow, error) { if prompt { workflows, err := GetWorkflows(client, repo, 0) if len(workflows) == 0 { err = errors.New("no workflows are enabled") } if err != nil { var httpErr api.HTTPError if errors.As(err, &httpErr) && httpErr.StatusCode == 404 { err = errors.New("no workflows are enabled") } return nil, fmt.Errorf("could not fetch workflows for %s: %w", ghrepo.FullName(repo), err) } return selectWorkflow(p, workflows, "Select a workflow", states) } workflows, err := FindWorkflow(client, repo, workflowSelector, states) if err != nil { return nil, err } if len(workflows) == 0 { return nil, fmt.Errorf("could not find any workflows named %s", workflowSelector) } if len(workflows) == 1 { return &workflows[0], nil } if !io.CanPrompt() { errMsg := "could not resolve to a unique workflow; found:" for _, workflow := range workflows { errMsg += fmt.Sprintf(" %s", workflow.Base()) } return nil, errors.New(errMsg) } return selectWorkflow(p, workflows, "Which workflow do you mean?", states) } func GetWorkflowContent(client *api.Client, repo ghrepo.Interface, workflow Workflow, ref string) ([]byte, error) { path := fmt.Sprintf("repos/%s/contents/%s", ghrepo.FullName(repo), workflow.Path) if ref != "" { q := fmt.Sprintf("?ref=%s", url.QueryEscape(ref)) path = path + q } type Result struct { Content string } var result Result err := client.REST(repo.RepoHost(), "GET", path, nil, &result) if err != nil { return nil, err } decoded, err := base64.StdEncoding.DecodeString(result.Content) if err != nil { return nil, fmt.Errorf("failed to decode workflow file: %w", err) } sanitized, err := io.ReadAll(transform.NewReader(bytes.NewReader(decoded), &asciisanitizer.Sanitizer{})) if err != nil { return nil, err } return sanitized, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/workflow/shared/test.go
pkg/cmd/workflow/shared/test.go
package shared var AWorkflow = Workflow{ Name: "a workflow", ID: 123, Path: ".github/workflows/flow.yml", State: Active, } var AWorkflowContent = `{"content":"bmFtZTogYSB3b3JrZmxvdwo="}` var DisabledWorkflow = Workflow{ Name: "a disabled workflow", ID: 456, Path: ".github/workflows/disabled.yml", State: DisabledManually, } var DisabledInactivityWorkflow = Workflow{ Name: "a disabled inactivity workflow", ID: 1206, Path: ".github/workflows/disabledInactivity.yml", State: DisabledInactivity, } var AnotherDisabledWorkflow = Workflow{ Name: "a disabled workflow", ID: 1213, Path: ".github/workflows/anotherDisabled.yml", State: DisabledManually, } var UniqueDisabledWorkflow = Workflow{ Name: "terrible workflow", ID: 1314, Path: ".github/workflows/terrible.yml", State: DisabledManually, } var AnotherWorkflow = Workflow{ Name: "another workflow", ID: 789, Path: ".github/workflows/another.yml", State: Active, } var AnotherWorkflowContent = `{"content":"bmFtZTogYW5vdGhlciB3b3JrZmxvdwo="}` var YetAnotherWorkflow = Workflow{ Name: "another workflow", ID: 1011, Path: ".github/workflows/yetanother.yml", State: Active, }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/org/org.go
pkg/cmd/org/org.go
package org import ( "github.com/MakeNowJust/heredoc" orgListCmd "github.com/cli/cli/v2/pkg/cmd/org/list" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/spf13/cobra" ) func NewCmdOrg(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "org <command>", Short: "Manage organizations", Long: "Work with GitHub organizations.", Example: heredoc.Doc(` $ gh org list `), GroupID: "core", } cmdutil.AddGroup(cmd, "General commands", orgListCmd.NewCmdList(f, nil)) return cmd }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/org/list/list_test.go
pkg/cmd/org/list/list_test.go
package list import ( "bytes" "net/http" "testing" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/config" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/stretchr/testify/assert" ) func TestNewCmdList(t *testing.T) { tests := []struct { name string cli string wants ListOptions wantsErr string }{ { name: "no arguments", cli: "", wants: ListOptions{ Limit: 30, }, }, { name: "with limit", cli: "-L 101", wants: ListOptions{ Limit: 101, }, }, { name: "too many arguments", cli: "123 456", wantsErr: "accepts at most 1 arg(s), received 2", }, { name: "invalid limit", cli: "-L 0", wantsErr: "invalid limit: 0", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { f := &cmdutil.Factory{} argv, err := shlex.Split(tt.cli) assert.NoError(t, err) var gotOpts *ListOptions cmd := NewCmdList(f, func(opts *ListOptions) error { gotOpts = opts return nil }) cmd.SetArgs(argv) cmd.SetIn(&bytes.Buffer{}) cmd.SetOut(&bytes.Buffer{}) cmd.SetErr(&bytes.Buffer{}) _, err = cmd.ExecuteC() if tt.wantsErr != "" { assert.EqualError(t, err, tt.wantsErr) return } assert.NoError(t, err) assert.Equal(t, tt.wants.Limit, gotOpts.Limit) }) } } func TestListRun(t *testing.T) { tests := []struct { name string opts ListOptions isTTY bool wantOut string }{ { name: "no organizations found", opts: ListOptions{HttpClient: func() (*http.Client, error) { r := &httpmock.Registry{} r.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data": {"viewer": {"login": "octocat"}}}`)) r.Register( httpmock.GraphQL(`query OrganizationList\b`), httpmock.StringResponse(` { "data": { "user": { "organizations": { "nodes": [], "totalCount": 0 } } } }`, ), ) return &http.Client{Transport: r}, nil }}, isTTY: true, wantOut: heredoc.Doc(` There are no organizations associated with @octocat `), }, { name: "default behavior", opts: ListOptions{HttpClient: func() (*http.Client, error) { r := &httpmock.Registry{} r.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data": {"viewer": {"login": "octocat"}}}`)) r.Register( httpmock.GraphQL(`query OrganizationList\b`), httpmock.StringResponse(` { "data": { "user": { "organizations": { "totalCount": 2, "nodes": [ { "login": "github" }, { "login": "cli" } ] } } } }`, ), ) return &http.Client{Transport: r}, nil }}, isTTY: true, wantOut: heredoc.Doc(` Showing 2 of 2 organizations github cli `), }, { name: "with limit", opts: ListOptions{Limit: 1, HttpClient: func() (*http.Client, error) { r := &httpmock.Registry{} r.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data": {"viewer": {"login": "octocat"}}}`)) r.Register( httpmock.GraphQL(`query OrganizationList\b`), httpmock.StringResponse(` { "data": { "user": { "organizations": { "totalCount": 2, "nodes": [ { "login": "github" }, { "login": "cli" } ] } } } }`, ), ) return &http.Client{Transport: r}, nil }}, isTTY: true, wantOut: heredoc.Doc(` Showing 1 of 2 organizations github `), }, { name: "nontty output", opts: ListOptions{HttpClient: func() (*http.Client, error) { r := &httpmock.Registry{} r.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data": {"viewer": {"login": "octocat"}}}`)) r.Register( httpmock.GraphQL(`query OrganizationList\b`), httpmock.StringResponse(` { "data": { "user": { "organizations": { "totalCount": 2, "nodes": [ { "login": "github" }, { "login": "cli" } ] } } } }`, ), ) return &http.Client{Transport: r}, nil }}, isTTY: false, wantOut: heredoc.Doc(` github cli `), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, stdout, _ := iostreams.Test() 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 } err := listRun(&tt.opts) assert.NoError(t, err) assert.Equal(t, tt.wantOut, stdout.String()) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/org/list/list.go
pkg/cmd/org/list/list.go
package list import ( "fmt" "net/http" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/text" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) type ListOptions struct { IO *iostreams.IOStreams Config func() (gh.Config, error) HttpClient func() (*http.Client, error) Limit int } func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Command { opts := ListOptions{ IO: f.IOStreams, Config: f.Config, HttpClient: f.HttpClient, } cmd := &cobra.Command{ Use: "list", Args: cobra.MaximumNArgs(1), Short: "List organizations for the authenticated user.", Example: heredoc.Doc(` # List the first 30 organizations $ gh org list # List more organizations $ gh org list --limit 100 `), Aliases: []string{"ls"}, RunE: func(cmd *cobra.Command, args []string) error { if opts.Limit < 1 { return cmdutil.FlagErrorf("invalid limit: %v", opts.Limit) } if runF != nil { return runF(&opts) } return listRun(&opts) }, } cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum number of organizations to list") return cmd } func listRun(opts *ListOptions) error { httpClient, err := opts.HttpClient() if err != nil { return err } cfg, err := opts.Config() if err != nil { return err } host, _ := cfg.Authentication().DefaultHost() listResult, err := listOrgs(httpClient, host, opts.Limit) if err != nil { return err } if err := opts.IO.StartPager(); err != nil { fmt.Fprintf(opts.IO.ErrOut, "error starting pager: %v\n", err) } defer opts.IO.StopPager() if opts.IO.IsStdoutTTY() { header := listHeader(listResult.User, len(listResult.Organizations), listResult.TotalCount) fmt.Fprintf(opts.IO.Out, "\n%s\n\n", header) } for _, org := range listResult.Organizations { fmt.Fprintln(opts.IO.Out, org.Login) } return nil } func listHeader(user string, resultCount, totalCount int) string { if totalCount == 0 { return "There are no organizations associated with @" + user } return fmt.Sprintf("Showing %d of %s", resultCount, text.Pluralize(totalCount, "organization")) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/org/list/http_test.go
pkg/cmd/org/list/http_test.go
package list import ( "net/http" "reflect" "testing" "github.com/cli/cli/v2/pkg/httpmock" ) func Test_listOrgs(t *testing.T) { type args struct { limit int } tests := []struct { name string args args httpStub func(*testing.T, *httpmock.Registry) wantErr bool }{ { name: "default", args: args{ limit: 30, }, httpStub: func(t *testing.T, reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data": {"viewer": {"login": "octocat"}}}`)) reg.Register( httpmock.GraphQL(`query OrganizationList\b`), httpmock.GraphQLQuery(`{"data":{}}`, func(query string, vars map[string]interface{}) { want := map[string]interface{}{ "user": "octocat", "limit": float64(30), } if !reflect.DeepEqual(vars, want) { t.Errorf("got GraphQL variables %#v, want %#v", vars, want) } })) }, }, { name: "with limit", args: args{ limit: 1, }, httpStub: func(t *testing.T, r *httpmock.Registry) { r.Register( httpmock.GraphQL(`query UserCurrent\b`), httpmock.StringResponse(`{"data": {"viewer": {"login": "octocat"}}}`)) r.Register( httpmock.GraphQL(`query OrganizationList\b`), httpmock.GraphQLQuery(`{"data":{}}`, func(query string, vars map[string]interface{}) { want := map[string]interface{}{ "user": "octocat", "limit": float64(1), } if !reflect.DeepEqual(vars, want) { t.Errorf("got GraphQL variables %#v, want %#v", vars, want) } })) }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { reg := &httpmock.Registry{} if tt.httpStub != nil { tt.httpStub(t, reg) } httpClient := &http.Client{Transport: reg} _, err := listOrgs(httpClient, "octocat", tt.args.limit) if (err != nil) != tt.wantErr { t.Errorf("listOrgs() error = %v, wantErr %v", err, tt.wantErr) return } }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/org/list/http.go
pkg/cmd/org/list/http.go
package list import ( "net/http" "github.com/cli/cli/v2/api" ) type OrganizationList struct { Organizations []Organization TotalCount int User string } type Organization struct { Login string } func listOrgs(httpClient *http.Client, hostname string, limit int) (*OrganizationList, error) { type response struct { User struct { Login string Organizations struct { TotalCount int Nodes []Organization PageInfo struct { HasNextPage bool EndCursor string } } `graphql:"organizations(first: $limit, after: $endCursor)"` } } query := `query OrganizationList($user: String!, $limit: Int!, $endCursor: String) { user(login: $user) { login organizations(first: $limit, after: $endCursor) { totalCount nodes { login } pageInfo { hasNextPage endCursor } } } }` client := api.NewClientFromHTTP(httpClient) user, err := api.CurrentLoginName(client, hostname) if err != nil { return nil, err } listResult := OrganizationList{} listResult.User = user pageLimit := min(limit, 100) variables := map[string]interface{}{ "user": user, } loop: for { variables["limit"] = pageLimit var data response err := client.GraphQL(hostname, query, variables, &data) if err != nil { return nil, err } listResult.TotalCount = data.User.Organizations.TotalCount for _, org := range data.User.Organizations.Nodes { listResult.Organizations = append(listResult.Organizations, org) if len(listResult.Organizations) == limit { break loop } } if data.User.Organizations.PageInfo.HasNextPage { variables["endCursor"] = data.User.Organizations.PageInfo.EndCursor pageLimit = min(pageLimit, limit-len(listResult.Organizations)) } else { break } } return &listResult, nil } func min(a, b int) int { if a < b { return a } return b }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/factory/remote_resolver.go
pkg/cmd/factory/remote_resolver.go
package factory import ( "errors" "fmt" "sort" "github.com/cli/cli/v2/context" "github.com/cli/cli/v2/git" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghinstance" "github.com/cli/cli/v2/pkg/set" "github.com/cli/go-gh/v2/pkg/ssh" ) const ( GH_HOST = "GH_HOST" ) type remoteResolver struct { readRemotes func() (git.RemoteSet, error) getConfig func() (gh.Config, error) urlTranslator context.Translator cachedRemotes context.Remotes remotesError error } func (rr *remoteResolver) Resolver() func() (context.Remotes, error) { return func() (context.Remotes, error) { if rr.cachedRemotes != nil || rr.remotesError != nil { return rr.cachedRemotes, rr.remotesError } gitRemotes, err := rr.readRemotes() if err != nil { rr.remotesError = err return nil, err } if len(gitRemotes) == 0 { rr.remotesError = errors.New("no git remotes found") return nil, rr.remotesError } sshTranslate := rr.urlTranslator if sshTranslate == nil { sshTranslate = ssh.NewTranslator() } resolvedRemotes := context.TranslateRemotes(gitRemotes, sshTranslate) cfg, err := rr.getConfig() if err != nil { return nil, err } authedHosts := cfg.Authentication().Hosts() if len(authedHosts) == 0 { return nil, errors.New("could not find any host configurations") } defaultHost, src := cfg.Authentication().DefaultHost() // Use set to dedupe list of hosts hostsSet := set.NewStringSet() hostsSet.AddValues(authedHosts) hostsSet.AddValues([]string{defaultHost, ghinstance.Default()}) hosts := hostsSet.ToSlice() // Sort remotes sort.Sort(resolvedRemotes) rr.cachedRemotes = resolvedRemotes.FilterByHosts(hosts) // Filter again by default host if one is set // For config file default host fallback to cachedRemotes if none match // For environment default host (GH_HOST) do not fallback to cachedRemotes if none match if src != "default" { filteredRemotes := rr.cachedRemotes.FilterByHosts([]string{defaultHost}) if isHostEnv(src) || len(filteredRemotes) > 0 { rr.cachedRemotes = filteredRemotes } } if len(rr.cachedRemotes) == 0 { if isHostEnv(src) { rr.remotesError = fmt.Errorf("none of the git remotes configured for this repository correspond to the %s environment variable. Try adding a matching remote or unsetting the variable", src) return nil, rr.remotesError } else if cfg.Authentication().HasEnvToken() { rr.remotesError = errors.New("set the GH_HOST environment variable to specify which GitHub host to use") return nil, rr.remotesError } rr.remotesError = errors.New("none of the git remotes configured for this repository point to a known GitHub host. To tell gh about a new GitHub host, please use `gh auth login`") return nil, rr.remotesError } return rr.cachedRemotes, nil } } func isHostEnv(src string) bool { return src == GH_HOST }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/factory/default.go
pkg/cmd/factory/default.go
package factory import ( "context" "fmt" "net/http" "os" "regexp" "slices" "time" "github.com/cli/cli/v2/api" ghContext "github.com/cli/cli/v2/context" "github.com/cli/cli/v2/git" "github.com/cli/cli/v2/internal/browser" "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/extension" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" xcolor "github.com/cli/go-gh/v2/pkg/x/color" ) var ssoHeader string var ssoURLRE = regexp.MustCompile(`\burl=([^;]+)`) func New(appVersion string) *cmdutil.Factory { f := &cmdutil.Factory{ AppVersion: appVersion, Config: configFunc(), // No factory dependencies ExecutableName: "gh", } f.IOStreams = ioStreams(f) // Depends on Config f.HttpClient = httpClientFunc(f, appVersion) // Depends on Config, IOStreams, and appVersion f.PlainHttpClient = plainHttpClientFunc(f, appVersion) // Depends on IOStreams, and appVersion f.GitClient = newGitClient(f) // Depends on IOStreams, and Executable f.Remotes = remotesFunc(f) // Depends on Config, and GitClient f.BaseRepo = BaseRepoFunc(f) // Depends on Remotes f.Prompter = newPrompter(f) // Depends on Config and IOStreams f.Browser = newBrowser(f) // Depends on Config, and IOStreams f.ExtensionManager = extensionManager(f) // Depends on Config, HttpClient, and IOStreams f.Branch = branchFunc(f) // Depends on GitClient return f } // BaseRepoFunc requests a list of Remotes, and selects the first one. // Although Remotes is injected via the factory so it looks like the function might // be configurable, in practice, it's calling readRemotes, and the injection is indirection. // // readRemotes makes use of the remoteResolver, which is responsible for requesting the list // of remotes for the current working directory from git. It then does some filtering to // only retain remotes for hosts that we have authenticated against; keep in mind this may // be the single value of GH_HOST. // // That list of remotes is sorted by their remote name, in the following order: // 1. upstream // 2. github // 3. origin // 4. other remotes, no ordering guaratanteed because the sort function is not stable // // Given that list, this function chooses the first one. // // Here's a common example of when this might matter: when we clone a fork, by default we add // the parent as a remote named upstream. So the remotes may look like this: // upstream https://github.com/cli/cli.git (fetch) // upstream https://github.com/cli/cli.git (push) // origin https://github.com/cli/cli-fork.git (fetch) // origin https://github.com/cli/cli-fork.git (push) // // With this resolution function, the upstream will always be chosen (assuming we have authenticated with github.com). func BaseRepoFunc(f *cmdutil.Factory) func() (ghrepo.Interface, error) { return func() (ghrepo.Interface, error) { remotes, err := f.Remotes() if err != nil { return nil, err } return remotes[0], nil } } // SmartBaseRepoFunc provides additional behaviour over BaseRepoFunc. Read the BaseRepoFunc // documentation for more information on how remotes are fetched and ordered. // // Unlike BaseRepoFunc, instead of selecting the first remote in the list, this function will // use the API to resolve repository networks, and attempt to use the `resolved` git remote config value // as part of determining the base repository. // // Although the behaviour commented below really belongs to the `BaseRepo` function on `ResolvedRemotes`, // in practice the most important place to understand the general behaviour is here, so that's where // I'm going to write it. // // Firstly, the remotes are inspected to see whether any are already resolved. Resolution means the git // config value of the `resolved` key was `base` (meaning this remote is the base repository), or a specific // repository e.g. `cli/cli` (meaning that specific repo is the base repo, regardless of whether a remote // exists for it). These values are set by default on clone of a fork, or by running `repo set-default`. If // either are set, that repository is returned. // // If we the current invocation is unable to prompt, then the first remote is returned. I believe this behaviour // exists for backwards compatibility before the later steps were introduced, however, this is frequently a source // of differing behaviour between interactive and non-interactive invocations: // // ➜ git remote -v // origin https://github.com/williammartin/test-repo.git (fetch) // origin https://github.com/williammartin/test-repo.git (push) // upstream https://github.com/williammartin-test-org/test-repo.git (fetch) // upstream https://github.com/williammartin-test-org/test-repo.git (push) // // ➜ gh pr list // X No default remote repository has been set for this directory. // // please run `gh repo set-default` to select a default remote repository. // ➜ gh pr list | cat // 3 test williammartin-test-org:remote-push-default-feature OPEN 2024-12-13T10:28:40Z // // Furthermore, when repositories have been renamed on the server and not on the local git remote, this causes // even more confusion because the API requests can be different, and FURTHERMORE this can be an issue for // services that don't handle renames correctly, like the ElasticSearch indexing. // // Assuming we have an interactive invocation, then the next step is to resolve a network of repositories. This // involves creating a dynamic GQL query requesting information about each repository (up to a limit of 5). // Each returned repo is added to a list, along with its parent, if present in the query response. // The repositories in the query retain the same ordering as previously outlined. Interestingly, the request is sent // to the hostname of the first repo, so if you happen to have remotes on different GitHub hosts, then they won't // resolve correctly. I'm not sure this has ever caused an issue, but does seem like a potential source of bugs. // In practice, since the remotes are ordered with upstream, github, origin before others, it's almost always going // to be the case that the correct host is chosen. // // Because fetching the network includes the parent repo, even if it is not a remote, this requires the user to // disambiguate, which can be surprising, though I'm not sure I've heard anyone complain: // // ➜ git remote -v // origin https://github.com/williammartin/test-repo.git (fetch) // origin https://github.com/williammartin/test-repo.git (push) // // ➜ gh pr list // X No default remote repository has been set for this directory. // // please run `gh repo set-default` to select a default remote repository. // // If no repos are returned from the API then we return the first remote from the original list. I'm not sure // why we do this rather than erroring, because it seems like almost every future step is going to fail when hitting // the API. Potentially it helps if there is an API blip? It was added without comment in: // https://github.com/cli/cli/pull/1706/files#diff-65730f0373fb91dd749940cf09daeaf884e5643d665a6c3eb09d54785a6d475eR113 // // If one repo is returned from the API, then that one is returned as the base repo. // // If more than one repo is returned from the API, we indicate to the user that they need to run `repo set-default`, // and return an error with no base repo. func SmartBaseRepoFunc(f *cmdutil.Factory) func() (ghrepo.Interface, error) { return func() (ghrepo.Interface, error) { httpClient, err := f.HttpClient() if err != nil { return nil, err } apiClient := api.NewClientFromHTTP(httpClient) remotes, err := f.Remotes() if err != nil { return nil, err } resolvedRepos, err := ghContext.ResolveRemotesToRepos(remotes, apiClient, "") if err != nil { return nil, err } baseRepo, err := resolvedRepos.BaseRepo(f.IOStreams) if err != nil { return nil, err } return baseRepo, nil } } func remotesFunc(f *cmdutil.Factory) func() (ghContext.Remotes, error) { rr := &remoteResolver{ readRemotes: func() (git.RemoteSet, error) { return f.GitClient.Remotes(context.Background()) }, getConfig: f.Config, } return rr.Resolver() } func httpClientFunc(f *cmdutil.Factory, appVersion string) func() (*http.Client, error) { return func() (*http.Client, error) { io := f.IOStreams cfg, err := f.Config() if err != nil { return nil, err } opts := api.HTTPClientOptions{ Config: cfg.Authentication(), Log: io.ErrOut, LogColorize: io.ColorEnabled(), AppVersion: appVersion, } client, err := api.NewHTTPClient(opts) if err != nil { return nil, err } client.Transport = api.ExtractHeader("X-GitHub-SSO", &ssoHeader)(client.Transport) return client, nil } } func plainHttpClientFunc(f *cmdutil.Factory, appVersion string) func() (*http.Client, error) { return func() (*http.Client, error) { io := f.IOStreams opts := api.HTTPClientOptions{ Log: io.ErrOut, LogColorize: io.ColorEnabled(), AppVersion: appVersion, // This is required to prevent automatic setting of auth and other headers. SkipDefaultHeaders: true, } client, err := api.NewHTTPClient(opts) if err != nil { return nil, err } return client, nil } } func newGitClient(f *cmdutil.Factory) *git.Client { io := f.IOStreams ghPath := f.Executable() client := &git.Client{ GhPath: ghPath, Stderr: io.ErrOut, Stdin: io.In, Stdout: io.Out, } return client } func newBrowser(f *cmdutil.Factory) browser.Browser { io := f.IOStreams return browser.New("", io.Out, io.ErrOut) } func newPrompter(f *cmdutil.Factory) prompter.Prompter { editor, _ := cmdutil.DetermineEditor(f.Config) io := f.IOStreams return prompter.New(editor, io) } func configFunc() func() (gh.Config, error) { var cachedConfig gh.Config var configError error return func() (gh.Config, error) { if cachedConfig != nil || configError != nil { return cachedConfig, configError } cachedConfig, configError = config.NewConfig() return cachedConfig, configError } } func branchFunc(f *cmdutil.Factory) func() (string, error) { return func() (string, error) { currentBranch, err := f.GitClient.CurrentBranch(context.Background()) if err != nil { return "", fmt.Errorf("could not determine current branch: %w", err) } return currentBranch, nil } } func extensionManager(f *cmdutil.Factory) *extension.Manager { em := extension.NewManager(f.IOStreams, f.GitClient) cfg, err := f.Config() if err != nil { return em } em.SetConfig(cfg) client, err := f.HttpClient() if err != nil { return em } em.SetClient(api.NewCachedHTTPClient(client, time.Second*30)) return em } func ioStreams(f *cmdutil.Factory) *iostreams.IOStreams { io := iostreams.System() cfg, err := f.Config() if err != nil { return io } if _, ghPromptDisabled := os.LookupEnv("GH_PROMPT_DISABLED"); ghPromptDisabled { io.SetNeverPrompt(true) } else if prompt := cfg.Prompt(""); prompt.Value == "disabled" { io.SetNeverPrompt(true) } falseyValues := []string{"false", "0", "no", ""} accessiblePrompterValue, accessiblePrompterIsSet := os.LookupEnv("GH_ACCESSIBLE_PROMPTER") if accessiblePrompterIsSet { if !slices.Contains(falseyValues, accessiblePrompterValue) { io.SetAccessiblePrompterEnabled(true) } } else if prompt := cfg.AccessiblePrompter(""); prompt.Value == "enabled" { io.SetAccessiblePrompterEnabled(true) } ghSpinnerDisabledValue, ghSpinnerDisabledIsSet := os.LookupEnv("GH_SPINNER_DISABLED") if ghSpinnerDisabledIsSet { if !slices.Contains(falseyValues, ghSpinnerDisabledValue) { io.SetSpinnerDisabled(true) } } else if spinnerDisabled := cfg.Spinner(""); spinnerDisabled.Value == "disabled" { io.SetSpinnerDisabled(true) } // Pager precedence // 1. GH_PAGER // 2. pager from config // 3. PAGER if ghPager, ghPagerExists := os.LookupEnv("GH_PAGER"); ghPagerExists { io.SetPager(ghPager) } else if pager := cfg.Pager(""); pager.Value != "" { io.SetPager(pager.Value) } if ghColorLabels, ghColorLabelsExists := os.LookupEnv("GH_COLOR_LABELS"); ghColorLabelsExists { switch ghColorLabels { case "", "0", "false", "no": io.SetColorLabels(false) default: io.SetColorLabels(true) } } else if prompt := cfg.ColorLabels(""); prompt.Value == "enabled" { io.SetColorLabels(true) } io.SetAccessibleColorsEnabled(xcolor.IsAccessibleColorsEnabled()) return io } // SSOURL returns the URL of a SAML SSO challenge received by the server for clients that use ExtractHeader // to extract the value of the "X-GitHub-SSO" response header. func SSOURL() string { if ssoHeader == "" { return "" } m := ssoURLRE.FindStringSubmatch(ssoHeader) if m == nil { return "" } return m[1] }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/factory/default_test.go
pkg/cmd/factory/default_test.go
package factory import ( "net/http" "net/http/httptest" "net/url" "path/filepath" "testing" "github.com/cli/cli/v2/git" "github.com/cli/cli/v2/internal/config" "github.com/cli/cli/v2/internal/gh" ghmock "github.com/cli/cli/v2/internal/gh/mock" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/httpmock" "github.com/cli/cli/v2/pkg/iostreams" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func Test_BaseRepo(t *testing.T) { tests := []struct { name string remotes git.RemoteSet override string wantsErr bool wantsName string wantsOwner string wantsHost string }{ { name: "matching remote", remotes: git.RemoteSet{ git.NewRemote("origin", "https://nonsense.com/owner/repo.git"), }, wantsName: "repo", wantsOwner: "owner", wantsHost: "nonsense.com", }, { name: "no matching remote", remotes: git.RemoteSet{ git.NewRemote("origin", "https://test.com/owner/repo.git"), }, wantsErr: true, }, { name: "override with matching remote", remotes: git.RemoteSet{ git.NewRemote("origin", "https://test.com/owner/repo.git"), }, override: "test.com", wantsName: "repo", wantsOwner: "owner", wantsHost: "test.com", }, { name: "override with no matching remote", remotes: git.RemoteSet{ git.NewRemote("origin", "https://nonsense.com/owner/repo.git"), }, override: "test.com", wantsErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { f := New("1") rr := &remoteResolver{ readRemotes: func() (git.RemoteSet, error) { return tt.remotes, nil }, getConfig: func() (gh.Config, error) { cfg := &ghmock.ConfigMock{} cfg.AuthenticationFunc = func() gh.AuthConfig { authCfg := &config.AuthConfig{} hosts := []string{"nonsense.com"} if tt.override != "" { hosts = append([]string{tt.override}, hosts...) } authCfg.SetHosts(hosts) authCfg.SetActiveToken("", "") authCfg.SetDefaultHost("nonsense.com", "hosts") if tt.override != "" { authCfg.SetDefaultHost(tt.override, "GH_HOST") } return authCfg } return cfg, nil }, } f.Remotes = rr.Resolver() f.BaseRepo = BaseRepoFunc(f) repo, err := f.BaseRepo() if tt.wantsErr { assert.Error(t, err) return } assert.NoError(t, err) assert.Equal(t, tt.wantsName, repo.RepoName()) assert.Equal(t, tt.wantsOwner, repo.RepoOwner()) assert.Equal(t, tt.wantsHost, repo.RepoHost()) }) } } func Test_SmartBaseRepo(t *testing.T) { pu, _ := url.Parse("https://test.com/newowner/newrepo.git") tests := []struct { name string remotes git.RemoteSet override string wantsErr bool wantsName string wantsOwner string wantsHost string tty bool httpStubs func(*httpmock.Registry) }{ { name: "override with matching remote", remotes: git.RemoteSet{ git.NewRemote("origin", "https://test.com/owner/repo.git"), }, override: "test.com", wantsName: "repo", wantsOwner: "owner", wantsHost: "test.com", }, { name: "override with matching remote and base resolution", remotes: git.RemoteSet{ &git.Remote{Name: "origin", Resolved: "base", FetchURL: pu, PushURL: pu}, }, override: "test.com", wantsName: "newrepo", wantsOwner: "newowner", wantsHost: "test.com", }, { name: "override with matching remote and nonbase resolution", remotes: git.RemoteSet{ &git.Remote{Name: "origin", Resolved: "johnny/test", FetchURL: pu, PushURL: pu}, }, override: "test.com", wantsName: "test", wantsOwner: "johnny", wantsHost: "test.com", }, { name: "override with no matching remote", remotes: git.RemoteSet{ git.NewRemote("origin", "https://example.com/owner/repo.git"), }, override: "test.com", wantsErr: true, }, { name: "only one remote", remotes: git.RemoteSet{ git.NewRemote("origin", "https://github.com/owner/repo.git"), }, wantsName: "repo", wantsOwner: "owner", wantsHost: "github.com", tty: true, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL("RepositoryNetwork"), httpmock.StringResponse(` { "data": { "viewer": { "login": "someone" }, "repo_000": { "id": "MDEwOlJlcG9zaXRvcnkxMDM3MjM2Mjc=", "name": "repo", "owner": { "login": "owner" }, "viewerPermission": "READ", "defaultBranchRef": { "name": "master" }, "isPrivate": false, "parent": null } } } `)) }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { f := New("1") rr := &remoteResolver{ readRemotes: func() (git.RemoteSet, error) { return tt.remotes, nil }, getConfig: func() (gh.Config, error) { cfg := &ghmock.ConfigMock{} cfg.AuthenticationFunc = func() gh.AuthConfig { authCfg := &config.AuthConfig{} hosts := []string{"nonsense.com"} if tt.override != "" { hosts = append([]string{tt.override}, hosts...) } authCfg.SetHosts(hosts) authCfg.SetActiveToken("", "") authCfg.SetDefaultHost("nonsense.com", "hosts") if tt.override != "" { authCfg.SetDefaultHost(tt.override, "GH_HOST") } return authCfg } return cfg, nil }, } reg := &httpmock.Registry{} defer reg.Verify(t) ios, _, _, _ := iostreams.Test() ios.SetStdinTTY(tt.tty) ios.SetStdoutTTY(tt.tty) if tt.httpStubs != nil { tt.httpStubs(reg) } f.IOStreams = ios f.HttpClient = func() (*http.Client, error) { return &http.Client{Transport: reg}, nil } f.Remotes = rr.Resolver() f.BaseRepo = SmartBaseRepoFunc(f) repo, err := f.BaseRepo() if tt.wantsErr { assert.Error(t, err) return } assert.NoError(t, err) assert.Equal(t, tt.wantsName, repo.RepoName()) assert.Equal(t, tt.wantsOwner, repo.RepoOwner()) assert.Equal(t, tt.wantsHost, repo.RepoHost()) }) } } // Defined in pkg/cmdutil/repo_override.go but test it along with other BaseRepo functions func Test_OverrideBaseRepo(t *testing.T) { tests := []struct { name string remotes git.RemoteSet config gh.Config envOverride string argOverride string wantsErr bool wantsName string wantsOwner string wantsHost string }{ { name: "override from argument", argOverride: "override/test", wantsHost: "github.com", wantsOwner: "override", wantsName: "test", }, { name: "override from environment", envOverride: "somehost.com/override/test", wantsHost: "somehost.com", wantsOwner: "override", wantsName: "test", }, { name: "no override", remotes: git.RemoteSet{ git.NewRemote("origin", "https://nonsense.com/owner/repo.git"), }, config: defaultConfig(), wantsHost: "nonsense.com", wantsOwner: "owner", wantsName: "repo", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if tt.envOverride != "" { t.Setenv("GH_REPO", tt.envOverride) } f := New("1") rr := &remoteResolver{ readRemotes: func() (git.RemoteSet, error) { return tt.remotes, nil }, getConfig: func() (gh.Config, error) { return tt.config, nil }, } f.Remotes = rr.Resolver() f.BaseRepo = cmdutil.OverrideBaseRepoFunc(f, tt.argOverride) repo, err := f.BaseRepo() if tt.wantsErr { assert.Error(t, err) return } assert.NoError(t, err) assert.Equal(t, tt.wantsName, repo.RepoName()) assert.Equal(t, tt.wantsOwner, repo.RepoOwner()) assert.Equal(t, tt.wantsHost, repo.RepoHost()) }) } } func Test_ioStreams_pager(t *testing.T) { tests := []struct { name string env map[string]string config gh.Config wantPager string }{ { name: "GH_PAGER and PAGER set", env: map[string]string{ "GH_PAGER": "GH_PAGER", "PAGER": "PAGER", }, wantPager: "GH_PAGER", }, { name: "GH_PAGER and config pager set", env: map[string]string{ "GH_PAGER": "GH_PAGER", }, config: pagerConfig(), wantPager: "GH_PAGER", }, { name: "config pager and PAGER set", env: map[string]string{ "PAGER": "PAGER", }, config: pagerConfig(), wantPager: "CONFIG_PAGER", }, { name: "only PAGER set", env: map[string]string{ "PAGER": "PAGER", }, wantPager: "PAGER", }, { name: "GH_PAGER set to blank string", env: map[string]string{ "GH_PAGER": "", "PAGER": "PAGER", }, wantPager: "", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if tt.env != nil { for k, v := range tt.env { t.Setenv(k, v) } } f := New("1") f.Config = func() (gh.Config, error) { if tt.config == nil { return config.NewBlankConfig(), nil } else { return tt.config, nil } } io := ioStreams(f) assert.Equal(t, tt.wantPager, io.GetPager()) }) } } func Test_ioStreams_prompt(t *testing.T) { tests := []struct { name string config gh.Config promptDisabled bool env map[string]string }{ { name: "default config", promptDisabled: false, }, { name: "config with prompt disabled", config: disablePromptConfig(), promptDisabled: true, }, { name: "prompt disabled via GH_PROMPT_DISABLED env var", env: map[string]string{"GH_PROMPT_DISABLED": "1"}, promptDisabled: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if tt.env != nil { for k, v := range tt.env { t.Setenv(k, v) } } f := New("1") f.Config = func() (gh.Config, error) { if tt.config == nil { return config.NewBlankConfig(), nil } else { return tt.config, nil } } io := ioStreams(f) assert.Equal(t, tt.promptDisabled, io.GetNeverPrompt()) }) } } func Test_ioStreams_spinnerDisabled(t *testing.T) { tests := []struct { name string config gh.Config spinnerDisabled bool env map[string]string }{ { name: "default config", spinnerDisabled: false, }, { name: "config with spinner disabled", config: disableSpinnersConfig(), spinnerDisabled: true, }, { name: "config with spinner enabled", config: enableSpinnersConfig(), spinnerDisabled: false, }, { name: "spinner disabled via GH_SPINNER_DISABLED env var = 0", env: map[string]string{"GH_SPINNER_DISABLED": "0"}, spinnerDisabled: false, }, { name: "spinner disabled via GH_SPINNER_DISABLED env var = false", env: map[string]string{"GH_SPINNER_DISABLED": "false"}, spinnerDisabled: false, }, { name: "spinner disabled via GH_SPINNER_DISABLED env var = no", env: map[string]string{"GH_SPINNER_DISABLED": "no"}, spinnerDisabled: false, }, { name: "spinner enabled via GH_SPINNER_DISABLED env var = 1", env: map[string]string{"GH_SPINNER_DISABLED": "1"}, spinnerDisabled: true, }, { name: "spinner enabled via GH_SPINNER_DISABLED env var = true", env: map[string]string{"GH_SPINNER_DISABLED": "true"}, spinnerDisabled: true, }, { name: "config enabled but env disabled, respects env", config: enableSpinnersConfig(), env: map[string]string{"GH_SPINNER_DISABLED": "true"}, spinnerDisabled: true, }, { name: "config disabled but env enabled, respects env", config: disableSpinnersConfig(), env: map[string]string{"GH_SPINNER_DISABLED": "false"}, spinnerDisabled: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { for k, v := range tt.env { t.Setenv(k, v) } f := New("1") f.Config = func() (gh.Config, error) { if tt.config == nil { return config.NewBlankConfig(), nil } else { return tt.config, nil } } io := ioStreams(f) assert.Equal(t, tt.spinnerDisabled, io.GetSpinnerDisabled()) }) } } func Test_ioStreams_accessiblePrompterEnabled(t *testing.T) { tests := []struct { name string config gh.Config accessiblePrompterEnabled bool env map[string]string }{ { name: "default config", accessiblePrompterEnabled: false, }, { name: "config with accessible prompter enabled", config: enableAccessiblePrompterConfig(), accessiblePrompterEnabled: true, }, { name: "config with accessible prompter disabled", config: disableAccessiblePrompterConfig(), accessiblePrompterEnabled: false, }, { name: "accessible prompter enabled via GH_ACCESSIBLE_PROMPTER env var = 1", env: map[string]string{"GH_ACCESSIBLE_PROMPTER": "1"}, accessiblePrompterEnabled: true, }, { name: "accessible prompter enabled via GH_ACCESSIBLE_PROMPTER env var = true", env: map[string]string{"GH_ACCESSIBLE_PROMPTER": "true"}, accessiblePrompterEnabled: true, }, { name: "accessible prompter disabled via GH_ACCESSIBLE_PROMPTER env var = 0", env: map[string]string{"GH_ACCESSIBLE_PROMPTER": "0"}, accessiblePrompterEnabled: false, }, { name: "config disabled but env enabled, respects env", config: disableAccessiblePrompterConfig(), env: map[string]string{"GH_ACCESSIBLE_PROMPTER": "true"}, accessiblePrompterEnabled: true, }, { name: "config enabled but env disabled, respects env", config: enableAccessiblePrompterConfig(), env: map[string]string{"GH_ACCESSIBLE_PROMPTER": "false"}, accessiblePrompterEnabled: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { for k, v := range tt.env { t.Setenv(k, v) } f := New("1") f.Config = func() (gh.Config, error) { if tt.config == nil { return config.NewBlankConfig(), nil } else { return tt.config, nil } } io := ioStreams(f) assert.Equal(t, tt.accessiblePrompterEnabled, io.AccessiblePrompterEnabled()) }) } } func Test_ioStreams_colorLabels(t *testing.T) { tests := []struct { name string config gh.Config colorLabelsEnabled bool env map[string]string }{ { name: "default config", colorLabelsEnabled: false, }, { name: "config with colorLabels enabled", config: enableColorLabelsConfig(), colorLabelsEnabled: true, }, { name: "config with colorLabels disabled", config: disableColorLabelsConfig(), colorLabelsEnabled: false, }, { name: "colorLabels enabled via `1` in GH_COLOR_LABELS env var", env: map[string]string{"GH_COLOR_LABELS": "1"}, colorLabelsEnabled: true, }, { name: "colorLabels enabled via `true` in GH_COLOR_LABELS env var", env: map[string]string{"GH_COLOR_LABELS": "true"}, colorLabelsEnabled: true, }, { name: "colorLabels enabled via `yes` in GH_COLOR_LABELS env var", env: map[string]string{"GH_COLOR_LABELS": "yes"}, colorLabelsEnabled: true, }, { name: "colorLabels disable via empty string in GH_COLOR_LABELS env var", env: map[string]string{"GH_COLOR_LABELS": ""}, colorLabelsEnabled: false, }, { name: "colorLabels disabled via `0` in GH_COLOR_LABELS env var", env: map[string]string{"GH_COLOR_LABELS": "0"}, colorLabelsEnabled: false, }, { name: "colorLabels disabled via `false` in GH_COLOR_LABELS env var", env: map[string]string{"GH_COLOR_LABELS": "false"}, colorLabelsEnabled: false, }, { name: "colorLabels disabled via `no` in GH_COLOR_LABELS env var", env: map[string]string{"GH_COLOR_LABELS": "no"}, colorLabelsEnabled: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if tt.env != nil { for k, v := range tt.env { t.Setenv(k, v) } } f := New("1") f.Config = func() (gh.Config, error) { if tt.config == nil { return config.NewBlankConfig(), nil } else { return tt.config, nil } } io := ioStreams(f) assert.Equal(t, tt.colorLabelsEnabled, io.ColorLabels()) }) } } func TestSSOURL(t *testing.T) { tests := []struct { name string host string sso string wantStderr string wantSSO string }{ { name: "SSO challenge in response header", host: "github.com", sso: "required; url=https://github.com/login/sso?return_to=xyz&param=123abc; another", wantStderr: "", wantSSO: "https://github.com/login/sso?return_to=xyz&param=123abc", }, } ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if sso := r.URL.Query().Get("sso"); sso != "" { w.Header().Set("X-GitHub-SSO", sso) } w.WriteHeader(http.StatusNoContent) })) defer ts.Close() for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { f := New("1") f.Config = func() (gh.Config, error) { return config.NewBlankConfig(), nil } ios, _, _, stderr := iostreams.Test() f.IOStreams = ios client, err := httpClientFunc(f, "v1.2.3")() require.NoError(t, err) req, err := http.NewRequest("GET", ts.URL, nil) if tt.sso != "" { q := req.URL.Query() q.Set("sso", tt.sso) req.URL.RawQuery = q.Encode() } req.Host = tt.host require.NoError(t, err) res, err := client.Do(req) require.NoError(t, err) assert.Equal(t, 204, res.StatusCode) assert.Equal(t, tt.wantStderr, stderr.String()) assert.Equal(t, tt.wantSSO, SSOURL()) }) } } func TestPlainHttpClient(t *testing.T) { var receivedHeaders *http.Header ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { receivedHeaders = &r.Header w.WriteHeader(http.StatusNoContent) })) defer ts.Close() f := New("1") f.Config = func() (gh.Config, error) { return config.NewBlankConfig(), nil } ios, _, _, _ := iostreams.Test() f.IOStreams = ios client, err := plainHttpClientFunc(f, "v1.2.3")() require.NoError(t, err) req, err := http.NewRequest("GET", ts.URL, nil) require.NoError(t, err) res, err := client.Do(req) require.NoError(t, err) assert.Equal(t, 204, res.StatusCode) assert.Equal(t, []string{"GitHub CLI v1.2.3"}, receivedHeaders.Values("User-Agent")) assert.Nil(t, receivedHeaders.Values("Authorization")) assert.Nil(t, receivedHeaders.Values("Content-Type")) assert.Nil(t, receivedHeaders.Values("Accept")) assert.Nil(t, receivedHeaders.Values("Time-Zone")) } func TestNewGitClient(t *testing.T) { tests := []struct { name string config gh.Config executable string wantAuthHosts []string wantGhPath string }{ { name: "creates git client", config: defaultConfig(), executable: filepath.Join("path", "to", "gh"), wantAuthHosts: []string{"nonsense.com"}, wantGhPath: filepath.Join("path", "to", "gh"), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { f := New("1") f.Config = func() (gh.Config, error) { if tt.config == nil { return config.NewBlankConfig(), nil } else { return tt.config, nil } } f.ExecutableName = tt.executable ios, _, _, _ := iostreams.Test() f.IOStreams = ios c := newGitClient(f) assert.Equal(t, tt.wantGhPath, c.GhPath) assert.Equal(t, ios.In, c.Stdin) assert.Equal(t, ios.Out, c.Stdout) assert.Equal(t, ios.ErrOut, c.Stderr) }) } } func defaultConfig() *ghmock.ConfigMock { cfg := config.NewFromString("") cfg.Set("nonsense.com", "oauth_token", "BLAH") return cfg } func pagerConfig() gh.Config { return config.NewFromString("pager: CONFIG_PAGER") } func disablePromptConfig() gh.Config { return config.NewFromString("prompt: disabled") } func enableAccessiblePrompterConfig() gh.Config { return config.NewFromString("accessible_prompter: enabled") } func disableAccessiblePrompterConfig() gh.Config { return config.NewFromString("accessible_prompter: disabled") } func disableSpinnersConfig() gh.Config { return config.NewFromString("spinner: disabled") } func enableSpinnersConfig() gh.Config { return config.NewFromString("spinner: enabled") } func disableColorLabelsConfig() gh.Config { return config.NewFromString("color_labels: disabled") } func enableColorLabelsConfig() gh.Config { return config.NewFromString("color_labels: enabled") }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/factory/remote_resolver_test.go
pkg/cmd/factory/remote_resolver_test.go
package factory import ( "errors" "net/url" "testing" "github.com/cli/cli/v2/context" "github.com/cli/cli/v2/git" "github.com/cli/cli/v2/internal/config" "github.com/cli/cli/v2/internal/gh" ghmock "github.com/cli/cli/v2/internal/gh/mock" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) type identityTranslator struct{} func (it identityTranslator) Translate(u *url.URL) *url.URL { return u } func Test_remoteResolver(t *testing.T) { tests := []struct { name string remotes func() (git.RemoteSet, error) config gh.Config output []string wantsErr bool }{ { name: "no authenticated hosts", remotes: func() (git.RemoteSet, error) { return git.RemoteSet{ git.NewRemote("origin", "https://github.com/owner/repo.git"), }, nil }, config: func() gh.Config { cfg := &ghmock.ConfigMock{} cfg.AuthenticationFunc = func() gh.AuthConfig { authCfg := &config.AuthConfig{} authCfg.SetHosts([]string{}) authCfg.SetDefaultHost("github.com", "default") return authCfg } return cfg }(), wantsErr: true, }, { name: "no git remotes", remotes: func() (git.RemoteSet, error) { return git.RemoteSet{}, nil }, config: func() gh.Config { cfg := &ghmock.ConfigMock{} cfg.AuthenticationFunc = func() gh.AuthConfig { authCfg := &config.AuthConfig{} authCfg.SetHosts([]string{"example.com"}) authCfg.SetDefaultHost("example.com", "hosts") return authCfg } return cfg }(), wantsErr: true, }, { name: "one authenticated host with no matching git remote and no fallback remotes", remotes: func() (git.RemoteSet, error) { return git.RemoteSet{ git.NewRemote("origin", "https://test.com/owner/repo.git"), }, nil }, config: func() gh.Config { cfg := &ghmock.ConfigMock{} cfg.AuthenticationFunc = func() gh.AuthConfig { authCfg := &config.AuthConfig{} authCfg.SetHosts([]string{"example.com"}) authCfg.SetActiveToken("", "") authCfg.SetDefaultHost("example.com", "hosts") return authCfg } return cfg }(), wantsErr: true, }, { name: "one authenticated host with no matching git remote and fallback remotes", remotes: func() (git.RemoteSet, error) { return git.RemoteSet{ git.NewRemote("origin", "https://github.com/owner/repo.git"), }, nil }, config: func() gh.Config { cfg := &ghmock.ConfigMock{} cfg.AuthenticationFunc = func() gh.AuthConfig { authCfg := &config.AuthConfig{} authCfg.SetHosts([]string{"example.com"}) authCfg.SetDefaultHost("example.com", "hosts") return authCfg } return cfg }(), output: []string{"origin"}, }, { name: "one authenticated host with matching git remote", remotes: func() (git.RemoteSet, error) { return git.RemoteSet{ git.NewRemote("origin", "https://example.com/owner/repo.git"), }, nil }, config: func() gh.Config { cfg := &ghmock.ConfigMock{} cfg.AuthenticationFunc = func() gh.AuthConfig { authCfg := &config.AuthConfig{} authCfg.SetHosts([]string{"example.com"}) authCfg.SetDefaultHost("example.com", "default") return authCfg } return cfg }(), output: []string{"origin"}, }, { name: "one authenticated host with multiple matching git remotes", remotes: func() (git.RemoteSet, error) { return git.RemoteSet{ git.NewRemote("upstream", "https://example.com/owner/repo.git"), git.NewRemote("github", "https://example.com/owner/repo.git"), git.NewRemote("origin", "https://example.com/owner/repo.git"), git.NewRemote("fork", "https://example.com/owner/repo.git"), }, nil }, config: func() gh.Config { cfg := &ghmock.ConfigMock{} cfg.AuthenticationFunc = func() gh.AuthConfig { authCfg := &config.AuthConfig{} authCfg.SetHosts([]string{"example.com"}) authCfg.SetDefaultHost("example.com", "default") return authCfg } return cfg }(), output: []string{"upstream", "github", "origin", "fork"}, }, { name: "multiple authenticated hosts with no matching git remote", remotes: func() (git.RemoteSet, error) { return git.RemoteSet{ git.NewRemote("origin", "https://test.com/owner/repo.git"), }, nil }, config: func() gh.Config { cfg := &ghmock.ConfigMock{} cfg.AuthenticationFunc = func() gh.AuthConfig { authCfg := &config.AuthConfig{} authCfg.SetHosts([]string{"example.com", "github.com"}) authCfg.SetActiveToken("", "") authCfg.SetDefaultHost("example.com", "default") return authCfg } return cfg }(), wantsErr: true, }, { name: "multiple authenticated hosts with one matching git remote", remotes: func() (git.RemoteSet, error) { return git.RemoteSet{ git.NewRemote("upstream", "https://test.com/owner/repo.git"), git.NewRemote("origin", "https://example.com/owner/repo.git"), }, nil }, config: func() gh.Config { cfg := &ghmock.ConfigMock{} cfg.AuthenticationFunc = func() gh.AuthConfig { authCfg := &config.AuthConfig{} authCfg.SetHosts([]string{"example.com", "github.com"}) authCfg.SetDefaultHost("github.com", "default") return authCfg } return cfg }(), output: []string{"origin"}, }, { name: "multiple authenticated hosts with multiple matching git remotes", remotes: func() (git.RemoteSet, error) { return git.RemoteSet{ git.NewRemote("upstream", "https://example.com/owner/repo.git"), git.NewRemote("github", "https://github.com/owner/repo.git"), git.NewRemote("origin", "https://example.com/owner/repo.git"), git.NewRemote("fork", "https://github.com/owner/repo.git"), git.NewRemote("test", "https://test.com/owner/repo.git"), }, nil }, config: func() gh.Config { cfg := &ghmock.ConfigMock{} cfg.AuthenticationFunc = func() gh.AuthConfig { authCfg := &config.AuthConfig{} authCfg.SetHosts([]string{"example.com", "github.com"}) authCfg.SetDefaultHost("github.com", "default") return authCfg } return cfg }(), output: []string{"upstream", "github", "origin", "fork"}, }, { name: "override host with no matching git remotes", remotes: func() (git.RemoteSet, error) { return git.RemoteSet{ git.NewRemote("origin", "https://example.com/owner/repo.git"), }, nil }, config: func() gh.Config { cfg := &ghmock.ConfigMock{} cfg.AuthenticationFunc = func() gh.AuthConfig { authCfg := &config.AuthConfig{} authCfg.SetHosts([]string{"example.com"}) authCfg.SetDefaultHost("test.com", "GH_HOST") return authCfg } return cfg }(), wantsErr: true, }, { name: "override host with one matching git remote", remotes: func() (git.RemoteSet, error) { return git.RemoteSet{ git.NewRemote("upstream", "https://example.com/owner/repo.git"), git.NewRemote("origin", "https://test.com/owner/repo.git"), }, nil }, config: func() gh.Config { cfg := &ghmock.ConfigMock{} cfg.AuthenticationFunc = func() gh.AuthConfig { authCfg := &config.AuthConfig{} authCfg.SetHosts([]string{"example.com"}) authCfg.SetDefaultHost("test.com", "GH_HOST") return authCfg } return cfg }(), output: []string{"origin"}, }, { name: "override host with multiple matching git remotes", remotes: func() (git.RemoteSet, error) { return git.RemoteSet{ git.NewRemote("upstream", "https://test.com/owner/repo.git"), git.NewRemote("github", "https://example.com/owner/repo.git"), git.NewRemote("origin", "https://test.com/owner/repo.git"), }, nil }, config: func() gh.Config { cfg := &ghmock.ConfigMock{} cfg.AuthenticationFunc = func() gh.AuthConfig { authCfg := &config.AuthConfig{} authCfg.SetHosts([]string{"example.com", "test.com"}) authCfg.SetDefaultHost("test.com", "GH_HOST") return authCfg } return cfg }(), output: []string{"upstream", "origin"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { rr := &remoteResolver{ readRemotes: tt.remotes, getConfig: func() (gh.Config, error) { return tt.config, nil }, urlTranslator: identityTranslator{}, } resolver := rr.Resolver() remotes, err := resolver() if tt.wantsErr { assert.Error(t, err) return } assert.NoError(t, err) names := []string{} for _, r := range remotes { names = append(names, r.Name) } assert.Equal(t, tt.output, names) }) } } func Test_remoteResolver_Caching(t *testing.T) { t.Run("cache remotes", func(t *testing.T) { var readRemotesCalled bool rr := &remoteResolver{ readRemotes: func() (git.RemoteSet, error) { if readRemotesCalled { return git.RemoteSet{}, errors.New("readRemotes should only be called once") } readRemotesCalled = true return git.RemoteSet{ git.NewRemote("origin", "https://github.com/owner/repo.git"), }, nil }, getConfig: func() (gh.Config, error) { cfg := &ghmock.ConfigMock{} cfg.AuthenticationFunc = func() gh.AuthConfig { authCfg := &config.AuthConfig{} authCfg.SetHosts([]string{"github.com"}) authCfg.SetDefaultHost("github.com", "default") return authCfg } return cfg, nil }, urlTranslator: identityTranslator{}, } resolver := rr.Resolver() expectedRemoteNames := []string{"origin"} remotes, err := resolver() require.NoError(t, err) require.Equal(t, expectedRemoteNames, mapRemotesToNames(remotes)) require.Equal(t, readRemotesCalled, true) cachedRemotes, err := resolver() require.NoError(t, err, "expected no error to be cached") require.Equal(t, expectedRemoteNames, mapRemotesToNames(cachedRemotes), "expected the remotes to be cached") }) t.Run("cache error", func(t *testing.T) { var readRemotesCalled bool rr := &remoteResolver{ readRemotes: func() (git.RemoteSet, error) { if readRemotesCalled { return git.RemoteSet{ git.NewRemote("origin", "https://github.com/owner/repo.git"), }, nil } readRemotesCalled = true return git.RemoteSet{}, errors.New("error to be cached") }, getConfig: func() (gh.Config, error) { cfg := &ghmock.ConfigMock{} cfg.AuthenticationFunc = func() gh.AuthConfig { authCfg := &config.AuthConfig{} authCfg.SetHosts([]string{"github.com"}) authCfg.SetDefaultHost("github.com", "default") return authCfg } return cfg, nil }, urlTranslator: identityTranslator{}, } resolver := rr.Resolver() expectedErr := errors.New("error to be cached") remotes, err := resolver() require.Equal(t, expectedErr, err) require.Empty(t, remotes, "should return no remotes") require.Equal(t, readRemotesCalled, true) cachedRemotes, err := resolver() require.Equal(t, expectedErr, err, "expected the error to be cached") require.Empty(t, cachedRemotes, "should return no remotes") }) } func mapRemotesToNames(remotes context.Remotes) []string { names := make([]string, len(remotes)) for i, r := range remotes { names[i] = r.Name } return names }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/completion/completion_test.go
pkg/cmd/completion/completion_test.go
package completion import ( "strings" "testing" "github.com/cli/cli/v2/pkg/iostreams" "github.com/google/shlex" "github.com/spf13/cobra" ) func TestNewCmdCompletion(t *testing.T) { tests := []struct { name string args string wantOut string wantErr string }{ { name: "no arguments", args: "completion", wantOut: "complete -o default -F __start_gh gh", }, { name: "zsh completion", args: "completion -s zsh", wantOut: "#compdef gh", }, { name: "fish completion", args: "completion -s fish", wantOut: "complete -c gh ", }, { name: "PowerShell completion", args: "completion -s powershell", wantOut: "Register-ArgumentCompleter", }, { name: "unsupported shell", args: "completion -s csh", wantErr: "invalid argument \"csh\" for \"-s, --shell\" flag: valid values are {bash|zsh|fish|powershell}", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ios, _, stdout, stderr := iostreams.Test() completeCmd := NewCmdCompletion(ios) rootCmd := &cobra.Command{Use: "gh"} rootCmd.AddCommand(completeCmd) argv, err := shlex.Split(tt.args) if err != nil { t.Fatalf("argument splitting error: %v", err) } rootCmd.SetArgs(argv) rootCmd.SetOut(stderr) rootCmd.SetErr(stderr) _, err = rootCmd.ExecuteC() if tt.wantErr != "" { if err == nil || err.Error() != tt.wantErr { t.Fatalf("expected error %q, got %q", tt.wantErr, err) } return } if err != nil { t.Fatalf("error executing command: %v", err) } if !strings.Contains(stdout.String(), tt.wantOut) { t.Errorf("completion output did not match:\n%s", stdout.String()) } if len(stderr.String()) > 0 { t.Errorf("expected nothing on stderr, got %q", stderr.String()) } }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmd/completion/completion.go
pkg/cmd/completion/completion.go
package completion import ( "fmt" "github.com/MakeNowJust/heredoc" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" ) func NewCmdCompletion(io *iostreams.IOStreams) *cobra.Command { var shellType string cmd := &cobra.Command{ Use: "completion -s <shell>", Short: "Generate shell completion scripts", Long: heredoc.Docf(` Generate shell completion scripts for GitHub CLI commands. When installing GitHub CLI through a package manager, it's possible that no additional shell configuration is necessary to gain completion support. For Homebrew, see <https://docs.brew.sh/Shell-Completion> If you need to set up completions manually, follow the instructions below. The exact config file locations might vary based on your system. Make sure to restart your shell before testing whether completions are working. ### bash First, ensure that you install %[1]sbash-completion%[1]s using your package manager. After, add this to your %[1]s~/.bash_profile%[1]s: eval "$(gh completion -s bash)" ### zsh Generate a %[1]s_gh%[1]s completion script and put it somewhere in your %[1]s$fpath%[1]s: gh completion -s zsh > /usr/local/share/zsh/site-functions/_gh Ensure that the following is present in your %[1]s~/.zshrc%[1]s: autoload -U compinit compinit -i Zsh version 5.7 or later is recommended. ### fish Generate a %[1]sgh.fish%[1]s completion script: gh completion -s fish > ~/.config/fish/completions/gh.fish ### PowerShell Open your profile script with: mkdir -Path (Split-Path -Parent $profile) -ErrorAction SilentlyContinue notepad $profile Add the line and save the file: Invoke-Expression -Command $(gh completion -s powershell | Out-String) `, "`"), RunE: func(cmd *cobra.Command, args []string) error { if shellType == "" { if io.IsStdoutTTY() { return cmdutil.FlagErrorf("error: the value for `--shell` is required") } shellType = "bash" } w := io.Out rootCmd := cmd.Parent() switch shellType { case "bash": return rootCmd.GenBashCompletionV2(w, true) case "zsh": return rootCmd.GenZshCompletion(w) case "powershell": return rootCmd.GenPowerShellCompletionWithDesc(w) case "fish": return rootCmd.GenFishCompletion(w, true) default: return fmt.Errorf("unsupported shell type %q", shellType) } }, DisableFlagsInUseLine: true, } cmdutil.DisableAuthCheck(cmd) cmdutil.StringEnumFlag(cmd, &shellType, "shell", "s", "", []string{"bash", "zsh", "fish", "powershell"}, "Shell type") return cmd }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmdutil/auth_check_test.go
pkg/cmdutil/auth_check_test.go
package cmdutil import ( "testing" "github.com/cli/cli/v2/internal/config" "github.com/cli/cli/v2/internal/gh" "github.com/spf13/cobra" "github.com/stretchr/testify/require" ) func Test_CheckAuth(t *testing.T) { tests := []struct { name string env map[string]string cfgStubs func(*testing.T, gh.Config) expected bool }{ { name: "no known hosts, no env auth token", expected: false, }, { name: "no known hosts, env auth token", env: map[string]string{"GITHUB_TOKEN": "token"}, expected: true, }, { name: "known host", cfgStubs: func(t *testing.T, c gh.Config) { _, err := c.Authentication().Login("github.com", "test-user", "test-token", "https", false) require.NoError(t, err) }, expected: true, }, { name: "enterprise token", env: map[string]string{"GH_ENTERPRISE_TOKEN": "token"}, expected: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { cfg, _ := config.NewIsolatedTestConfig(t) if tt.cfgStubs != nil { tt.cfgStubs(t, cfg) } for k, v := range tt.env { t.Setenv(k, v) } require.Equal(t, tt.expected, CheckAuth(cfg)) }) } } func Test_IsAuthCheckEnabled(t *testing.T) { tests := []struct { name string init func() (*cobra.Command, error) isAuthCheckEnabled bool }{ { name: "no annotations", init: func() (*cobra.Command, error) { cmd := &cobra.Command{} cmd.Flags().Bool("flag", false, "") return cmd, nil }, isAuthCheckEnabled: true, }, { name: "command-level disable", init: func() (*cobra.Command, error) { cmd := &cobra.Command{} DisableAuthCheck(cmd) return cmd, nil }, isAuthCheckEnabled: false, }, { name: "command with flag-level disable, flag not set", init: func() (*cobra.Command, error) { cmd := &cobra.Command{} cmd.Flags().Bool("flag", false, "") DisableAuthCheckFlag(cmd.Flag("flag")) return cmd, nil }, isAuthCheckEnabled: true, }, { name: "command with flag-level disable, flag set", init: func() (*cobra.Command, error) { cmd := &cobra.Command{} cmd.Flags().Bool("flag", false, "") if err := cmd.Flags().Set("flag", "true"); err != nil { return nil, err } DisableAuthCheckFlag(cmd.Flag("flag")) return cmd, nil }, isAuthCheckEnabled: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { cmd, err := tt.init() require.NoError(t, err) // IsAuthCheckEnabled assumes commands under test are subcommands parent := &cobra.Command{Use: "root"} parent.AddCommand(cmd) require.Equal(t, tt.isAuthCheckEnabled, IsAuthCheckEnabled(cmd)) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmdutil/flags.go
pkg/cmdutil/flags.go
package cmdutil import ( "context" "fmt" "strconv" "strings" "github.com/spf13/cobra" "github.com/spf13/pflag" ) // NilStringFlag defines a new flag with a string pointer receiver. This is useful for differentiating // between the flag being set to a blank value and the flag not being passed at all. func NilStringFlag(cmd *cobra.Command, p **string, name string, shorthand string, usage string) *pflag.Flag { return cmd.Flags().VarPF(newStringValue(p), name, shorthand, usage) } // NilBoolFlag defines a new flag with a bool pointer receiver. This is useful for differentiating // between the flag being explicitly set to a false value and the flag not being passed at all. func NilBoolFlag(cmd *cobra.Command, p **bool, name string, shorthand string, usage string) *pflag.Flag { f := cmd.Flags().VarPF(newBoolValue(p), name, shorthand, usage) f.NoOptDefVal = "true" return f } // StringEnumFlag defines a new string flag that only allows values listed in options. func StringEnumFlag(cmd *cobra.Command, p *string, name, shorthand, defaultValue string, options []string, usage string) *pflag.Flag { *p = defaultValue val := &enumValue{string: p, options: options} f := cmd.Flags().VarPF(val, name, shorthand, fmt.Sprintf("%s: %s", usage, formatValuesForUsageDocs(options))) _ = cmd.RegisterFlagCompletionFunc(name, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return options, cobra.ShellCompDirectiveNoFileComp }) return f } func StringSliceEnumFlag(cmd *cobra.Command, p *[]string, name, shorthand string, defaultValues, options []string, usage string) *pflag.Flag { *p = defaultValues val := &enumMultiValue{value: p, options: options} f := cmd.Flags().VarPF(val, name, shorthand, fmt.Sprintf("%s: %s", usage, formatValuesForUsageDocs(options))) _ = cmd.RegisterFlagCompletionFunc(name, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return options, cobra.ShellCompDirectiveNoFileComp }) return f } type gitClient interface { TrackingBranchNames(context.Context, string) []string } // RegisterBranchCompletionFlags suggests and autocompletes known remote git branches for flags passed func RegisterBranchCompletionFlags(gitc gitClient, cmd *cobra.Command, flags ...string) error { for _, flag := range flags { err := cmd.RegisterFlagCompletionFunc(flag, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { if repoFlag := cmd.Flag("repo"); repoFlag != nil && repoFlag.Changed { return nil, cobra.ShellCompDirectiveNoFileComp } return gitc.TrackingBranchNames(context.TODO(), toComplete), cobra.ShellCompDirectiveNoFileComp }) if err != nil { return err } } return nil } func formatValuesForUsageDocs(values []string) string { return fmt.Sprintf("{%s}", strings.Join(values, "|")) } type stringValue struct { string **string } func newStringValue(p **string) *stringValue { return &stringValue{p} } func (s *stringValue) Set(value string) error { *s.string = &value return nil } func (s *stringValue) String() string { if s.string == nil || *s.string == nil { return "" } return **s.string } func (s *stringValue) Type() string { return "string" } type boolValue struct { bool **bool } func newBoolValue(p **bool) *boolValue { return &boolValue{p} } func (b *boolValue) Set(value string) error { v, err := strconv.ParseBool(value) *b.bool = &v return err } func (b *boolValue) String() string { if b.bool == nil || *b.bool == nil { return "false" } else if **b.bool { return "true" } return "false" } func (b *boolValue) Type() string { return "bool" } func (b *boolValue) IsBoolFlag() bool { return true } type enumValue struct { string *string options []string } func (e *enumValue) Set(value string) error { if !isIncluded(value, e.options) { return fmt.Errorf("valid values are %s", formatValuesForUsageDocs(e.options)) } *e.string = value return nil } func (e *enumValue) String() string { return *e.string } func (e *enumValue) Type() string { return "string" } type enumMultiValue struct { value *[]string options []string } func (e *enumMultiValue) Set(value string) error { items := strings.Split(value, ",") for _, item := range items { if !isIncluded(item, e.options) { return fmt.Errorf("valid values are %s", formatValuesForUsageDocs(e.options)) } } *e.value = append(*e.value, items...) return nil } func (e *enumMultiValue) String() string { if len(*e.value) == 0 { return "" } return fmt.Sprintf("{%s}", strings.Join(*e.value, ", ")) } func (e *enumMultiValue) Type() string { return "stringSlice" } func isIncluded(value string, opts []string) bool { for _, opt := range opts { if strings.EqualFold(opt, value) { return true } } return false }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmdutil/repo_override.go
pkg/cmdutil/repo_override.go
package cmdutil import ( "os" "sort" "strings" "github.com/cli/cli/v2/internal/ghrepo" "github.com/spf13/cobra" ) func executeParentHooks(cmd *cobra.Command, args []string) error { for cmd.HasParent() { cmd = cmd.Parent() if cmd.PersistentPreRunE != nil { return cmd.PersistentPreRunE(cmd, args) } } return nil } func EnableRepoOverride(cmd *cobra.Command, f *Factory) { cmd.PersistentFlags().StringP("repo", "R", "", "Select another repository using the `[HOST/]OWNER/REPO` format") _ = cmd.RegisterFlagCompletionFunc("repo", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { remotes, err := f.Remotes() if err != nil { return nil, cobra.ShellCompDirectiveError } config, err := f.Config() if err != nil { return nil, cobra.ShellCompDirectiveError } defaultHost, _ := config.Authentication().DefaultHost() var results []string for _, remote := range remotes { repo := remote.RepoOwner() + "/" + remote.RepoName() if !strings.EqualFold(remote.RepoHost(), defaultHost) { repo = remote.RepoHost() + "/" + repo } if strings.HasPrefix(repo, toComplete) { results = append(results, repo) } } sort.Strings(results) return results, cobra.ShellCompDirectiveNoFileComp }) cmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error { if err := executeParentHooks(cmd, args); err != nil { return err } repoOverride, _ := cmd.Flags().GetString("repo") f.BaseRepo = OverrideBaseRepoFunc(f, repoOverride) return nil } } func OverrideBaseRepoFunc(f *Factory, override string) func() (ghrepo.Interface, error) { if override == "" { override = os.Getenv("GH_REPO") } if override != "" { return func() (ghrepo.Interface, error) { return ghrepo.FromFullName(override) } } return f.BaseRepo }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmdutil/errors.go
pkg/cmdutil/errors.go
package cmdutil import ( "errors" "fmt" "github.com/AlecAivazis/survey/v2/terminal" ) // FlagErrorf returns a new FlagError that wraps an error produced by // fmt.Errorf(format, args...). func FlagErrorf(format string, args ...interface{}) error { return FlagErrorWrap(fmt.Errorf(format, args...)) } // FlagErrorWrap returns a new FlagError that wraps the specified error. func FlagErrorWrap(err error) error { return &FlagError{err} } // A *FlagError indicates an error processing command-line flags or other arguments. // Such errors cause the application to display the usage message. type FlagError struct { // Note: not struct{error}: only *FlagError should satisfy error. err error } func (fe *FlagError) Error() string { return fe.err.Error() } func (fe *FlagError) Unwrap() error { return fe.err } // SilentError is an error that triggers exit code 1 without any error messaging var SilentError = errors.New("SilentError") // CancelError signals user-initiated cancellation var CancelError = errors.New("CancelError") // PendingError signals nothing failed but something is pending var PendingError = errors.New("PendingError") func IsUserCancellation(err error) bool { return errors.Is(err, CancelError) || errors.Is(err, terminal.InterruptErr) } func MutuallyExclusive(message string, conditions ...bool) error { numTrue := 0 for _, ok := range conditions { if ok { numTrue++ } } if numTrue > 1 { return FlagErrorf("%s", message) } return nil } type NoResultsError struct { message string } func (e NoResultsError) Error() string { return e.message } func NewNoResultsError(message string) NoResultsError { return NoResultsError{message: message} }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmdutil/json_flags.go
pkg/cmdutil/json_flags.go
package cmdutil import ( "bytes" "encoding/json" "errors" "fmt" "io" "reflect" "sort" "strings" "github.com/cli/cli/v2/pkg/iostreams" "github.com/cli/cli/v2/pkg/jsoncolor" "github.com/cli/cli/v2/pkg/set" "github.com/cli/go-gh/v2/pkg/jq" "github.com/cli/go-gh/v2/pkg/template" "github.com/spf13/cobra" "github.com/spf13/pflag" ) type JSONFlagError struct { error } func AddJSONFlags(cmd *cobra.Command, exportTarget *Exporter, fields []string) { f := cmd.Flags() addJsonFlag(f) addJqFlag(f, "q") addTemplateFlag(f, "t") setupJsonFlags(cmd, exportTarget, fields) } func AddJSONFlagsWithoutShorthand(cmd *cobra.Command, exportTarget *Exporter, fields []string) { f := cmd.Flags() addJsonFlag(f) addJqFlag(f, "") addTemplateFlag(f, "") setupJsonFlags(cmd, exportTarget, fields) } func addJsonFlag(f *pflag.FlagSet) { f.StringSlice("json", nil, "Output JSON with the specified `fields`") } func addJqFlag(f *pflag.FlagSet, shorthand string) { f.StringP("jq", shorthand, "", "Filter JSON output using a jq `expression`") } func addTemplateFlag(f *pflag.FlagSet, shorthand string) { f.StringP("template", shorthand, "", "Format JSON output using a Go template; see \"gh help formatting\"") } func setupJsonFlags(cmd *cobra.Command, exportTarget *Exporter, fields []string) { _ = cmd.RegisterFlagCompletionFunc("json", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { var results []string var prefix string if idx := strings.LastIndexByte(toComplete, ','); idx >= 0 { prefix = toComplete[:idx+1] toComplete = toComplete[idx+1:] } toComplete = strings.ToLower(toComplete) for _, f := range fields { if strings.HasPrefix(strings.ToLower(f), toComplete) { results = append(results, prefix+f) } } sort.Strings(results) return results, cobra.ShellCompDirectiveNoSpace }) oldPreRun := cmd.PreRunE cmd.PreRunE = func(c *cobra.Command, args []string) error { if oldPreRun != nil { if err := oldPreRun(c, args); err != nil { return err } } if export, err := checkJSONFlags(c); err == nil { if export == nil { *exportTarget = nil } else { allowedFields := set.NewStringSet() allowedFields.AddValues(fields) for _, f := range export.fields { if !allowedFields.Contains(f) { sort.Strings(fields) return JSONFlagError{fmt.Errorf("Unknown JSON field: %q\nAvailable fields:\n %s", f, strings.Join(fields, "\n "))} } } *exportTarget = export } } else { return err } return nil } cmd.SetFlagErrorFunc(func(c *cobra.Command, e error) error { if c == cmd && e.Error() == "flag needs an argument: --json" { sort.Strings(fields) return JSONFlagError{fmt.Errorf("Specify one or more comma-separated fields for `--json`:\n %s", strings.Join(fields, "\n "))} } if cmd.HasParent() { return cmd.Parent().FlagErrorFunc()(c, e) } return e }) if len(fields) == 0 { return } if cmd.Annotations == nil { cmd.Annotations = map[string]string{} } cmd.Annotations["help:json-fields"] = strings.Join(fields, ",") } func checkJSONFlags(cmd *cobra.Command) (*jsonExporter, error) { f := cmd.Flags() jsonFlag := f.Lookup("json") jqFlag := f.Lookup("jq") tplFlag := f.Lookup("template") webFlag := f.Lookup("web") if jsonFlag.Changed { if webFlag != nil && webFlag.Changed { return nil, errors.New("cannot use `--web` with `--json`") } jv := jsonFlag.Value.(pflag.SliceValue) return &jsonExporter{ fields: jv.GetSlice(), filter: jqFlag.Value.String(), template: tplFlag.Value.String(), }, nil } else if jqFlag.Changed { return nil, errors.New("cannot use `--jq` without specifying `--json`") } else if tplFlag.Changed { return nil, errors.New("cannot use `--template` without specifying `--json`") } return nil, nil } func AddFormatFlags(cmd *cobra.Command, exportTarget *Exporter) { var format string StringEnumFlag(cmd, &format, "format", "", "", []string{"json"}, "Output format") f := cmd.Flags() f.StringP("jq", "q", "", "Filter JSON output using a jq `expression`") f.StringP("template", "t", "", "Format JSON output using a Go template; see \"gh help formatting\"") oldPreRun := cmd.PreRunE cmd.PreRunE = func(c *cobra.Command, args []string) error { if oldPreRun != nil { if err := oldPreRun(c, args); err != nil { return err } } if export, err := checkFormatFlags(c); err == nil { if export == nil { *exportTarget = nil } else { *exportTarget = export } } else { return err } return nil } } func checkFormatFlags(cmd *cobra.Command) (*jsonExporter, error) { f := cmd.Flags() formatFlag := f.Lookup("format") formatValue := formatFlag.Value.String() jqFlag := f.Lookup("jq") tplFlag := f.Lookup("template") webFlag := f.Lookup("web") if formatFlag.Changed { if webFlag != nil && webFlag.Changed { return nil, errors.New("cannot use `--web` with `--format`") } return &jsonExporter{ filter: jqFlag.Value.String(), template: tplFlag.Value.String(), }, nil } else if jqFlag.Changed && formatValue != "json" { return nil, errors.New("cannot use `--jq` without specifying `--format json`") } else if tplFlag.Changed && formatValue != "json" { return nil, errors.New("cannot use `--template` without specifying `--format json`") } return nil, nil } type Exporter interface { Fields() []string Write(io *iostreams.IOStreams, data interface{}) error } type jsonExporter struct { fields []string filter string template string } // NewJSONExporter returns an Exporter to emit JSON. func NewJSONExporter() *jsonExporter { return &jsonExporter{} } func (e *jsonExporter) Fields() []string { return e.fields } func (e *jsonExporter) SetFields(fields []string) { e.fields = fields } // Write serializes data into JSON output written to w. If the object passed as data implements exportable, // or if data is a map or slice of exportable object, ExportData() will be called on each object to obtain // raw data for serialization. func (e *jsonExporter) Write(ios *iostreams.IOStreams, data interface{}) error { buf := bytes.Buffer{} encoder := json.NewEncoder(&buf) encoder.SetEscapeHTML(false) if err := encoder.Encode(e.exportData(reflect.ValueOf(data))); err != nil { return err } w := ios.Out if e.filter != "" { indent := "" if ios.IsStdoutTTY() { indent = " " } if err := jq.EvaluateFormatted(&buf, w, e.filter, indent, ios.ColorEnabled()); err != nil { return err } } else if e.template != "" { t := template.New(w, ios.TerminalWidth(), ios.ColorEnabled()) if err := t.Parse(e.template); err != nil { return err } if err := t.Execute(&buf); err != nil { return err } return t.Flush() } else if ios.ColorEnabled() { return jsoncolor.Write(w, &buf, " ") } _, err := io.Copy(w, &buf) return err } func (e *jsonExporter) exportData(v reflect.Value) interface{} { switch v.Kind() { case reflect.Ptr, reflect.Interface: if !v.IsNil() { return e.exportData(v.Elem()) } case reflect.Slice: a := make([]interface{}, v.Len()) for i := 0; i < v.Len(); i++ { a[i] = e.exportData(v.Index(i)) } return a case reflect.Map: t := reflect.MapOf(v.Type().Key(), emptyInterfaceType) m := reflect.MakeMapWithSize(t, v.Len()) iter := v.MapRange() for iter.Next() { ve := reflect.ValueOf(e.exportData(iter.Value())) m.SetMapIndex(iter.Key(), ve) } return m.Interface() case reflect.Struct: if v.CanAddr() && reflect.PointerTo(v.Type()).Implements(exportableType) { ve := v.Addr().Interface().(exportable) return ve.ExportData(e.fields) } else if v.Type().Implements(exportableType) { ve := v.Interface().(exportable) return ve.ExportData(e.fields) } } return v.Interface() } type exportable interface { ExportData([]string) map[string]interface{} } var exportableType = reflect.TypeOf((*exportable)(nil)).Elem() var sliceOfEmptyInterface []interface{} var emptyInterfaceType = reflect.TypeOf(sliceOfEmptyInterface).Elem() // Basic function that can be used with structs that need to implement // the exportable interface. It has numerous limitations so verify // that it works as expected with the struct and fields you want to export. // If it does not, then implementing a custom ExportData method is necessary. // Perhaps this should be moved up into exportData for the case when // a struct does not implement the exportable interface, but for now it will // need to be explicitly used. func StructExportData(s interface{}, fields []string) map[string]interface{} { v := reflect.ValueOf(s) if v.Kind() == reflect.Ptr { v = v.Elem() } if v.Kind() != reflect.Struct { // If s is not a struct or pointer to a struct return nil. return nil } data := make(map[string]interface{}, len(fields)) for _, f := range fields { sf := fieldByName(v, f) if sf.IsValid() && sf.CanInterface() { data[f] = sf.Interface() } } return data } func fieldByName(v reflect.Value, field string) reflect.Value { return v.FieldByNameFunc(func(s string) bool { return strings.EqualFold(field, s) }) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmdutil/json_flags_test.go
pkg/cmdutil/json_flags_test.go
package cmdutil import ( "bytes" "encoding/json" "fmt" "io" "testing" "time" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestAddJSONFlags(t *testing.T) { tests := []struct { name string fields []string args []string wantsExport *jsonExporter wantsError string }{ { name: "no JSON flag", fields: []string{}, args: []string{}, wantsExport: nil, }, { name: "empty JSON flag", fields: []string{"one", "two"}, args: []string{"--json"}, wantsExport: nil, wantsError: "Specify one or more comma-separated fields for `--json`:\n one\n two", }, { name: "invalid JSON field", fields: []string{"id", "number"}, args: []string{"--json", "idontexist"}, wantsExport: nil, wantsError: "Unknown JSON field: \"idontexist\"\nAvailable fields:\n id\n number", }, { name: "cannot combine --json with --web", fields: []string{"id", "number", "title"}, args: []string{"--json", "id", "--web"}, wantsExport: nil, wantsError: "cannot use `--web` with `--json`", }, { name: "cannot use --jq without --json", fields: []string{}, args: []string{"--jq", ".number"}, wantsExport: nil, wantsError: "cannot use `--jq` without specifying `--json`", }, { name: "cannot use --template without --json", fields: []string{}, args: []string{"--template", "{{.number}}"}, wantsExport: nil, wantsError: "cannot use `--template` without specifying `--json`", }, { name: "with JSON fields", fields: []string{"id", "number", "title"}, args: []string{"--json", "number,title"}, wantsExport: &jsonExporter{ fields: []string{"number", "title"}, filter: "", template: "", }, }, { name: "with jq filter", fields: []string{"id", "number", "title"}, args: []string{"--json", "number", "-q.number"}, wantsExport: &jsonExporter{ fields: []string{"number"}, filter: ".number", template: "", }, }, { name: "with Go template", fields: []string{"id", "number", "title"}, args: []string{"--json", "number", "-t", "{{.number}}"}, wantsExport: &jsonExporter{ fields: []string{"number"}, filter: "", template: "{{.number}}", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { cmd := &cobra.Command{Run: func(*cobra.Command, []string) {}} cmd.Flags().Bool("web", false, "") var exporter Exporter AddJSONFlags(cmd, &exporter, tt.fields) cmd.SetArgs(tt.args) cmd.SetOut(io.Discard) cmd.SetErr(io.Discard) _, err := cmd.ExecuteC() if tt.wantsError == "" { require.NoError(t, err) } else { assert.EqualError(t, err, tt.wantsError) return } if tt.wantsExport == nil { assert.Nil(t, exporter) } else { assert.Equal(t, tt.wantsExport, exporter) } }) } } func TestAddJSONFlagsWithoutShorthand(t *testing.T) { tests := []struct { name string setFlags func(cmd *cobra.Command) wantFlags map[string]string }{ { name: "no conflicting flags", setFlags: func(cmd *cobra.Command) { cmd.Flags().StringP("web", "w", "", "") cmd.Flags().StringP("token", "t", "", "") }, wantFlags: map[string]string{ "web": "w", "token": "t", "jq": "", "template": "", "json": "", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { cmd := &cobra.Command{Run: func(*cobra.Command, []string) {}} tt.setFlags(cmd) AddJSONFlagsWithoutShorthand(cmd, nil, []string{}) for f, shorthand := range tt.wantFlags { flag := cmd.Flags().Lookup(f) require.NotNil(t, flag) require.Equal(t, shorthand, flag.Shorthand) } }) } } // TestAddJSONFlagsSetsAnnotations asserts that `AddJSONFlags` function adds the // appropriate annotation to the command, which could later be used by doc // generator functions. func TestAddJSONFlagsSetsAnnotations(t *testing.T) { tests := []struct { name string cmd *cobra.Command jsonFields []string expectedAnnotations map[string]string }{ { name: "empty set of fields", cmd: &cobra.Command{}, jsonFields: []string{}, expectedAnnotations: nil, }, { name: "empty set of fields, with existing annotations", cmd: &cobra.Command{Annotations: map[string]string{"foo": "bar"}}, jsonFields: []string{}, expectedAnnotations: map[string]string{"foo": "bar"}, }, { name: "no other annotations", cmd: &cobra.Command{}, jsonFields: []string{"few", "json", "fields"}, expectedAnnotations: map[string]string{ "help:json-fields": "few,json,fields", }, }, { name: "with existing annotations (ensure no overwrite)", cmd: &cobra.Command{Annotations: map[string]string{"foo": "bar"}}, jsonFields: []string{"few", "json", "fields"}, expectedAnnotations: map[string]string{ "foo": "bar", "help:json-fields": "few,json,fields", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { AddJSONFlags(tt.cmd, nil, tt.jsonFields) assert.Equal(t, tt.expectedAnnotations, tt.cmd.Annotations) }) } } func TestAddFormatFlags(t *testing.T) { tests := []struct { name string args []string wantsExport *jsonExporter wantsError string }{ { name: "no format flag", args: []string{}, wantsExport: nil, }, { name: "empty format flag", args: []string{"--format"}, wantsExport: nil, wantsError: "flag needs an argument: --format", }, { name: "invalid format field", args: []string{"--format", "idontexist"}, wantsExport: nil, wantsError: "invalid argument \"idontexist\" for \"--format\" flag: valid values are {json}", }, { name: "cannot combine --format with --web", args: []string{"--format", "json", "--web"}, wantsExport: nil, wantsError: "cannot use `--web` with `--format`", }, { name: "cannot use --jq without --format", args: []string{"--jq", ".number"}, wantsExport: nil, wantsError: "cannot use `--jq` without specifying `--format json`", }, { name: "cannot use --template without --format", args: []string{"--template", "{{.number}}"}, wantsExport: nil, wantsError: "cannot use `--template` without specifying `--format json`", }, { name: "with json format", args: []string{"--format", "json"}, wantsExport: &jsonExporter{ filter: "", template: "", }, }, { name: "with jq filter", args: []string{"--format", "json", "-q.number"}, wantsExport: &jsonExporter{ filter: ".number", template: "", }, }, { name: "with Go template", args: []string{"--format", "json", "-t", "{{.number}}"}, wantsExport: &jsonExporter{ filter: "", template: "{{.number}}", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { cmd := &cobra.Command{Run: func(*cobra.Command, []string) {}} cmd.Flags().Bool("web", false, "") var exporter Exporter AddFormatFlags(cmd, &exporter) cmd.SetArgs(tt.args) cmd.SetOut(io.Discard) cmd.SetErr(io.Discard) _, err := cmd.ExecuteC() if tt.wantsError == "" { require.NoError(t, err) } else { assert.EqualError(t, err, tt.wantsError) return } if tt.wantsExport == nil { assert.Nil(t, exporter) } else { assert.Equal(t, tt.wantsExport, exporter) } }) } } func Test_exportFormat_Write(t *testing.T) { type args struct { data interface{} } tests := []struct { name string exporter jsonExporter args args wantW string wantErr bool istty bool }{ { name: "regular JSON output", exporter: jsonExporter{}, args: args{ data: map[string]string{"name": "hubot"}, }, wantW: "{\"name\":\"hubot\"}\n", wantErr: false, istty: false, }, { name: "call ExportData", exporter: jsonExporter{fields: []string{"field1", "field2"}}, args: args{ data: &exportableItem{"item1"}, }, wantW: "{\"field1\":\"item1:field1\",\"field2\":\"item1:field2\"}\n", wantErr: false, istty: false, }, { name: "recursively call ExportData", exporter: jsonExporter{fields: []string{"f1", "f2"}}, args: args{ data: map[string]interface{}{ "s1": []exportableItem{{"i1"}, {"i2"}}, "s2": []exportableItem{{"i3"}}, }, }, wantW: "{\"s1\":[{\"f1\":\"i1:f1\",\"f2\":\"i1:f2\"},{\"f1\":\"i2:f1\",\"f2\":\"i2:f2\"}],\"s2\":[{\"f1\":\"i3:f1\",\"f2\":\"i3:f2\"}]}\n", wantErr: false, istty: false, }, { name: "with jq filter", exporter: jsonExporter{filter: ".name"}, args: args{ data: map[string]string{"name": "hubot"}, }, wantW: "hubot\n", wantErr: false, istty: false, }, { name: "with jq filter pretty printing", exporter: jsonExporter{filter: "."}, args: args{ data: map[string]string{"name": "hubot"}, }, wantW: "{\n \"name\": \"hubot\"\n}\n", wantErr: false, istty: true, }, { name: "with Go template", exporter: jsonExporter{template: "{{.name}}"}, args: args{ data: map[string]string{"name": "hubot"}, }, wantW: "hubot", wantErr: false, istty: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { io, _, w, _ := iostreams.Test() io.SetStdoutTTY(tt.istty) if err := tt.exporter.Write(io, tt.args.data); (err != nil) != tt.wantErr { t.Errorf("exportFormat.Write() error = %v, wantErr %v", err, tt.wantErr) return } if gotW := w.String(); gotW != tt.wantW { t.Errorf("exportFormat.Write() = %q, want %q", gotW, tt.wantW) } }) } } type exportableItem struct { Name string } func (e *exportableItem) ExportData(fields []string) map[string]interface{} { m := map[string]interface{}{} for _, f := range fields { m[f] = fmt.Sprintf("%s:%s", e.Name, f) } return m } func TestStructExportData(t *testing.T) { tf, _ := time.Parse(time.RFC3339, "2024-01-01T00:00:00Z") type s struct { StringField string IntField int BoolField bool TimeField time.Time SliceField []int MapField map[string]int StructField struct { A string B int c bool } unexportedField int } export := s{ StringField: "test", IntField: 1, BoolField: true, TimeField: tf, SliceField: []int{1, 2, 3}, MapField: map[string]int{ "one": 1, "two": 2, "three": 3, }, StructField: struct { A string B int c bool }{ A: "a", B: 1, c: true, }, unexportedField: 4, } fields := []string{"stringField", "intField", "boolField", "sliceField", "mapField", "structField"} tests := []struct { name string export interface{} fields []string wantOut string }{ { name: "serializes struct types", export: export, fields: fields, wantOut: `{"boolField":true,"intField":1,"mapField":{"one":1,"three":3,"two":2},"sliceField":[1,2,3],"stringField":"test","structField":{"A":"a","B":1}}`, }, { name: "serializes pointer to struct types", export: &export, fields: fields, wantOut: `{"boolField":true,"intField":1,"mapField":{"one":1,"three":3,"two":2},"sliceField":[1,2,3],"stringField":"test","structField":{"A":"a","B":1}}`, }, { name: "does not serialize non-struct types", export: map[string]string{ "test": "test", }, fields: nil, wantOut: `null`, }, { name: "ignores unknown fields", export: export, fields: []string{"stringField", "unknownField"}, wantOut: `{"stringField":"test"}`, }, { name: "ignores unexported fields", export: export, fields: []string{"stringField", "unexportedField"}, wantOut: `{"stringField":"test"}`, }, { name: "field matching is case insensitive but casing impacts JSON output", export: export, fields: []string{"STRINGfield"}, wantOut: `{"STRINGfield":"test"}`, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { buf := bytes.Buffer{} encoder := json.NewEncoder(&buf) encoder.SetEscapeHTML(false) out := StructExportData(tt.export, tt.fields) require.NoError(t, encoder.Encode(out)) require.JSONEq(t, tt.wantOut, buf.String()) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmdutil/factory_test.go
pkg/cmdutil/factory_test.go
package cmdutil import ( "os" "path/filepath" "strings" "testing" ) func Test_executable(t *testing.T) { testExe, err := os.Executable() if err != nil { t.Fatal(err) } testExeName := filepath.Base(testExe) // Create 3 extra PATH entries that each contain an executable with the same name as the running test // process. The first is a symlink, but to an unrelated executable, the second is a symlink to our test // process and thus represents the result we want, and the third one is an unrelated executable. dir := t.TempDir() bin1 := filepath.Join(dir, "bin1") bin1Exe := filepath.Join(bin1, testExeName) bin2 := filepath.Join(dir, "bin2") bin2Exe := filepath.Join(bin2, testExeName) bin3 := filepath.Join(dir, "bin3") bin3Exe := filepath.Join(bin3, testExeName) if err := os.MkdirAll(bin1, 0755); err != nil { t.Fatal(err) } if err := os.MkdirAll(bin2, 0755); err != nil { t.Fatal(err) } if err := os.MkdirAll(bin3, 0755); err != nil { t.Fatal(err) } if f, err := os.OpenFile(bin3Exe, os.O_CREATE, 0755); err == nil { f.Close() } else { t.Fatal(err) } if err := os.Symlink(testExe, bin2Exe); err != nil { t.Fatal(err) } if err := os.Symlink(bin3Exe, bin1Exe); err != nil { t.Fatal(err) } oldPath := os.Getenv("PATH") t.Setenv("PATH", strings.Join([]string{bin1, bin2, bin3, oldPath}, string(os.PathListSeparator))) if got := executable(""); got != bin2Exe { t.Errorf("executable() = %q, want %q", got, bin2Exe) } } func Test_executable_relative(t *testing.T) { testExe, err := os.Executable() if err != nil { t.Fatal(err) } testExeName := filepath.Base(testExe) // Create 3 extra PATH entries that each contain an executable with the same name as the running test // process. The first is a relative symlink, but to an unrelated executable, the second is a relative // symlink to our test process and thus represents the result we want, and the third one is an unrelated // executable. dir := t.TempDir() bin1 := filepath.Join(dir, "bin1") bin1Exe := filepath.Join(bin1, testExeName) bin2 := filepath.Join(dir, "bin2") bin2Exe := filepath.Join(bin2, testExeName) bin3 := filepath.Join(dir, "bin3") bin3Exe := filepath.Join(bin3, testExeName) if err := os.MkdirAll(bin1, 0755); err != nil { t.Fatal(err) } if err := os.MkdirAll(bin2, 0755); err != nil { t.Fatal(err) } if err := os.MkdirAll(bin3, 0755); err != nil { t.Fatal(err) } if f, err := os.OpenFile(bin3Exe, os.O_CREATE, 0755); err == nil { f.Close() } else { t.Fatal(err) } bin2Rel, err := filepath.Rel(bin2, testExe) if err != nil { t.Fatal(err) } if err := os.Symlink(bin2Rel, bin2Exe); err != nil { t.Fatal(err) } bin1Rel, err := filepath.Rel(bin1, bin3Exe) if err != nil { t.Fatal(err) } if err := os.Symlink(bin1Rel, bin1Exe); err != nil { t.Fatal(err) } oldPath := os.Getenv("PATH") t.Setenv("PATH", strings.Join([]string{bin1, bin2, bin3, oldPath}, string(os.PathListSeparator))) if got := executable(""); got != bin2Exe { t.Errorf("executable() = %q, want %q", got, bin2Exe) } } func Test_Executable_override(t *testing.T) { override := strings.Join([]string{"C:", "cygwin64", "home", "gh.exe"}, string(os.PathSeparator)) t.Setenv("GH_PATH", override) f := Factory{} if got := f.Executable(); got != override { t.Errorf("executable() = %q, want %q", got, override) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmdutil/args_test.go
pkg/cmdutil/args_test.go
package cmdutil import ( "errors" "os" "path/filepath" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestMinimumArgs(t *testing.T) { tests := []struct { N int Args []string }{ { N: 1, Args: []string{"v1.2.3"}, }, { N: 2, Args: []string{"v1.2.3", "cli/cli"}, }, } for _, test := range tests { if got := MinimumArgs(test.N, "")(nil, test.Args); got != nil { t.Errorf("Got: %v, Want: (nil)", got) } } } func TestMinimumNs_with_error(t *testing.T) { tests := []struct { N int CustomMessage string WantMessage string }{ { N: 1, CustomMessage: "A custom msg", WantMessage: "A custom msg", }, { N: 1, CustomMessage: "", WantMessage: "requires at least 1 arg(s), only received 0", }, } for _, test := range tests { if got := MinimumArgs(test.N, test.CustomMessage)(nil, nil); got.Error() != test.WantMessage { t.Errorf("Got: %v, Want: %v", got, test.WantMessage) } } } func TestPartition(t *testing.T) { tests := []struct { name string slice []any predicate func(any) bool wantMatching []any wantNonMatching []any }{ { name: "When the slice is empty, it returns two empty slices", slice: []any{}, predicate: func(any) bool { return true }, wantMatching: []any{}, wantNonMatching: []any{}, }, { name: "when the slice has one element that satisfies the predicate, it returns a slice with that element and an empty slice", slice: []any{ "foo", }, predicate: func(any) bool { return true }, wantMatching: []any{"foo"}, wantNonMatching: []any{}, }, { name: "when the slice has one element that does not satisfy the predicate, it returns an empty slice and a slice with that element", slice: []any{ "foo", }, predicate: func(any) bool { return false }, wantMatching: []any{}, wantNonMatching: []any{"foo"}, }, { name: "when the slice has multiple elements, it returns a slice with the elements that satisfy the predicate and a slice with the elements that do not satisfy the predicate", slice: []any{ "foo", "bar", "baz", }, predicate: func(s any) bool { return s.(string) != "foo" }, wantMatching: []any{"bar", "baz"}, wantNonMatching: []any{"foo"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotMatching, gotNonMatching := Partition(tt.slice, tt.predicate) assert.ElementsMatch(t, tt.wantMatching, gotMatching) assert.ElementsMatch(t, tt.wantNonMatching, gotNonMatching) }) } } func TestGlobPaths(t *testing.T) { tests := []struct { name string os string patterns []string wantOut []string wantErr error }{ { name: "When no patterns are passed, return an empty slice", patterns: []string{}, wantOut: []string{}, wantErr: nil, }, { name: "When no files match, it returns an empty expansions array with error", patterns: []string{"foo"}, wantOut: []string{}, wantErr: errors.New("no matches found for `foo`"), }, { name: "When a single pattern, '*.txt' is passed with one match, it returns that match", patterns: []string{ "*.txt", }, wantOut: []string{ "rootFile.txt", }, wantErr: nil, }, { name: "When a single pattern, '*/*.txt' is passed with multiple matches, it returns those matches", patterns: []string{ "*/*.txt", }, wantOut: []string{ filepath.Join("subDir1", "subDir1_file.txt"), filepath.Join("subDir2", "subDir2_file.txt"), }, wantErr: nil, }, { name: "When multiple patterns, '*/*.txt' and '*/*.go', are passed with multiple matches, it returns those matches", patterns: []string{ "*/*.txt", "*/*.go", }, wantOut: []string{ filepath.Join("subDir1", "subDir1_file.txt"), filepath.Join("subDir2", "subDir2_file.txt"), filepath.Join("subDir2", "subDir2_file.go"), }, wantErr: nil, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { cleanupFn := createTestDir(t) defer cleanupFn() got, err := GlobPaths(tt.patterns) if tt.wantErr != nil { assert.EqualError(t, err, tt.wantErr.Error()) } else { require.NoError(t, err) } assert.Equal(t, tt.wantOut, got) }) } } // Creates a temporary directory with the structure below. Returns // a cleanup function that will remove the directory and all of its // contents. The cleanup function should be wrapped in a defer statement. // // | root // |-- rootFile.txt // |-- subDir1 // | |-- subDir1_file.txt // | // |-- subDir2 // |-- subDir2_file.go // |-- subDir2_file.txt func createTestDir(t *testing.T) (cleanupFn func()) { t.Helper() // Make Directories rootDir := t.TempDir() // Move workspace to temporary directory t.Chdir(rootDir) // Make subdirectories err := os.Mkdir(filepath.Join(rootDir, "subDir1"), 0755) if err != nil { t.Fatal(err) } err = os.Mkdir(filepath.Join(rootDir, "subDir2"), 0755) if err != nil { t.Fatal(err) } // Make Files err = os.WriteFile(filepath.Join(rootDir, "rootFile.txt"), []byte(""), 0644) if err != nil { t.Fatal(err) } err = os.WriteFile(filepath.Join(rootDir, "subDir1", "subDir1_file.txt"), []byte(""), 0o644) if err != nil { t.Fatal(err) } err = os.WriteFile(filepath.Join(rootDir, "subDir2", "subDir2_file.go"), []byte(""), 0o644) if err != nil { t.Fatal(err) } err = os.WriteFile(filepath.Join(rootDir, "subDir2", "subDir2_file.txt"), []byte(""), 0o644) if err != nil { t.Fatal(err) } cleanupFn = func() { os.RemoveAll(rootDir) } return cleanupFn }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmdutil/cmdgroup.go
pkg/cmdutil/cmdgroup.go
package cmdutil import "github.com/spf13/cobra" func AddGroup(parent *cobra.Command, title string, cmds ...*cobra.Command) { g := &cobra.Group{ Title: title, ID: title, } parent.AddGroup(g) for _, c := range cmds { c.GroupID = g.ID parent.AddCommand(c) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmdutil/auth_check.go
pkg/cmdutil/auth_check.go
package cmdutil import ( "reflect" "github.com/cli/cli/v2/internal/gh" "github.com/spf13/cobra" "github.com/spf13/pflag" ) const skipAuthCheckAnnotation = "skipAuthCheck" func DisableAuthCheck(cmd *cobra.Command) { if cmd.Annotations == nil { cmd.Annotations = map[string]string{} } cmd.Annotations[skipAuthCheckAnnotation] = "true" } func DisableAuthCheckFlag(flag *pflag.Flag) { if flag.Annotations == nil { flag.Annotations = map[string][]string{} } flag.Annotations[skipAuthCheckAnnotation] = []string{"true"} } func CheckAuth(cfg gh.Config) bool { if cfg.Authentication().HasEnvToken() { return true } if len(cfg.Authentication().Hosts()) > 0 { return true } return false } func IsAuthCheckEnabled(cmd *cobra.Command) bool { switch cmd.Name() { case "help", cobra.ShellCompRequestCmd, cobra.ShellCompNoDescRequestCmd: return false } for c := cmd; c.Parent() != nil; c = c.Parent() { // Check whether any command marked as DisableAuthCheck is set if c.Annotations != nil && c.Annotations[skipAuthCheckAnnotation] == "true" { return false } // Check whether any flag marked as DisableAuthCheckFlag is set var skipAuthCheck bool c.Flags().Visit(func(f *pflag.Flag) { if f.Annotations != nil && reflect.DeepEqual(f.Annotations[skipAuthCheckAnnotation], []string{"true"}) { skipAuthCheck = true } }) if skipAuthCheck { return false } } return true }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmdutil/factory.go
pkg/cmdutil/factory.go
package cmdutil import ( "net/http" "os" "path/filepath" "strings" "github.com/cli/cli/v2/context" "github.com/cli/cli/v2/git" "github.com/cli/cli/v2/internal/browser" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/prompter" "github.com/cli/cli/v2/pkg/extensions" "github.com/cli/cli/v2/pkg/iostreams" ) type Factory struct { AppVersion string ExecutableName string Browser browser.Browser ExtensionManager extensions.ExtensionManager GitClient *git.Client IOStreams *iostreams.IOStreams Prompter prompter.Prompter BaseRepo func() (ghrepo.Interface, error) Branch func() (string, error) Config func() (gh.Config, error) HttpClient func() (*http.Client, error) // PlainHttpClient is a special HTTP client that does not automatically set // auth and other headers. This is meant to be used in situations where the // client needs to specify the headers itself (e.g. during login). PlainHttpClient func() (*http.Client, error) Remotes func() (context.Remotes, error) } // Executable is the path to the currently invoked binary func (f *Factory) Executable() string { ghPath := os.Getenv("GH_PATH") if ghPath != "" { return ghPath } if !strings.ContainsRune(f.ExecutableName, os.PathSeparator) { f.ExecutableName = executable(f.ExecutableName) } return f.ExecutableName } // Finds the location of the executable for the current process as it's found in PATH, respecting symlinks. // If the process couldn't determine its location, return fallbackName. If the executable wasn't found in // PATH, return the absolute location to the program. // // The idea is that the result of this function is callable in the future and refers to the same // installation of gh, even across upgrades. This is needed primarily for Homebrew, which installs software // under a location such as `/usr/local/Cellar/gh/1.13.1/bin/gh` and symlinks it from `/usr/local/bin/gh`. // When the version is upgraded, Homebrew will often delete older versions, but keep the symlink. Because of // this, we want to refer to the `gh` binary as `/usr/local/bin/gh` and not as its internal Homebrew // location. // // None of this would be needed if we could just refer to GitHub CLI as `gh`, i.e. without using an absolute // path. However, for some reason Homebrew does not include `/usr/local/bin` in PATH when it invokes git // commands to update its taps. If `gh` (no path) is being used as git credential helper, as set up by `gh // auth login`, running `brew update` will print out authentication errors as git is unable to locate // Homebrew-installed `gh`. func executable(fallbackName string) string { exe, err := os.Executable() if err != nil { return fallbackName } base := filepath.Base(exe) path := os.Getenv("PATH") for _, dir := range filepath.SplitList(path) { p, err := filepath.Abs(filepath.Join(dir, base)) if err != nil { continue } f, err := os.Lstat(p) if err != nil { continue } if p == exe { return p } else if f.Mode()&os.ModeSymlink != 0 { realP, err := filepath.EvalSymlinks(p) if err != nil { continue } realExe, err := filepath.EvalSymlinks(exe) if err != nil { continue } if realP == realExe { return p } } } return exe }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmdutil/args.go
pkg/cmdutil/args.go
package cmdutil import ( "fmt" "path/filepath" "github.com/spf13/cobra" "github.com/spf13/pflag" ) func MinimumArgs(n int, msg string) cobra.PositionalArgs { if msg == "" { return cobra.MinimumNArgs(1) } return func(cmd *cobra.Command, args []string) error { if len(args) < n { return FlagErrorf("%s", msg) } return nil } } func ExactArgs(n int, msg string) cobra.PositionalArgs { return func(cmd *cobra.Command, args []string) error { if len(args) > n { return FlagErrorf("too many arguments") } if len(args) < n { return FlagErrorf("%s", msg) } return nil } } func NoArgsQuoteReminder(cmd *cobra.Command, args []string) error { if len(args) < 1 { return nil } errMsg := fmt.Sprintf("unknown argument %q", args[0]) if len(args) > 1 { errMsg = fmt.Sprintf("unknown arguments %q", args) } hasValueFlag := false cmd.Flags().Visit(func(f *pflag.Flag) { if f.Value.Type() != "bool" { hasValueFlag = true } }) if hasValueFlag { errMsg += "; please quote all values that have spaces" } return FlagErrorf("%s", errMsg) } // Partition takes a slice of any type T and separates it into two slices // of the same type based on the provided predicate function. Any item // that returns true for the predicate will be included in the first slice // returned, and any item that returns false for the predicate will be // included in the second slice returned. func Partition[T any](slice []T, predicate func(T) bool) ([]T, []T) { var matching, nonMatching []T for _, item := range slice { if predicate(item) { matching = append(matching, item) } else { nonMatching = append(nonMatching, item) } } return matching, nonMatching } // GlobPaths expands a list of file patterns into a list of file paths. // If no files match a pattern, that pattern will return an error. // If no pattern is passed, this returns an empty list and no error. // // For information on supported glob patterns, see // https://pkg.go.dev/path/filepath#Match func GlobPaths(patterns []string) ([]string, error) { expansions := []string{} for _, pattern := range patterns { matches, err := filepath.Glob(pattern) if err != nil { return nil, fmt.Errorf("%s: %v", pattern, err) } if len(matches) == 0 { return []string{}, fmt.Errorf("no matches found for `%s`", pattern) } expansions = append(expansions, matches...) } return expansions, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmdutil/file_input.go
pkg/cmdutil/file_input.go
package cmdutil import ( "io" "os" ) func ReadFile(filename string, stdin io.ReadCloser) ([]byte, error) { if filename == "-" { b, err := io.ReadAll(stdin) _ = stdin.Close() return b, err } return os.ReadFile(filename) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/cmdutil/legacy.go
pkg/cmdutil/legacy.go
package cmdutil import ( "fmt" "os" "github.com/cli/cli/v2/internal/gh" ) // TODO: consider passing via Factory // TODO: support per-hostname settings func DetermineEditor(cf func() (gh.Config, error)) (string, error) { editorCommand := os.Getenv("GH_EDITOR") if editorCommand == "" { cfg, err := cf() if err != nil { return "", fmt.Errorf("could not read config: %w", err) } editorCommand = cfg.Editor("").Value } return editorCommand, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/iostreams/iostreams_test.go
pkg/iostreams/iostreams_test.go
package iostreams import ( "bufio" "fmt" "os" "testing" ) func TestStopAlternateScreenBuffer(t *testing.T) { ios, _, stdout, _ := Test() ios.SetAlternateScreenBufferEnabled(true) ios.StartAlternateScreenBuffer() fmt.Fprint(ios.Out, "test") ios.StopAlternateScreenBuffer() // Stopping a subsequent time should no-op. ios.StopAlternateScreenBuffer() const want = "\x1b[?1049htest\x1b[?1049l" if got := stdout.String(); got != want { t.Errorf("after IOStreams.StopAlternateScreenBuffer() got %q, want %q", got, want) } } func TestIOStreams_pager(t *testing.T) { t.Skip("TODO: fix this test in race detection mode") ios, _, stdout, _ := Test() ios.SetStdoutTTY(true) ios.SetPager(fmt.Sprintf("%s -test.run=TestHelperProcess --", os.Args[0])) t.Setenv("GH_WANT_HELPER_PROCESS", "1") if err := ios.StartPager(); err != nil { t.Fatal(err) } if _, err := fmt.Fprintln(ios.Out, "line1"); err != nil { t.Errorf("error writing line 1: %v", err) } if _, err := fmt.Fprintln(ios.Out, "line2"); err != nil { t.Errorf("error writing line 2: %v", err) } ios.StopPager() wants := "pager: line1\npager: line2\n" if got := stdout.String(); got != wants { t.Errorf("expected %q, got %q", wants, got) } } func TestHelperProcess(t *testing.T) { if os.Getenv("GH_WANT_HELPER_PROCESS") != "1" { return } scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { fmt.Printf("pager: %s\n", scanner.Text()) } if err := scanner.Err(); err != nil { fmt.Fprintf(os.Stderr, "error reading stdin: %v", err) os.Exit(1) } os.Exit(0) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/iostreams/iostreams_progress_indicator_test.go
pkg/iostreams/iostreams_progress_indicator_test.go
//go:build !windows package iostreams import ( "fmt" "io" "os" "strings" "testing" "time" "github.com/Netflix/go-expect" "github.com/creack/pty" "github.com/hinshun/vt10x" "github.com/stretchr/testify/require" ) func TestStartProgressIndicatorWithLabel(t *testing.T) { osOut := os.Stdout defer func() { os.Stdout = osOut }() // Why do we need a channel in these tests to implement a timeout instead of // relying on expect's timeout? // // Well, expect's timeout is based on the maximum time of a single read // from the console. This works in cases like prompting where we block // waiting for input because the console is not ready to be read. // But in this case, we are not blocking waiting for input and stdout // can be constantly read. This means the timeout will never be reached // in the event of a expectation failure. // To fix this, we need to implement our own timeout that is based // specifically on the total time spent reading the console and waiting // for the target string instead of the max time for a single read // from the console. t.Run("progress indicator respects GH_SPINNER_DISABLED is true", func(t *testing.T) { console := newTestVirtualTerminal(t) io := newTestIOStreams(t, console, true) done := make(chan error) go func() { _, err := console.ExpectString("Working...") done <- err }() io.StartProgressIndicatorWithLabel("") defer io.StopProgressIndicator() select { case err := <-done: require.NoError(t, err) case <-time.After(2 * time.Second): t.Fatal("Test timed out waiting for progress indicator") } }) t.Run("progress indicator respects GH_SPINNER_DISABLED is false", func(t *testing.T) { console := newTestVirtualTerminal(t) io := newTestIOStreams(t, console, false) done := make(chan error) go func() { _, err := console.ExpectString("⣾") done <- err }() io.StartProgressIndicatorWithLabel("") defer io.StopProgressIndicator() select { case err := <-done: require.NoError(t, err) case <-time.After(2 * time.Second): t.Fatal("Test timed out waiting for progress indicator") } }) t.Run("progress indicator with GH_SPINNER_DISABLED shows label", func(t *testing.T) { console := newTestVirtualTerminal(t) io := newTestIOStreams(t, console, true) progressIndicatorLabel := "downloading happiness" done := make(chan error) go func() { _, err := console.ExpectString(progressIndicatorLabel + "...") done <- err }() io.StartProgressIndicatorWithLabel(progressIndicatorLabel) defer io.StopProgressIndicator() select { case err := <-done: require.NoError(t, err) case <-time.After(2 * time.Second): t.Fatal("Test timed out waiting for progress indicator") } }) t.Run("progress indicator shows label and spinner", func(t *testing.T) { console := newTestVirtualTerminal(t) io := newTestIOStreams(t, console, false) progressIndicatorLabel := "downloading happiness" done := make(chan error) go func() { _, err := console.ExpectString(progressIndicatorLabel) require.NoError(t, err) _, err = console.ExpectString("⣾") done <- err }() io.StartProgressIndicatorWithLabel(progressIndicatorLabel) defer io.StopProgressIndicator() select { case err := <-done: require.NoError(t, err) case <-time.After(2 * time.Second): t.Fatal("Test timed out waiting for progress indicator") } }) t.Run("multiple calls to start progress indicator with GH_SPINNER_DISABLED prints additional labels", func(t *testing.T) { console := newTestVirtualTerminal(t) io := newTestIOStreams(t, console, true) progressIndicatorLabel1 := "downloading happiness" progressIndicatorLabel2 := "downloading sadness" done := make(chan error) go func() { _, err := console.ExpectString(progressIndicatorLabel1 + "...") require.NoError(t, err) _, err = console.ExpectString(progressIndicatorLabel2 + "...") done <- err }() io.StartProgressIndicatorWithLabel(progressIndicatorLabel1) defer io.StopProgressIndicator() io.StartProgressIndicatorWithLabel(progressIndicatorLabel2) select { case err := <-done: require.NoError(t, err) case <-time.After(2 * time.Second): t.Fatal("Test timed out waiting for progress indicator") } }) } func newTestVirtualTerminal(t *testing.T) *expect.Console { t.Helper() // Create a PTY and hook up a virtual terminal emulator ptm, pts, err := pty.Open() require.NoError(t, err) term := vt10x.New(vt10x.WithWriter(pts)) // Create a console via Expect that allows scripting against the terminal consoleOpts := []expect.ConsoleOpt{ expect.WithStdin(ptm), expect.WithStdout(term), expect.WithCloser(ptm, pts), failOnExpectError(t), failOnSendError(t), expect.WithDefaultTimeout(time.Second), } console, err := expect.NewConsole(consoleOpts...) require.NoError(t, err) t.Cleanup(func() { testCloser(t, console) }) return console } func newTestIOStreams(t *testing.T, console *expect.Console, spinnerDisabled bool) *IOStreams { t.Helper() in := console.Tty() out := console.Tty() errOut := console.Tty() // Because the briandowns/spinner checks os.Stdout directly, // we need this hack to trick it into allowing the spinner to print... os.Stdout = out io := &IOStreams{ In: in, Out: out, ErrOut: errOut, term: fakeTerm{}, } io.progressIndicatorEnabled = true io.SetSpinnerDisabled(spinnerDisabled) return io } // failOnExpectError adds an observer that will fail the test in a standardised way // if any expectation on the command output fails, without requiring an explicit // assertion. // // Use WithRelaxedIO to disable this behaviour. func failOnExpectError(t *testing.T) expect.ConsoleOpt { t.Helper() return expect.WithExpectObserver( func(matchers []expect.Matcher, buf string, err error) { t.Helper() if err == nil { return } if len(matchers) == 0 { t.Fatalf("Error occurred while matching %q: %s\n", buf, err) } var criteria []string for _, matcher := range matchers { criteria = append(criteria, fmt.Sprintf("%q", matcher.Criteria())) } t.Fatalf("Failed to find [%s] in %q: %s\n", strings.Join(criteria, ", "), buf, err) }, ) } // failOnSendError adds an observer that will fail the test in a standardised way // if any sending of input fails, without requiring an explicit assertion. // // Use WithRelaxedIO to disable this behaviour. func failOnSendError(t *testing.T) expect.ConsoleOpt { t.Helper() return expect.WithSendObserver( func(msg string, n int, err error) { t.Helper() if err != nil { t.Fatalf("Failed to send %q: %s\n", msg, err) } if len(msg) != n { t.Fatalf("Only sent %d of %d bytes for %q\n", n, len(msg), msg) } }, ) } // testCloser is a helper to fail the test if a Closer fails to close. func testCloser(t *testing.T, closer io.Closer) { t.Helper() if err := closer.Close(); err != nil { t.Errorf("Close failed: %s", err) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/iostreams/color_test.go
pkg/iostreams/color_test.go
package iostreams import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) func TestLabel(t *testing.T) { tests := []struct { name string hex string text string wants string cs *ColorScheme }{ { name: "truecolor", hex: "fc0303", text: "red", wants: "\033[38;2;252;3;3mred\033[0m", cs: &ColorScheme{ Enabled: true, EightBitColor: true, TrueColor: true, ColorLabels: true, }, }, { name: "no truecolor", hex: "fc0303", text: "red", wants: "red", cs: &ColorScheme{ Enabled: true, EightBitColor: true, ColorLabels: true, }, }, { name: "no color", hex: "fc0303", text: "red", wants: "red", cs: &ColorScheme{ ColorLabels: true, }, }, { name: "invalid hex", hex: "fc0", text: "red", wants: "red", cs: &ColorScheme{ ColorLabels: true, }, }, { name: "no color labels", hex: "fc0303", text: "red", wants: "red", cs: &ColorScheme{ Enabled: true, EightBitColor: true, ColorLabels: true, }, }, } for _, tt := range tests { output := tt.cs.Label(tt.hex, tt.text) assert.Equal(t, tt.wants, output) } } func TestTableHeader(t *testing.T) { reset := "\x1b[0m" defaultUnderline := "\x1b[0;4;39m" brightBlackUnderline := "\x1b[0;4;90m" dimBlackUnderline := "\x1b[0;2;4;37m" tests := []struct { name string cs *ColorScheme input string expected string }{ { name: "when color is disabled, text is not stylized", cs: &ColorScheme{ Accessible: true, Theme: NoTheme, }, input: "this should not be stylized", expected: "this should not be stylized", }, { name: "when 4-bit color is enabled but no theme, 4-bit default color and underline are used", cs: &ColorScheme{ Enabled: true, Accessible: true, Theme: NoTheme, }, input: "this should have no explicit color but underlined", expected: fmt.Sprintf("%sthis should have no explicit color but underlined%s", defaultUnderline, reset), }, { name: "when 4-bit color is enabled and theme is light, 4-bit dark color and underline are used", cs: &ColorScheme{ Enabled: true, Accessible: true, Theme: LightTheme, }, input: "this should have dark foreground color and underlined", expected: fmt.Sprintf("%sthis should have dark foreground color and underlined%s", brightBlackUnderline, reset), }, { name: "when 4-bit color is enabled and theme is dark, 4-bit light color and underline are used", cs: &ColorScheme{ Enabled: true, Accessible: true, Theme: DarkTheme, }, input: "this should have light foreground color and underlined", expected: fmt.Sprintf("%sthis should have light foreground color and underlined%s", dimBlackUnderline, reset), }, { name: "when 8-bit color is enabled but no theme, 4-bit default color and underline are used", cs: &ColorScheme{ Enabled: true, EightBitColor: true, Accessible: true, Theme: NoTheme, }, input: "this should have no explicit color but underlined", expected: fmt.Sprintf("%sthis should have no explicit color but underlined%s", defaultUnderline, reset), }, { name: "when 8-bit color is enabled and theme is light, 4-bit dark color and underline are used", cs: &ColorScheme{ Enabled: true, EightBitColor: true, Accessible: true, Theme: LightTheme, }, input: "this should have dark foreground color and underlined", expected: fmt.Sprintf("%sthis should have dark foreground color and underlined%s", brightBlackUnderline, reset), }, { name: "when 8-bit color is true and theme is dark, 4-bit light color and underline are used", cs: &ColorScheme{ Enabled: true, EightBitColor: true, Accessible: true, Theme: DarkTheme, }, input: "this should have light foreground color and underlined", expected: fmt.Sprintf("%sthis should have light foreground color and underlined%s", dimBlackUnderline, reset), }, { name: "when 24-bit color is enabled but no theme, 4-bit default color and underline are used", cs: &ColorScheme{ Enabled: true, EightBitColor: true, TrueColor: true, Accessible: true, Theme: NoTheme, }, input: "this should have no explicit color but underlined", expected: fmt.Sprintf("%sthis should have no explicit color but underlined%s", defaultUnderline, reset), }, { name: "when 24-bit color is enabled and theme is light, 4-bit dark color and underline are used", cs: &ColorScheme{ Enabled: true, EightBitColor: true, TrueColor: true, Accessible: true, Theme: LightTheme, }, input: "this should have dark foreground color and underlined", expected: fmt.Sprintf("%sthis should have dark foreground color and underlined%s", brightBlackUnderline, reset), }, { name: "when 24-bit color is true and theme is dark, 4-bit light color and underline are used", cs: &ColorScheme{ Enabled: true, EightBitColor: true, TrueColor: true, Accessible: true, Theme: DarkTheme, }, input: "this should have light foreground color and underlined", expected: fmt.Sprintf("%sthis should have light foreground color and underlined%s", dimBlackUnderline, reset), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert.Equal(t, tt.expected, tt.cs.TableHeader(tt.input)) }) } } func TestMuted(t *testing.T) { reset := "\x1b[0m" gray4bit := "\x1b[0;90m" gray8bit := "\x1b[38;5;242m" brightBlack4bit := "\x1b[0;90m" dimBlack4bit := "\x1b[0;2;37m" tests := []struct { name string cs *ColorScheme input string expected string }{ { name: "when color is disabled but accessible colors are disabled, text is not stylized", cs: &ColorScheme{}, input: "this should not be stylized", expected: "this should not be stylized", }, { name: "when 4-bit color is enabled but accessible colors are disabled, legacy 4-bit gray color is used", cs: &ColorScheme{ Enabled: true, }, input: "this should be 4-bit gray", expected: fmt.Sprintf("%sthis should be 4-bit gray%s", gray4bit, reset), }, { name: "when 8-bit color is enabled but accessible colors are disabled, legacy 8-bit gray color is used", cs: &ColorScheme{ Enabled: true, EightBitColor: true, }, input: "this should be 8-bit gray", expected: fmt.Sprintf("%sthis should be 8-bit gray%s", gray8bit, reset), }, { name: "when 24-bit color is enabled but accessible colors are disabled, legacy 8-bit gray color is used", cs: &ColorScheme{ Enabled: true, EightBitColor: true, TrueColor: true, }, input: "this should be 8-bit gray", expected: fmt.Sprintf("%sthis should be 8-bit gray%s", gray8bit, reset), }, { name: "when 4-bit color is enabled and theme is dark, 4-bit light color is used", cs: &ColorScheme{ Enabled: true, EightBitColor: true, TrueColor: true, Accessible: true, Theme: DarkTheme, }, input: "this should be 4-bit dim black", expected: fmt.Sprintf("%sthis should be 4-bit dim black%s", dimBlack4bit, reset), }, { name: "when 4-bit color is enabled and theme is light, 4-bit dark color is used", cs: &ColorScheme{ Enabled: true, EightBitColor: true, TrueColor: true, Accessible: true, Theme: LightTheme, }, input: "this should be 4-bit bright black", expected: fmt.Sprintf("%sthis should be 4-bit bright black%s", brightBlack4bit, reset), }, { name: "when 4-bit color is enabled but no theme, 4-bit default color is used", cs: &ColorScheme{ Enabled: true, EightBitColor: true, TrueColor: true, Accessible: true, Theme: NoTheme, }, input: "this should have no explicit color", expected: "this should have no explicit color", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert.Equal(t, tt.expected, tt.cs.Muted(tt.input)) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/iostreams/console.go
pkg/iostreams/console.go
//go:build !windows package iostreams import "os" func hasAlternateScreenBuffer(_ bool) bool { // on non-Windows, we just assume that alternate screen buffer is supported in most cases return os.Getenv("TERM") != "dumb" }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/iostreams/color.go
pkg/iostreams/color.go
package iostreams import ( "fmt" "strconv" "strings" "github.com/mgutz/ansi" ) const ( NoTheme = "none" DarkTheme = "dark" LightTheme = "light" highlightStyle = "black:yellow" ) // Special cases like darkThemeTableHeader / lightThemeTableHeader are necessary when using color and modifiers // (bold, underline, dim) because ansi.ColorFunc requires a foreground color and resets formats. var ( magenta = ansi.ColorFunc("magenta") cyan = ansi.ColorFunc("cyan") red = ansi.ColorFunc("red") yellow = ansi.ColorFunc("yellow") blue = ansi.ColorFunc("blue") green = ansi.ColorFunc("green") gray = ansi.ColorFunc("black+h") bold = ansi.ColorFunc("default+b") cyanBold = ansi.ColorFunc("cyan+b") greenBold = ansi.ColorFunc("green+b") highlightStart = ansi.ColorCode(highlightStyle) highlight = ansi.ColorFunc(highlightStyle) darkThemeMuted = ansi.ColorFunc("white+d") darkThemeTableHeader = ansi.ColorFunc("white+du") lightThemeMuted = ansi.ColorFunc("black+h") lightThemeTableHeader = ansi.ColorFunc("black+hu") noThemeTableHeader = ansi.ColorFunc("default+u") gray256 = func(t string) string { return fmt.Sprintf("\x1b[%d;5;%dm%s\x1b[0m", 38, 242, t) } ) // ColorScheme controls how text is colored based upon terminal capabilities and user preferences. type ColorScheme struct { // Enabled is whether color is used at all. Enabled bool // EightBitColor is whether the terminal supports 8-bit, 256 colors. EightBitColor bool // TrueColor is whether the terminal supports 24-bit, 16 million colors. TrueColor bool // Accessible is whether colors must be base 16 colors that users can customize in terminal preferences. Accessible bool // ColorLabels is whether labels are colored based on their truecolor RGB hex color. ColorLabels bool // Theme is the terminal background color theme used to contextually color text for light, dark, or none at all. Theme string } func (c *ColorScheme) Bold(t string) string { if !c.Enabled { return t } return bold(t) } func (c *ColorScheme) Boldf(t string, args ...interface{}) string { return c.Bold(fmt.Sprintf(t, args...)) } func (c *ColorScheme) Muted(t string) string { // Fallback to previous logic if accessible colors preview is disabled. if !c.Accessible { return c.Gray(t) } // Muted text is only stylized if color is enabled. if !c.Enabled { return t } switch c.Theme { case LightTheme: return lightThemeMuted(t) case DarkTheme: return darkThemeMuted(t) default: return t } } func (c *ColorScheme) Mutedf(t string, args ...interface{}) string { return c.Muted(fmt.Sprintf(t, args...)) } func (c *ColorScheme) Red(t string) string { if !c.Enabled { return t } return red(t) } func (c *ColorScheme) Redf(t string, args ...interface{}) string { return c.Red(fmt.Sprintf(t, args...)) } func (c *ColorScheme) Yellow(t string) string { if !c.Enabled { return t } return yellow(t) } func (c *ColorScheme) Yellowf(t string, args ...interface{}) string { return c.Yellow(fmt.Sprintf(t, args...)) } func (c *ColorScheme) Green(t string) string { if !c.Enabled { return t } return green(t) } func (c *ColorScheme) Greenf(t string, args ...interface{}) string { return c.Green(fmt.Sprintf(t, args...)) } func (c *ColorScheme) GreenBold(t string) string { if !c.Enabled { return t } return greenBold(t) } // Deprecated: Use Muted instead for thematically contrasting color. func (c *ColorScheme) Gray(t string) string { if !c.Enabled { return t } if c.EightBitColor { return gray256(t) } return gray(t) } // Deprecated: Use Mutedf instead for thematically contrasting color. func (c *ColorScheme) Grayf(t string, args ...interface{}) string { return c.Gray(fmt.Sprintf(t, args...)) } func (c *ColorScheme) Magenta(t string) string { if !c.Enabled { return t } return magenta(t) } func (c *ColorScheme) Magentaf(t string, args ...interface{}) string { return c.Magenta(fmt.Sprintf(t, args...)) } func (c *ColorScheme) Cyan(t string) string { if !c.Enabled { return t } return cyan(t) } func (c *ColorScheme) Cyanf(t string, args ...interface{}) string { return c.Cyan(fmt.Sprintf(t, args...)) } func (c *ColorScheme) CyanBold(t string) string { if !c.Enabled { return t } return cyanBold(t) } func (c *ColorScheme) Blue(t string) string { if !c.Enabled { return t } return blue(t) } func (c *ColorScheme) Bluef(t string, args ...interface{}) string { return c.Blue(fmt.Sprintf(t, args...)) } func (c *ColorScheme) SuccessIcon() string { return c.SuccessIconWithColor(c.Green) } func (c *ColorScheme) SuccessIconWithColor(colo func(string) string) string { return colo("✓") } func (c *ColorScheme) WarningIcon() string { return c.Yellow("!") } func (c *ColorScheme) FailureIcon() string { return c.FailureIconWithColor(c.Red) } func (c *ColorScheme) FailureIconWithColor(colo func(string) string) string { return colo("X") } func (c *ColorScheme) HighlightStart() string { if !c.Enabled { return "" } return highlightStart } func (c *ColorScheme) Highlight(t string) string { if !c.Enabled { return t } return highlight(t) } func (c *ColorScheme) Reset() string { if !c.Enabled { return "" } return ansi.Reset } func (c *ColorScheme) ColorFromString(s string) func(string) string { s = strings.ToLower(s) var fn func(string) string switch s { case "bold": fn = c.Bold case "red": fn = c.Red case "yellow": fn = c.Yellow case "green": fn = c.Green case "gray": fn = c.Muted case "magenta": fn = c.Magenta case "cyan": fn = c.Cyan case "blue": fn = c.Blue default: fn = func(s string) string { return s } } return fn } // Label stylizes text based on label's RGB hex color. func (c *ColorScheme) Label(hex string, x string) string { if !c.Enabled || !c.TrueColor || !c.ColorLabels || len(hex) != 6 { return x } r, _ := strconv.ParseInt(hex[0:2], 16, 64) g, _ := strconv.ParseInt(hex[2:4], 16, 64) b, _ := strconv.ParseInt(hex[4:6], 16, 64) return fmt.Sprintf("\033[38;2;%d;%d;%dm%s\033[0m", r, g, b, x) } func (c *ColorScheme) TableHeader(t string) string { // Table headers are only stylized if color is enabled including underline modifier. if !c.Enabled { return t } switch c.Theme { case DarkTheme: return darkThemeTableHeader(t) case LightTheme: return lightThemeTableHeader(t) default: return noThemeTableHeader(t) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/iostreams/epipe_other.go
pkg/iostreams/epipe_other.go
//go:build !windows package iostreams import ( "errors" "syscall" ) func isEpipeError(err error) bool { return errors.Is(err, syscall.EPIPE) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/iostreams/console_windows.go
pkg/iostreams/console_windows.go
//go:build windows package iostreams func hasAlternateScreenBuffer(hasTrueColor bool) bool { // on Windows we just assume that alternate screen buffer is supported if we // enabled virtual terminal processing, which in turn enables truecolor return hasTrueColor }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/iostreams/iostreams.go
pkg/iostreams/iostreams.go
package iostreams import ( "bytes" "errors" "fmt" "io" "os" "os/exec" "os/signal" "strings" "sync" "time" "github.com/briandowns/spinner" ghTerm "github.com/cli/go-gh/v2/pkg/term" "github.com/cli/safeexec" "github.com/google/shlex" "github.com/mattn/go-colorable" "github.com/mattn/go-isatty" ) const DefaultWidth = 80 // ErrClosedPagerPipe is the error returned when writing to a pager that has been closed. type ErrClosedPagerPipe struct { error } type fileWriter interface { io.Writer Fd() uintptr } type fileReader interface { io.ReadCloser Fd() uintptr } type term interface { IsTerminalOutput() bool IsColorEnabled() bool Is256ColorSupported() bool IsTrueColorSupported() bool Theme() string Size() (int, int, error) } type IOStreams struct { term term In fileReader Out fileWriter ErrOut fileWriter terminalTheme string progressIndicatorEnabled bool progressIndicator *spinner.Spinner progressIndicatorMu sync.Mutex spinnerDisabled bool alternateScreenBufferEnabled bool alternateScreenBufferActive bool alternateScreenBufferMu sync.Mutex stdinTTYOverride bool stdinIsTTY bool stdoutTTYOverride bool stdoutIsTTY bool stderrTTYOverride bool stderrIsTTY bool colorOverride bool colorEnabled bool colorLabels bool accessibleColorsEnabled bool pagerCommand string pagerProcess *os.Process neverPrompt bool accessiblePrompterEnabled bool TempFileOverride *os.File } func (s *IOStreams) ColorEnabled() bool { if s.colorOverride { return s.colorEnabled } return s.term.IsColorEnabled() } func (s *IOStreams) ColorSupport256() bool { if s.colorOverride { return s.colorEnabled } return s.term.Is256ColorSupported() } func (s *IOStreams) HasTrueColor() bool { if s.colorOverride { return s.colorEnabled } return s.term.IsTrueColorSupported() } func (s *IOStreams) ColorLabels() bool { return s.colorLabels } // DetectTerminalTheme is a utility to call before starting the output pager so that the terminal background // can be reliably detected. func (s *IOStreams) DetectTerminalTheme() { if !s.ColorEnabled() || s.pagerProcess != nil { s.terminalTheme = "none" return } style := os.Getenv("GLAMOUR_STYLE") if style != "" && style != "auto" { // ensure GLAMOUR_STYLE takes precedence over "light" and "dark" themes s.terminalTheme = "none" return } s.terminalTheme = s.term.Theme() } // TerminalTheme returns "light", "dark", or "none" depending on the background color of the terminal. func (s *IOStreams) TerminalTheme() string { if s.terminalTheme == "" { s.DetectTerminalTheme() } return s.terminalTheme } func (s *IOStreams) SetColorEnabled(colorEnabled bool) { s.colorOverride = true s.colorEnabled = colorEnabled } func (s *IOStreams) SetColorLabels(colorLabels bool) { s.colorLabels = colorLabels } func (s *IOStreams) SetStdinTTY(isTTY bool) { s.stdinTTYOverride = true s.stdinIsTTY = isTTY } func (s *IOStreams) IsStdinTTY() bool { if s.stdinTTYOverride { return s.stdinIsTTY } if stdin, ok := s.In.(*os.File); ok { return isTerminal(stdin) } return false } func (s *IOStreams) SetStdoutTTY(isTTY bool) { s.stdoutTTYOverride = true s.stdoutIsTTY = isTTY } func (s *IOStreams) IsStdoutTTY() bool { if s.stdoutTTYOverride { return s.stdoutIsTTY } // support GH_FORCE_TTY if s.term.IsTerminalOutput() { return true } stdout, ok := s.Out.(*os.File) return ok && isCygwinTerminal(stdout.Fd()) } func (s *IOStreams) SetStderrTTY(isTTY bool) { s.stderrTTYOverride = true s.stderrIsTTY = isTTY } func (s *IOStreams) IsStderrTTY() bool { if s.stderrTTYOverride { return s.stderrIsTTY } if stderr, ok := s.ErrOut.(*os.File); ok { return isTerminal(stderr) } return false } func (s *IOStreams) SetPager(cmd string) { s.pagerCommand = cmd } func (s *IOStreams) GetPager() string { return s.pagerCommand } func (s *IOStreams) StartPager() error { if s.pagerCommand == "" || s.pagerCommand == "cat" || !s.IsStdoutTTY() { return nil } pagerArgs, err := shlex.Split(s.pagerCommand) if err != nil { return err } pagerEnv := os.Environ() for i := len(pagerEnv) - 1; i >= 0; i-- { if strings.HasPrefix(pagerEnv[i], "PAGER=") { pagerEnv = append(pagerEnv[0:i], pagerEnv[i+1:]...) } } if _, ok := os.LookupEnv("LESS"); !ok { pagerEnv = append(pagerEnv, "LESS=FRX") } if _, ok := os.LookupEnv("LV"); !ok { pagerEnv = append(pagerEnv, "LV=-c") } pagerExe, err := safeexec.LookPath(pagerArgs[0]) if err != nil { return err } pagerCmd := exec.Command(pagerExe, pagerArgs[1:]...) pagerCmd.Env = pagerEnv pagerCmd.Stdout = s.Out pagerCmd.Stderr = s.ErrOut pagedOut, err := pagerCmd.StdinPipe() if err != nil { return err } s.Out = &fdWriteCloser{ fd: s.Out.Fd(), WriteCloser: &pagerWriter{pagedOut}, } err = pagerCmd.Start() if err != nil { return err } s.pagerProcess = pagerCmd.Process return nil } func (s *IOStreams) StopPager() { if s.pagerProcess == nil { return } // if a pager was started, we're guaranteed to have a WriteCloser _ = s.Out.(io.WriteCloser).Close() _, _ = s.pagerProcess.Wait() s.pagerProcess = nil } func (s *IOStreams) CanPrompt() bool { if s.neverPrompt { return false } return s.IsStdinTTY() && s.IsStdoutTTY() } func (s *IOStreams) GetNeverPrompt() bool { return s.neverPrompt } func (s *IOStreams) SetNeverPrompt(v bool) { s.neverPrompt = v } func (s *IOStreams) GetSpinnerDisabled() bool { return s.spinnerDisabled } func (s *IOStreams) SetSpinnerDisabled(v bool) { s.spinnerDisabled = v } func (s *IOStreams) StartProgressIndicator() { s.StartProgressIndicatorWithLabel("") } func (s *IOStreams) StartProgressIndicatorWithLabel(label string) { if !s.progressIndicatorEnabled { return } if s.spinnerDisabled { // If the spinner is disabled, simply print a // textual progress indicator and return. // This means that s.ProgressIndicator will be nil. // See also: the comment on StopProgressIndicator() s.startTextualProgressIndicator(label) return } s.progressIndicatorMu.Lock() defer s.progressIndicatorMu.Unlock() if s.progressIndicator != nil { if label == "" { s.progressIndicator.Prefix = "" } else { s.progressIndicator.Prefix = label + " " } return } // https://github.com/briandowns/spinner#available-character-sets // ⣾ ⣷ ⣽ ⣻ ⡿ spinnerStyle := spinner.CharSets[11] sp := spinner.New(spinnerStyle, 120*time.Millisecond, spinner.WithWriter(s.ErrOut), spinner.WithColor("fgCyan")) if label != "" { sp.Prefix = label + " " } sp.Start() s.progressIndicator = sp } func (s *IOStreams) startTextualProgressIndicator(label string) { s.progressIndicatorMu.Lock() defer s.progressIndicatorMu.Unlock() // Default label when spinner disabled is "Working..." if label == "" { label = "Working..." } // Add an ellipsis to the label if it doesn't already have one. ellipsis := "..." if !strings.HasSuffix(label, ellipsis) { label = label + ellipsis } fmt.Fprintf(s.ErrOut, "%s%s", s.ColorScheme().Cyan(label), "\n") } // StopProgressIndicator stops the progress indicator if it is running. // Note that a textual progess indicator does not create a progress indicator, // so this method is a no-op in that case. func (s *IOStreams) StopProgressIndicator() { s.progressIndicatorMu.Lock() defer s.progressIndicatorMu.Unlock() if s.progressIndicator == nil { return } s.progressIndicator.Stop() s.progressIndicator = nil } func (s *IOStreams) RunWithProgress(label string, run func() error) error { s.StartProgressIndicatorWithLabel(label) defer s.StopProgressIndicator() return run() } func (s *IOStreams) StartAlternateScreenBuffer() { if s.alternateScreenBufferEnabled { s.alternateScreenBufferMu.Lock() defer s.alternateScreenBufferMu.Unlock() if _, err := fmt.Fprint(s.Out, "\x1b[?1049h"); err == nil { s.alternateScreenBufferActive = true ch := make(chan os.Signal, 1) signal.Notify(ch, os.Interrupt) go func() { <-ch s.StopAlternateScreenBuffer() os.Exit(1) }() } } } func (s *IOStreams) StopAlternateScreenBuffer() { s.alternateScreenBufferMu.Lock() defer s.alternateScreenBufferMu.Unlock() if s.alternateScreenBufferActive { fmt.Fprint(s.Out, "\x1b[?1049l") s.alternateScreenBufferActive = false } } func (s *IOStreams) SetAlternateScreenBufferEnabled(enabled bool) { s.alternateScreenBufferEnabled = enabled } func (s *IOStreams) RefreshScreen() { if s.IsStdoutTTY() { // Move cursor to 0,0 fmt.Fprint(s.Out, "\x1b[0;0H") // Clear from cursor to bottom of screen fmt.Fprint(s.Out, "\x1b[J") } } // TerminalWidth returns the width of the terminal that controls the process func (s *IOStreams) TerminalWidth() int { w, _, err := s.term.Size() if err == nil && w > 0 { return w } return DefaultWidth } func (s *IOStreams) ColorScheme() *ColorScheme { return &ColorScheme{ Enabled: s.ColorEnabled(), EightBitColor: s.ColorSupport256(), TrueColor: s.HasTrueColor(), Accessible: s.AccessibleColorsEnabled(), ColorLabels: s.ColorLabels(), Theme: s.TerminalTheme(), } } func (s *IOStreams) ReadUserFile(fn string) ([]byte, error) { var r io.ReadCloser if fn == "-" { r = s.In } else { var err error r, err = os.Open(fn) if err != nil { return nil, err } } defer r.Close() return io.ReadAll(r) } func (s *IOStreams) TempFile(dir, pattern string) (*os.File, error) { if s.TempFileOverride != nil { return s.TempFileOverride, nil } return os.CreateTemp(dir, pattern) } func (s *IOStreams) SetAccessibleColorsEnabled(enabled bool) { s.accessibleColorsEnabled = enabled } func (s *IOStreams) AccessibleColorsEnabled() bool { return s.accessibleColorsEnabled } func (s *IOStreams) SetAccessiblePrompterEnabled(enabled bool) { s.accessiblePrompterEnabled = enabled } func (s *IOStreams) AccessiblePrompterEnabled() bool { return s.accessiblePrompterEnabled } func System() *IOStreams { terminal := ghTerm.FromEnv() var stdout fileWriter = os.Stdout // On Windows with no virtual terminal processing support, translate ANSI escape // sequences to console syscalls. if colorableStdout := colorable.NewColorable(os.Stdout); colorableStdout != os.Stdout { // Ensure that the file descriptor of the original stdout is preserved. stdout = &fdWriter{ fd: os.Stdout.Fd(), Writer: colorableStdout, } } var stderr fileWriter = os.Stderr // On Windows with no virtual terminal processing support, translate ANSI escape // sequences to console syscalls. if colorableStderr := colorable.NewColorable(os.Stderr); colorableStderr != os.Stderr { // Ensure that the file descriptor of the original stderr is preserved. stderr = &fdWriter{ fd: os.Stderr.Fd(), Writer: colorableStderr, } } io := &IOStreams{ In: os.Stdin, Out: stdout, ErrOut: stderr, pagerCommand: os.Getenv("PAGER"), term: &terminal, } stdoutIsTTY := io.IsStdoutTTY() stderrIsTTY := io.IsStderrTTY() if stdoutIsTTY && stderrIsTTY { io.progressIndicatorEnabled = true } if stdoutIsTTY && hasAlternateScreenBuffer(terminal.IsTrueColorSupported()) { io.alternateScreenBufferEnabled = true } return io } type fakeTerm struct{} func (t fakeTerm) IsTerminalOutput() bool { return false } func (t fakeTerm) IsColorEnabled() bool { return false } func (t fakeTerm) Is256ColorSupported() bool { return false } func (t fakeTerm) IsTrueColorSupported() bool { return false } func (t fakeTerm) Theme() string { return "" } func (t fakeTerm) Size() (int, int, error) { return 80, -1, nil } func Test() (*IOStreams, *bytes.Buffer, *bytes.Buffer, *bytes.Buffer) { in := &bytes.Buffer{} out := &bytes.Buffer{} errOut := &bytes.Buffer{} io := &IOStreams{ In: &fdReader{ fd: 0, ReadCloser: io.NopCloser(in), }, Out: &fdWriter{fd: 1, Writer: out}, ErrOut: &fdWriter{fd: 2, Writer: errOut}, term: &fakeTerm{}, } io.SetStdinTTY(false) io.SetStdoutTTY(false) io.SetStderrTTY(false) return io, in, out, errOut } func isTerminal(f *os.File) bool { return ghTerm.IsTerminal(f) || isCygwinTerminal(f.Fd()) } func isCygwinTerminal(fd uintptr) bool { return isatty.IsCygwinTerminal(fd) } // pagerWriter implements a WriteCloser that wraps all EPIPE errors in an ErrClosedPagerPipe type. type pagerWriter struct { io.WriteCloser } func (w *pagerWriter) Write(d []byte) (int, error) { n, err := w.WriteCloser.Write(d) if err != nil && (errors.Is(err, io.ErrClosedPipe) || isEpipeError(err)) { return n, &ErrClosedPagerPipe{err} } return n, err } // fdWriter represents a wrapped stdout Writer that preserves the original file descriptor type fdWriter struct { io.Writer fd uintptr } func (w *fdWriter) Fd() uintptr { return w.fd } // fdWriteCloser represents a wrapped stdout Writer that preserves the original file descriptor type fdWriteCloser struct { io.WriteCloser fd uintptr } func (w *fdWriteCloser) Fd() uintptr { return w.fd } // fdReader represents a wrapped stdin ReadCloser that preserves the original file descriptor type fdReader struct { io.ReadCloser fd uintptr } func (r *fdReader) Fd() uintptr { return r.fd }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/iostreams/epipe_windows.go
pkg/iostreams/epipe_windows.go
package iostreams import ( "errors" "syscall" ) func isEpipeError(err error) bool { // 232 is Windows error code ERROR_NO_DATA, "The pipe is being closed". return errors.Is(err, syscall.Errno(232)) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/extensions/extension_mock.go
pkg/extensions/extension_mock.go
// Code generated by moq; DO NOT EDIT. // github.com/matryer/moq package extensions import ( "sync" ) // Ensure, that ExtensionMock does implement Extension. // If this is not the case, regenerate this file with moq. var _ Extension = &ExtensionMock{} // ExtensionMock is a mock implementation of Extension. // // func TestSomethingThatUsesExtension(t *testing.T) { // // // make and configure a mocked Extension // mockedExtension := &ExtensionMock{ // CurrentVersionFunc: func() string { // panic("mock out the CurrentVersion method") // }, // IsBinaryFunc: func() bool { // panic("mock out the IsBinary method") // }, // IsLocalFunc: func() bool { // panic("mock out the IsLocal method") // }, // IsPinnedFunc: func() bool { // panic("mock out the IsPinned method") // }, // LatestVersionFunc: func() string { // panic("mock out the LatestVersion method") // }, // NameFunc: func() string { // panic("mock out the Name method") // }, // OwnerFunc: func() string { // panic("mock out the Owner method") // }, // PathFunc: func() string { // panic("mock out the Path method") // }, // URLFunc: func() string { // panic("mock out the URL method") // }, // UpdateAvailableFunc: func() bool { // panic("mock out the UpdateAvailable method") // }, // } // // // use mockedExtension in code that requires Extension // // and then make assertions. // // } type ExtensionMock struct { // CurrentVersionFunc mocks the CurrentVersion method. CurrentVersionFunc func() string // IsBinaryFunc mocks the IsBinary method. IsBinaryFunc func() bool // IsLocalFunc mocks the IsLocal method. IsLocalFunc func() bool // IsPinnedFunc mocks the IsPinned method. IsPinnedFunc func() bool // LatestVersionFunc mocks the LatestVersion method. LatestVersionFunc func() string // NameFunc mocks the Name method. NameFunc func() string // OwnerFunc mocks the Owner method. OwnerFunc func() string // PathFunc mocks the Path method. PathFunc func() string // URLFunc mocks the URL method. URLFunc func() string // UpdateAvailableFunc mocks the UpdateAvailable method. UpdateAvailableFunc func() bool // calls tracks calls to the methods. calls struct { // CurrentVersion holds details about calls to the CurrentVersion method. CurrentVersion []struct { } // IsBinary holds details about calls to the IsBinary method. IsBinary []struct { } // IsLocal holds details about calls to the IsLocal method. IsLocal []struct { } // IsPinned holds details about calls to the IsPinned method. IsPinned []struct { } // LatestVersion holds details about calls to the LatestVersion method. LatestVersion []struct { } // Name holds details about calls to the Name method. Name []struct { } // Owner holds details about calls to the Owner method. Owner []struct { } // Path holds details about calls to the Path method. Path []struct { } // URL holds details about calls to the URL method. URL []struct { } // UpdateAvailable holds details about calls to the UpdateAvailable method. UpdateAvailable []struct { } } lockCurrentVersion sync.RWMutex lockIsBinary sync.RWMutex lockIsLocal sync.RWMutex lockIsPinned sync.RWMutex lockLatestVersion sync.RWMutex lockName sync.RWMutex lockOwner sync.RWMutex lockPath sync.RWMutex lockURL sync.RWMutex lockUpdateAvailable sync.RWMutex } // CurrentVersion calls CurrentVersionFunc. func (mock *ExtensionMock) CurrentVersion() string { if mock.CurrentVersionFunc == nil { panic("ExtensionMock.CurrentVersionFunc: method is nil but Extension.CurrentVersion was just called") } callInfo := struct { }{} mock.lockCurrentVersion.Lock() mock.calls.CurrentVersion = append(mock.calls.CurrentVersion, callInfo) mock.lockCurrentVersion.Unlock() return mock.CurrentVersionFunc() } // CurrentVersionCalls gets all the calls that were made to CurrentVersion. // Check the length with: // // len(mockedExtension.CurrentVersionCalls()) func (mock *ExtensionMock) CurrentVersionCalls() []struct { } { var calls []struct { } mock.lockCurrentVersion.RLock() calls = mock.calls.CurrentVersion mock.lockCurrentVersion.RUnlock() return calls } // IsBinary calls IsBinaryFunc. func (mock *ExtensionMock) IsBinary() bool { if mock.IsBinaryFunc == nil { panic("ExtensionMock.IsBinaryFunc: method is nil but Extension.IsBinary was just called") } callInfo := struct { }{} mock.lockIsBinary.Lock() mock.calls.IsBinary = append(mock.calls.IsBinary, callInfo) mock.lockIsBinary.Unlock() return mock.IsBinaryFunc() } // IsBinaryCalls gets all the calls that were made to IsBinary. // Check the length with: // // len(mockedExtension.IsBinaryCalls()) func (mock *ExtensionMock) IsBinaryCalls() []struct { } { var calls []struct { } mock.lockIsBinary.RLock() calls = mock.calls.IsBinary mock.lockIsBinary.RUnlock() return calls } // IsLocal calls IsLocalFunc. func (mock *ExtensionMock) IsLocal() bool { if mock.IsLocalFunc == nil { panic("ExtensionMock.IsLocalFunc: method is nil but Extension.IsLocal was just called") } callInfo := struct { }{} mock.lockIsLocal.Lock() mock.calls.IsLocal = append(mock.calls.IsLocal, callInfo) mock.lockIsLocal.Unlock() return mock.IsLocalFunc() } // IsLocalCalls gets all the calls that were made to IsLocal. // Check the length with: // // len(mockedExtension.IsLocalCalls()) func (mock *ExtensionMock) IsLocalCalls() []struct { } { var calls []struct { } mock.lockIsLocal.RLock() calls = mock.calls.IsLocal mock.lockIsLocal.RUnlock() return calls } // IsPinned calls IsPinnedFunc. func (mock *ExtensionMock) IsPinned() bool { if mock.IsPinnedFunc == nil { panic("ExtensionMock.IsPinnedFunc: method is nil but Extension.IsPinned was just called") } callInfo := struct { }{} mock.lockIsPinned.Lock() mock.calls.IsPinned = append(mock.calls.IsPinned, callInfo) mock.lockIsPinned.Unlock() return mock.IsPinnedFunc() } // IsPinnedCalls gets all the calls that were made to IsPinned. // Check the length with: // // len(mockedExtension.IsPinnedCalls()) func (mock *ExtensionMock) IsPinnedCalls() []struct { } { var calls []struct { } mock.lockIsPinned.RLock() calls = mock.calls.IsPinned mock.lockIsPinned.RUnlock() return calls } // LatestVersion calls LatestVersionFunc. func (mock *ExtensionMock) LatestVersion() string { if mock.LatestVersionFunc == nil { panic("ExtensionMock.LatestVersionFunc: method is nil but Extension.LatestVersion was just called") } callInfo := struct { }{} mock.lockLatestVersion.Lock() mock.calls.LatestVersion = append(mock.calls.LatestVersion, callInfo) mock.lockLatestVersion.Unlock() return mock.LatestVersionFunc() } // LatestVersionCalls gets all the calls that were made to LatestVersion. // Check the length with: // // len(mockedExtension.LatestVersionCalls()) func (mock *ExtensionMock) LatestVersionCalls() []struct { } { var calls []struct { } mock.lockLatestVersion.RLock() calls = mock.calls.LatestVersion mock.lockLatestVersion.RUnlock() return calls } // Name calls NameFunc. func (mock *ExtensionMock) Name() string { if mock.NameFunc == nil { panic("ExtensionMock.NameFunc: method is nil but Extension.Name was just called") } callInfo := struct { }{} mock.lockName.Lock() mock.calls.Name = append(mock.calls.Name, callInfo) mock.lockName.Unlock() return mock.NameFunc() } // NameCalls gets all the calls that were made to Name. // Check the length with: // // len(mockedExtension.NameCalls()) func (mock *ExtensionMock) NameCalls() []struct { } { var calls []struct { } mock.lockName.RLock() calls = mock.calls.Name mock.lockName.RUnlock() return calls } // Owner calls OwnerFunc. func (mock *ExtensionMock) Owner() string { if mock.OwnerFunc == nil { panic("ExtensionMock.OwnerFunc: method is nil but Extension.Owner was just called") } callInfo := struct { }{} mock.lockOwner.Lock() mock.calls.Owner = append(mock.calls.Owner, callInfo) mock.lockOwner.Unlock() return mock.OwnerFunc() } // OwnerCalls gets all the calls that were made to Owner. // Check the length with: // // len(mockedExtension.OwnerCalls()) func (mock *ExtensionMock) OwnerCalls() []struct { } { var calls []struct { } mock.lockOwner.RLock() calls = mock.calls.Owner mock.lockOwner.RUnlock() return calls } // Path calls PathFunc. func (mock *ExtensionMock) Path() string { if mock.PathFunc == nil { panic("ExtensionMock.PathFunc: method is nil but Extension.Path was just called") } callInfo := struct { }{} mock.lockPath.Lock() mock.calls.Path = append(mock.calls.Path, callInfo) mock.lockPath.Unlock() return mock.PathFunc() } // PathCalls gets all the calls that were made to Path. // Check the length with: // // len(mockedExtension.PathCalls()) func (mock *ExtensionMock) PathCalls() []struct { } { var calls []struct { } mock.lockPath.RLock() calls = mock.calls.Path mock.lockPath.RUnlock() return calls } // URL calls URLFunc. func (mock *ExtensionMock) URL() string { if mock.URLFunc == nil { panic("ExtensionMock.URLFunc: method is nil but Extension.URL was just called") } callInfo := struct { }{} mock.lockURL.Lock() mock.calls.URL = append(mock.calls.URL, callInfo) mock.lockURL.Unlock() return mock.URLFunc() } // URLCalls gets all the calls that were made to URL. // Check the length with: // // len(mockedExtension.URLCalls()) func (mock *ExtensionMock) URLCalls() []struct { } { var calls []struct { } mock.lockURL.RLock() calls = mock.calls.URL mock.lockURL.RUnlock() return calls } // UpdateAvailable calls UpdateAvailableFunc. func (mock *ExtensionMock) UpdateAvailable() bool { if mock.UpdateAvailableFunc == nil { panic("ExtensionMock.UpdateAvailableFunc: method is nil but Extension.UpdateAvailable was just called") } callInfo := struct { }{} mock.lockUpdateAvailable.Lock() mock.calls.UpdateAvailable = append(mock.calls.UpdateAvailable, callInfo) mock.lockUpdateAvailable.Unlock() return mock.UpdateAvailableFunc() } // UpdateAvailableCalls gets all the calls that were made to UpdateAvailable. // Check the length with: // // len(mockedExtension.UpdateAvailableCalls()) func (mock *ExtensionMock) UpdateAvailableCalls() []struct { } { var calls []struct { } mock.lockUpdateAvailable.RLock() calls = mock.calls.UpdateAvailable mock.lockUpdateAvailable.RUnlock() return calls }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/extensions/extension.go
pkg/extensions/extension.go
package extensions import ( "io" "github.com/cli/cli/v2/internal/ghrepo" ) type ExtTemplateType int const ( GitTemplateType ExtTemplateType = 0 GoBinTemplateType ExtTemplateType = 1 OtherBinTemplateType ExtTemplateType = 2 ) //go:generate moq -rm -out extension_mock.go . Extension type Extension interface { Name() string // Extension Name without gh- Path() string // Path to executable URL() string CurrentVersion() string LatestVersion() string IsPinned() bool UpdateAvailable() bool IsBinary() bool IsLocal() bool Owner() string } //go:generate moq -rm -out manager_mock.go . ExtensionManager type ExtensionManager interface { List() []Extension Install(ghrepo.Interface, string) error InstallLocal(dir string) error Upgrade(name string, force bool) error Remove(name string) error Dispatch(args []string, stdin io.Reader, stdout, stderr io.Writer) (bool, error) Create(name string, tmplType ExtTemplateType) error EnableDryRunMode() UpdateDir(name string) string }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/extensions/manager_mock.go
pkg/extensions/manager_mock.go
// Code generated by moq; DO NOT EDIT. // github.com/matryer/moq package extensions import ( "github.com/cli/cli/v2/internal/ghrepo" "io" "sync" ) // Ensure, that ExtensionManagerMock does implement ExtensionManager. // If this is not the case, regenerate this file with moq. var _ ExtensionManager = &ExtensionManagerMock{} // ExtensionManagerMock is a mock implementation of ExtensionManager. // // func TestSomethingThatUsesExtensionManager(t *testing.T) { // // // make and configure a mocked ExtensionManager // mockedExtensionManager := &ExtensionManagerMock{ // CreateFunc: func(name string, tmplType ExtTemplateType) error { // panic("mock out the Create method") // }, // DispatchFunc: func(args []string, stdin io.Reader, stdout io.Writer, stderr io.Writer) (bool, error) { // panic("mock out the Dispatch method") // }, // EnableDryRunModeFunc: func() { // panic("mock out the EnableDryRunMode method") // }, // InstallFunc: func(interfaceMoqParam ghrepo.Interface, s string) error { // panic("mock out the Install method") // }, // InstallLocalFunc: func(dir string) error { // panic("mock out the InstallLocal method") // }, // ListFunc: func() []Extension { // panic("mock out the List method") // }, // RemoveFunc: func(name string) error { // panic("mock out the Remove method") // }, // UpdateDirFunc: func(name string) string { // panic("mock out the UpdateDir method") // }, // UpgradeFunc: func(name string, force bool) error { // panic("mock out the Upgrade method") // }, // } // // // use mockedExtensionManager in code that requires ExtensionManager // // and then make assertions. // // } type ExtensionManagerMock struct { // CreateFunc mocks the Create method. CreateFunc func(name string, tmplType ExtTemplateType) error // DispatchFunc mocks the Dispatch method. DispatchFunc func(args []string, stdin io.Reader, stdout io.Writer, stderr io.Writer) (bool, error) // EnableDryRunModeFunc mocks the EnableDryRunMode method. EnableDryRunModeFunc func() // InstallFunc mocks the Install method. InstallFunc func(interfaceMoqParam ghrepo.Interface, s string) error // InstallLocalFunc mocks the InstallLocal method. InstallLocalFunc func(dir string) error // ListFunc mocks the List method. ListFunc func() []Extension // RemoveFunc mocks the Remove method. RemoveFunc func(name string) error // UpdateDirFunc mocks the UpdateDir method. UpdateDirFunc func(name string) string // UpgradeFunc mocks the Upgrade method. UpgradeFunc func(name string, force bool) error // calls tracks calls to the methods. calls struct { // Create holds details about calls to the Create method. Create []struct { // Name is the name argument value. Name string // TmplType is the tmplType argument value. TmplType ExtTemplateType } // Dispatch holds details about calls to the Dispatch method. Dispatch []struct { // Args is the args argument value. Args []string // Stdin is the stdin argument value. Stdin io.Reader // Stdout is the stdout argument value. Stdout io.Writer // Stderr is the stderr argument value. Stderr io.Writer } // EnableDryRunMode holds details about calls to the EnableDryRunMode method. EnableDryRunMode []struct { } // Install holds details about calls to the Install method. Install []struct { // InterfaceMoqParam is the interfaceMoqParam argument value. InterfaceMoqParam ghrepo.Interface // S is the s argument value. S string } // InstallLocal holds details about calls to the InstallLocal method. InstallLocal []struct { // Dir is the dir argument value. Dir string } // List holds details about calls to the List method. List []struct { } // Remove holds details about calls to the Remove method. Remove []struct { // Name is the name argument value. Name string } // UpdateDir holds details about calls to the UpdateDir method. UpdateDir []struct { // Name is the name argument value. Name string } // Upgrade holds details about calls to the Upgrade method. Upgrade []struct { // Name is the name argument value. Name string // Force is the force argument value. Force bool } } lockCreate sync.RWMutex lockDispatch sync.RWMutex lockEnableDryRunMode sync.RWMutex lockInstall sync.RWMutex lockInstallLocal sync.RWMutex lockList sync.RWMutex lockRemove sync.RWMutex lockUpdateDir sync.RWMutex lockUpgrade sync.RWMutex } // Create calls CreateFunc. func (mock *ExtensionManagerMock) Create(name string, tmplType ExtTemplateType) error { if mock.CreateFunc == nil { panic("ExtensionManagerMock.CreateFunc: method is nil but ExtensionManager.Create was just called") } callInfo := struct { Name string TmplType ExtTemplateType }{ Name: name, TmplType: tmplType, } mock.lockCreate.Lock() mock.calls.Create = append(mock.calls.Create, callInfo) mock.lockCreate.Unlock() return mock.CreateFunc(name, tmplType) } // CreateCalls gets all the calls that were made to Create. // Check the length with: // // len(mockedExtensionManager.CreateCalls()) func (mock *ExtensionManagerMock) CreateCalls() []struct { Name string TmplType ExtTemplateType } { var calls []struct { Name string TmplType ExtTemplateType } mock.lockCreate.RLock() calls = mock.calls.Create mock.lockCreate.RUnlock() return calls } // Dispatch calls DispatchFunc. func (mock *ExtensionManagerMock) Dispatch(args []string, stdin io.Reader, stdout io.Writer, stderr io.Writer) (bool, error) { if mock.DispatchFunc == nil { panic("ExtensionManagerMock.DispatchFunc: method is nil but ExtensionManager.Dispatch was just called") } callInfo := struct { Args []string Stdin io.Reader Stdout io.Writer Stderr io.Writer }{ Args: args, Stdin: stdin, Stdout: stdout, Stderr: stderr, } mock.lockDispatch.Lock() mock.calls.Dispatch = append(mock.calls.Dispatch, callInfo) mock.lockDispatch.Unlock() return mock.DispatchFunc(args, stdin, stdout, stderr) } // DispatchCalls gets all the calls that were made to Dispatch. // Check the length with: // // len(mockedExtensionManager.DispatchCalls()) func (mock *ExtensionManagerMock) DispatchCalls() []struct { Args []string Stdin io.Reader Stdout io.Writer Stderr io.Writer } { var calls []struct { Args []string Stdin io.Reader Stdout io.Writer Stderr io.Writer } mock.lockDispatch.RLock() calls = mock.calls.Dispatch mock.lockDispatch.RUnlock() return calls } // EnableDryRunMode calls EnableDryRunModeFunc. func (mock *ExtensionManagerMock) EnableDryRunMode() { if mock.EnableDryRunModeFunc == nil { panic("ExtensionManagerMock.EnableDryRunModeFunc: method is nil but ExtensionManager.EnableDryRunMode was just called") } callInfo := struct { }{} mock.lockEnableDryRunMode.Lock() mock.calls.EnableDryRunMode = append(mock.calls.EnableDryRunMode, callInfo) mock.lockEnableDryRunMode.Unlock() mock.EnableDryRunModeFunc() } // EnableDryRunModeCalls gets all the calls that were made to EnableDryRunMode. // Check the length with: // // len(mockedExtensionManager.EnableDryRunModeCalls()) func (mock *ExtensionManagerMock) EnableDryRunModeCalls() []struct { } { var calls []struct { } mock.lockEnableDryRunMode.RLock() calls = mock.calls.EnableDryRunMode mock.lockEnableDryRunMode.RUnlock() return calls } // Install calls InstallFunc. func (mock *ExtensionManagerMock) Install(interfaceMoqParam ghrepo.Interface, s string) error { if mock.InstallFunc == nil { panic("ExtensionManagerMock.InstallFunc: method is nil but ExtensionManager.Install was just called") } callInfo := struct { InterfaceMoqParam ghrepo.Interface S string }{ InterfaceMoqParam: interfaceMoqParam, S: s, } mock.lockInstall.Lock() mock.calls.Install = append(mock.calls.Install, callInfo) mock.lockInstall.Unlock() return mock.InstallFunc(interfaceMoqParam, s) } // InstallCalls gets all the calls that were made to Install. // Check the length with: // // len(mockedExtensionManager.InstallCalls()) func (mock *ExtensionManagerMock) InstallCalls() []struct { InterfaceMoqParam ghrepo.Interface S string } { var calls []struct { InterfaceMoqParam ghrepo.Interface S string } mock.lockInstall.RLock() calls = mock.calls.Install mock.lockInstall.RUnlock() return calls } // InstallLocal calls InstallLocalFunc. func (mock *ExtensionManagerMock) InstallLocal(dir string) error { if mock.InstallLocalFunc == nil { panic("ExtensionManagerMock.InstallLocalFunc: method is nil but ExtensionManager.InstallLocal was just called") } callInfo := struct { Dir string }{ Dir: dir, } mock.lockInstallLocal.Lock() mock.calls.InstallLocal = append(mock.calls.InstallLocal, callInfo) mock.lockInstallLocal.Unlock() return mock.InstallLocalFunc(dir) } // InstallLocalCalls gets all the calls that were made to InstallLocal. // Check the length with: // // len(mockedExtensionManager.InstallLocalCalls()) func (mock *ExtensionManagerMock) InstallLocalCalls() []struct { Dir string } { var calls []struct { Dir string } mock.lockInstallLocal.RLock() calls = mock.calls.InstallLocal mock.lockInstallLocal.RUnlock() return calls } // List calls ListFunc. func (mock *ExtensionManagerMock) List() []Extension { if mock.ListFunc == nil { panic("ExtensionManagerMock.ListFunc: method is nil but ExtensionManager.List was just called") } callInfo := struct { }{} mock.lockList.Lock() mock.calls.List = append(mock.calls.List, callInfo) mock.lockList.Unlock() return mock.ListFunc() } // ListCalls gets all the calls that were made to List. // Check the length with: // // len(mockedExtensionManager.ListCalls()) func (mock *ExtensionManagerMock) ListCalls() []struct { } { var calls []struct { } mock.lockList.RLock() calls = mock.calls.List mock.lockList.RUnlock() return calls } // Remove calls RemoveFunc. func (mock *ExtensionManagerMock) Remove(name string) error { if mock.RemoveFunc == nil { panic("ExtensionManagerMock.RemoveFunc: method is nil but ExtensionManager.Remove was just called") } callInfo := struct { Name string }{ Name: name, } mock.lockRemove.Lock() mock.calls.Remove = append(mock.calls.Remove, callInfo) mock.lockRemove.Unlock() return mock.RemoveFunc(name) } // RemoveCalls gets all the calls that were made to Remove. // Check the length with: // // len(mockedExtensionManager.RemoveCalls()) func (mock *ExtensionManagerMock) RemoveCalls() []struct { Name string } { var calls []struct { Name string } mock.lockRemove.RLock() calls = mock.calls.Remove mock.lockRemove.RUnlock() return calls } // UpdateDir calls UpdateDirFunc. func (mock *ExtensionManagerMock) UpdateDir(name string) string { if mock.UpdateDirFunc == nil { panic("ExtensionManagerMock.UpdateDirFunc: method is nil but ExtensionManager.UpdateDir was just called") } callInfo := struct { Name string }{ Name: name, } mock.lockUpdateDir.Lock() mock.calls.UpdateDir = append(mock.calls.UpdateDir, callInfo) mock.lockUpdateDir.Unlock() return mock.UpdateDirFunc(name) } // UpdateDirCalls gets all the calls that were made to UpdateDir. // Check the length with: // // len(mockedExtensionManager.UpdateDirCalls()) func (mock *ExtensionManagerMock) UpdateDirCalls() []struct { Name string } { var calls []struct { Name string } mock.lockUpdateDir.RLock() calls = mock.calls.UpdateDir mock.lockUpdateDir.RUnlock() return calls } // Upgrade calls UpgradeFunc. func (mock *ExtensionManagerMock) Upgrade(name string, force bool) error { if mock.UpgradeFunc == nil { panic("ExtensionManagerMock.UpgradeFunc: method is nil but ExtensionManager.Upgrade was just called") } callInfo := struct { Name string Force bool }{ Name: name, Force: force, } mock.lockUpgrade.Lock() mock.calls.Upgrade = append(mock.calls.Upgrade, callInfo) mock.lockUpgrade.Unlock() return mock.UpgradeFunc(name, force) } // UpgradeCalls gets all the calls that were made to Upgrade. // Check the length with: // // len(mockedExtensionManager.UpgradeCalls()) func (mock *ExtensionManagerMock) UpgradeCalls() []struct { Name string Force bool } { var calls []struct { Name string Force bool } mock.lockUpgrade.RLock() calls = mock.calls.Upgrade mock.lockUpgrade.RUnlock() return calls }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/jsonfieldstest/jsonfieldstest.go
pkg/jsonfieldstest/jsonfieldstest.go
package jsonfieldstest import ( "strings" "testing" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func jsonFieldsFor(cmd *cobra.Command) []string { // This annotation is added by the `cmdutil.AddJSONFlags` function. // // This is an extremely janky way to get access to this information but due to the fact we pass // around concrete cobra.Command structs, there's no viable way to have typed access to the fields. // // It's also kind of fragile because it's several hops away from the code that actually validates the usage // of these flags, so it's possible for things to get out of sync. stringFields, ok := cmd.Annotations["help:json-fields"] if !ok { return nil } return strings.Split(stringFields, ",") } // NewCmdFunc represents the typical function signature we use for creating commands e.g. `NewCmdView`. // // It is generic over `T` as each command construction has their own Options type e.g. `ViewOptions` type NewCmdFunc[T any] func(f *cmdutil.Factory, runF func(*T) error) *cobra.Command // ExpectCommandToSupportJSONFields asserts that the provided command supports exactly the provided fields. // Ordering of the expected fields is not important. // // Make sure you are not pointing to the same slice of fields in the test and the implementation. // It can be a little tedious to rewrite the fields inline in the test but it's significantly more useful because: // - It forces the test author to think about and convey exactly the expected fields for a command // - It avoids accidentally adding fields to a command, and the test passing unintentionally func ExpectCommandToSupportJSONFields[T any](t *testing.T, fn NewCmdFunc[T], expectedFields []string) { t.Helper() actualFields := jsonFieldsFor(fn(&cmdutil.Factory{}, nil)) assert.Equal(t, len(actualFields), len(expectedFields), "expected number of fields to match") require.ElementsMatch(t, expectedFields, actualFields) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/option/option.go
pkg/option/option.go
// MIT License // Copyright (c) 2022 Tom Godkin // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // o provides an Option type to represent values that may or may not be present. // // This code was copies from https://github.com/BooleanCat/go-functional@ae5a155c0e997d1c5de53ea8b49109aca9c53d9f // and we've added the Map function and associated tests. It was pulled into the project because I believe if we're // using Option, it should be a core domain type rather than a dependency. package o import "fmt" // Option represents an optional value. The [Some] variant contains a value and // the [None] variant represents the absence of a value. type Option[T any] struct { value T present bool } // Some instantiates an [Option] with a value. func Some[T any](value T) Option[T] { return Option[T]{value, true} } // None instantiates an [Option] with no value. func None[T any]() Option[T] { return Option[T]{} } func SomeIfNonZero[T comparable](value T) Option[T] { // value is a zero value then return a None var zero T if value == zero { return None[T]() } return Some(value) } // String implements the [fmt.Stringer] interface. func (o Option[T]) String() string { if o.present { return fmt.Sprintf("Some(%v)", o.value) } return "None" } var _ fmt.Stringer = Option[struct{}]{} // Unwrap returns the underlying value of a [Some] variant, or panics if called // on a [None] variant. func (o Option[T]) Unwrap() T { if o.present { return o.value } panic("called `Option.Unwrap()` on a `None` value") } // UnwrapOr returns the underlying value of a [Some] variant, or the provided // value on a [None] variant. func (o Option[T]) UnwrapOr(value T) T { if o.present { return o.value } return value } // UnwrapOrElse returns the underlying value of a [Some] variant, or the result // of calling the provided function on a [None] variant. func (o Option[T]) UnwrapOrElse(f func() T) T { if o.present { return o.value } return f() } // UnwrapOrZero returns the underlying value of a [Some] variant, or the zero // value on a [None] variant. func (o Option[T]) UnwrapOrZero() T { if o.present { return o.value } var value T return value } // IsSome returns true if the [Option] is a [Some] variant. func (o Option[T]) IsSome() bool { return o.present } // IsNone returns true if the [Option] is a [None] variant. func (o Option[T]) IsNone() bool { return !o.present } // Value returns the underlying value and true for a [Some] variant, or the // zero value and false for a [None] variant. func (o Option[T]) Value() (T, bool) { return o.value, o.present } // Expect returns the underlying value for a [Some] variant, or panics with the // provided message for a [None] variant. func (o Option[T]) Expect(message string) T { if o.present { return o.value } panic(message) } // Map applies a function to the contained value of (if [Some]), or returns [None]. // // Use this function very sparingly as it can lead to very unidiomatic and surprising Go code. However, // there are times when used judiciiously, it is significantly more ergonomic than unwrapping the Option. func Map[T, U any](o Option[T], f func(T) U) Option[U] { if o.present { return Some(f(o.value)) } return None[U]() }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/option/option_test.go
pkg/option/option_test.go
// MIT License // Copyright (c) 2022 Tom Godkin // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. package o_test import ( "fmt" "testing" o "github.com/cli/cli/v2/pkg/option" "github.com/stretchr/testify/require" ) func ExampleOption_Unwrap() { fmt.Println(o.Some(4).Unwrap()) // Output: 4 } func ExampleOption_UnwrapOr() { fmt.Println(o.Some(4).UnwrapOr(3)) fmt.Println(o.None[int]().UnwrapOr(3)) // Output: // 4 // 3 } func ExampleOption_UnwrapOrElse() { fmt.Println(o.Some(4).UnwrapOrElse(func() int { return 3 })) fmt.Println(o.None[int]().UnwrapOrElse(func() int { return 3 })) // Output: // 4 // 3 } func ExampleOption_UnwrapOrZero() { fmt.Println(o.Some(4).UnwrapOrZero()) fmt.Println(o.None[int]().UnwrapOrZero()) // Output // 4 // 0 } func ExampleOption_IsSome() { fmt.Println(o.Some(4).IsSome()) fmt.Println(o.None[int]().IsSome()) // Output: // true // false } func ExampleOption_IsNone() { fmt.Println(o.Some(4).IsNone()) fmt.Println(o.None[int]().IsNone()) // Output: // false // true } func ExampleOption_Value() { value, ok := o.Some(4).Value() fmt.Println(value) fmt.Println(ok) // Output: // 4 // true } func ExampleOption_Expect() { fmt.Println(o.Some(4).Expect("oops")) // Output: 4 } func ExampleMap() { fmt.Println(o.Map(o.Some(2), double)) fmt.Println(o.Map(o.None[int](), double)) // Output: // Some(4) // None } func double(i int) int { return i * 2 } func TestSomeStringer(t *testing.T) { require.Equal(t, fmt.Sprintf("%s", o.Some("foo")), "Some(foo)") //nolint:gosimple require.Equal(t, fmt.Sprintf("%s", o.Some(42)), "Some(42)") //nolint:gosimple } func TestNoneStringer(t *testing.T) { require.Equal(t, fmt.Sprintf("%s", o.None[string]()), "None") //nolint:gosimple } func TestSomeUnwrap(t *testing.T) { require.Equal(t, o.Some(42).Unwrap(), 42) } func TestNoneUnwrap(t *testing.T) { defer func() { require.Equal(t, fmt.Sprint(recover()), "called `Option.Unwrap()` on a `None` value") }() o.None[string]().Unwrap() t.Error("did not panic") } func TestSomeUnwrapOr(t *testing.T) { require.Equal(t, o.Some(42).UnwrapOr(3), 42) } func TestNoneUnwrapOr(t *testing.T) { require.Equal(t, o.None[int]().UnwrapOr(3), 3) } func TestSomeUnwrapOrElse(t *testing.T) { require.Equal(t, o.Some(42).UnwrapOrElse(func() int { return 41 }), 42) } func TestNoneUnwrapOrElse(t *testing.T) { require.Equal(t, o.None[int]().UnwrapOrElse(func() int { return 41 }), 41) } func TestSomeUnwrapOrZero(t *testing.T) { require.Equal(t, o.Some(42).UnwrapOrZero(), 42) } func TestNoneUnwrapOrZero(t *testing.T) { require.Equal(t, o.None[int]().UnwrapOrZero(), 0) } func TestIsSome(t *testing.T) { require.True(t, o.Some(42).IsSome()) require.False(t, o.None[int]().IsSome()) } func TestIsNone(t *testing.T) { require.False(t, o.Some(42).IsNone()) require.True(t, o.None[int]().IsNone()) } func TestSomeValue(t *testing.T) { value, ok := o.Some(42).Value() require.Equal(t, value, 42) require.True(t, ok) } func TestNoneValue(t *testing.T) { value, ok := o.None[int]().Value() require.Equal(t, value, 0) require.False(t, ok) } func TestSomeExpect(t *testing.T) { require.Equal(t, o.Some(42).Expect("oops"), 42) } func TestNoneExpect(t *testing.T) { defer func() { require.Equal(t, fmt.Sprint(recover()), "oops") }() o.None[int]().Expect("oops") t.Error("did not panic") } func TestMap(t *testing.T) { require.Equal(t, o.Map(o.Some(2), double), o.Some(4)) require.True(t, o.Map(o.None[int](), double).IsNone()) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/ssh/ssh_keys.go
pkg/ssh/ssh_keys.go
package ssh import ( "errors" "fmt" "os" "os/exec" "path/filepath" "runtime" "github.com/cli/cli/v2/internal/config" "github.com/cli/cli/v2/internal/run" "github.com/cli/safeexec" ) type Context struct { configDir string keygenExe string } // NewContextForTests creates a new `ssh.Context` with internal properties set to the // specified values. It should only be used to inject test-specific setup. func NewContextForTests(configDir, keygenExe string) Context { return Context{ configDir, keygenExe, } } type KeyPair struct { PublicKeyPath string PrivateKeyPath string } var ErrKeyAlreadyExists = errors.New("SSH key already exists") func (c *Context) LocalPublicKeys() ([]string, error) { sshDir, err := c.SshDir() if err != nil { return nil, err } return filepath.Glob(filepath.Join(sshDir, "*.pub")) } func (c *Context) HasKeygen() bool { _, err := c.findKeygen() return err == nil } func (c *Context) GenerateSSHKey(keyName string, passphrase string) (*KeyPair, error) { keygenExe, err := c.findKeygen() if err != nil { return nil, err } sshDir, err := c.SshDir() if err != nil { return nil, err } err = os.MkdirAll(sshDir, 0700) if err != nil { return nil, fmt.Errorf("could not create .ssh directory: %w", err) } keyFile := filepath.Join(sshDir, keyName) keyPair := KeyPair{ PublicKeyPath: keyFile + ".pub", PrivateKeyPath: keyFile, } if _, err := os.Stat(keyFile); err == nil { // Still return keyPair because the caller might be OK with this - they can check the error with errors.Is(err, ErrKeyAlreadyExists) return &keyPair, ErrKeyAlreadyExists } if err := os.MkdirAll(filepath.Dir(keyFile), 0711); err != nil { return nil, err } keygenCmd := exec.Command(keygenExe, "-t", "ed25519", "-C", "", "-N", passphrase, "-f", keyFile) err = run.PrepareCmd(keygenCmd).Run() if err != nil { return nil, err } return &keyPair, nil } func (c *Context) SshDir() (string, error) { if c.configDir != "" { return c.configDir, nil } dir, err := config.HomeDirPath(".ssh") if err == nil { c.configDir = dir } return dir, err } func (c *Context) findKeygen() (string, error) { if c.keygenExe != "" { return c.keygenExe, nil } keygenExe, err := safeexec.LookPath("ssh-keygen") if err != nil && runtime.GOOS == "windows" { // We can try and find ssh-keygen in a Git for Windows install if gitPath, err := safeexec.LookPath("git"); err == nil { gitKeygen := filepath.Join(filepath.Dir(gitPath), "..", "usr", "bin", "ssh-keygen.exe") if _, err = os.Stat(gitKeygen); err == nil { return gitKeygen, nil } } } if err == nil { c.keygenExe = keygenExe } return keygenExe, err }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/findsh/find_windows.go
pkg/findsh/find_windows.go
package findsh import ( "os" "path/filepath" "github.com/cli/safeexec" ) func Find() (string, error) { shPath, shErr := safeexec.LookPath("sh") if shErr == nil { return shPath, nil } gitPath, err := safeexec.LookPath("git") if err != nil { return "", shErr } gitDir := filepath.Dir(gitPath) // regular Git for Windows install shPath = filepath.Join(gitDir, "..", "bin", "sh.exe") if _, err := os.Stat(shPath); err == nil { return filepath.Clean(shPath), nil } // git as a scoop shim shPath = filepath.Join(gitDir, "..", "apps", "git", "current", "bin", "sh.exe") if _, err := os.Stat(shPath); err == nil { return filepath.Clean(shPath), nil } return "", shErr }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/findsh/find.go
pkg/findsh/find.go
//go:build !windows package findsh import "os/exec" // Find locates the `sh` interpreter on the system. func Find() (string, error) { return exec.LookPath("sh") }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/jsoncolor/jsoncolor.go
pkg/jsoncolor/jsoncolor.go
package jsoncolor import ( "bytes" "encoding/json" "fmt" "io" "strings" ) const ( colorDelim = "1;38" // bright white colorKey = "1;34" // bright blue colorNull = "36" // cyan colorString = "32" // green colorBool = "33" // yellow ) type JsonWriter interface { Preface() []json.Delim } // Write colorized JSON output parsed from reader func Write(w io.Writer, r io.Reader, indent string) error { dec := json.NewDecoder(r) dec.UseNumber() var idx int var stack []json.Delim if jsonWriter, ok := w.(JsonWriter); ok { stack = append(stack, jsonWriter.Preface()...) } for { t, err := dec.Token() if err == io.EOF { break } if err != nil { return err } switch tt := t.(type) { case json.Delim: switch tt { case '{', '[': stack = append(stack, tt) idx = 0 fmt.Fprintf(w, "\x1b[%sm%s\x1b[m", colorDelim, tt) if dec.More() { fmt.Fprint(w, "\n", strings.Repeat(indent, len(stack))) } continue case '}', ']': stack = stack[:len(stack)-1] idx = 0 fmt.Fprintf(w, "\x1b[%sm%s\x1b[m", colorDelim, tt) } default: b, err := marshalJSON(tt) if err != nil { return err } isKey := len(stack) > 0 && stack[len(stack)-1] == '{' && idx%2 == 0 idx++ var color string if isKey { color = colorKey } else if tt == nil { color = colorNull } else { switch t.(type) { case string: color = colorString case bool: color = colorBool } } if color == "" { _, _ = w.Write(b) } else { fmt.Fprintf(w, "\x1b[%sm%s\x1b[m", color, b) } if isKey { fmt.Fprintf(w, "\x1b[%sm:\x1b[m ", colorDelim) continue } } if dec.More() { fmt.Fprintf(w, "\x1b[%sm,\x1b[m\n%s", colorDelim, strings.Repeat(indent, len(stack))) } else if len(stack) > 0 { fmt.Fprint(w, "\n", strings.Repeat(indent, len(stack)-1)) } else { fmt.Fprint(w, "\n") } } return nil } // WriteDelims writes delims in color and with the appropriate indent // based on the stack size returned from an io.Writer that implements JsonWriter.Preface(). func WriteDelims(w io.Writer, delims, indent string) error { var stack []json.Delim if jaw, ok := w.(JsonWriter); ok { stack = jaw.Preface() } fmt.Fprintf(w, "\x1b[%sm%s\x1b[m", colorDelim, delims) fmt.Fprint(w, "\n", strings.Repeat(indent, len(stack))) return nil } // marshalJSON works like json.Marshal but with HTML-escaping disabled func marshalJSON(v interface{}) ([]byte, error) { buf := bytes.Buffer{} enc := json.NewEncoder(&buf) enc.SetEscapeHTML(false) if err := enc.Encode(v); err != nil { return nil, err } bb := buf.Bytes() // omit trailing newline added by json.Encoder if len(bb) > 0 && bb[len(bb)-1] == '\n' { return bb[:len(bb)-1], nil } return bb, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/jsoncolor/jsoncolor_test.go
pkg/jsoncolor/jsoncolor_test.go
package jsoncolor import ( "bytes" "io" "testing" "github.com/google/go-cmp/cmp" ) func TestWrite(t *testing.T) { type args struct { r io.Reader indent string } tests := []struct { name string args args wantW string wantErr bool }{ { name: "blank", args: args{ r: bytes.NewBufferString(``), indent: "", }, wantW: "", wantErr: false, }, { name: "empty object", args: args{ r: bytes.NewBufferString(`{}`), indent: "", }, wantW: "\x1b[1;38m{\x1b[m\x1b[1;38m}\x1b[m\n", wantErr: false, }, { name: "nested object", args: args{ r: bytes.NewBufferString(`{"hash":{"a":1,"b":2},"array":[3,4]}`), indent: "\t", }, wantW: "\x1b[1;38m{\x1b[m\n\t\x1b[1;34m\"hash\"\x1b[m\x1b[1;38m:\x1b[m " + "\x1b[1;38m{\x1b[m\n\t\t\x1b[1;34m\"a\"\x1b[m\x1b[1;38m:\x1b[m 1\x1b[1;38m,\x1b[m\n\t\t\x1b[1;34m\"b\"\x1b[m\x1b[1;38m:\x1b[m 2\n\t\x1b[1;38m}\x1b[m\x1b[1;38m,\x1b[m" + "\n\t\x1b[1;34m\"array\"\x1b[m\x1b[1;38m:\x1b[m \x1b[1;38m[\x1b[m\n\t\t3\x1b[1;38m,\x1b[m\n\t\t4\n\t\x1b[1;38m]\x1b[m\n\x1b[1;38m}\x1b[m\n", wantErr: false, }, { name: "string", args: args{ r: bytes.NewBufferString(`"foo"`), indent: "", }, wantW: "\x1b[32m\"foo\"\x1b[m\n", wantErr: false, }, { name: "error", args: args{ r: bytes.NewBufferString(`{{`), indent: "", }, wantW: "\x1b[1;38m{\x1b[m\n", wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { w := &bytes.Buffer{} if err := Write(w, tt.args.r, tt.args.indent); (err != nil) != tt.wantErr { t.Errorf("Write() error = %v, wantErr %v", err, tt.wantErr) return } diff := cmp.Diff(tt.wantW, w.String()) if diff != "" { t.Error(diff) } }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/httpmock/registry.go
pkg/httpmock/registry.go
package httpmock import ( "fmt" "net/http" "runtime/debug" "strings" "sync" "testing" ) // Replace http.Client transport layer with registry so all requests get // recorded. func ReplaceTripper(client *http.Client, reg *Registry) { client.Transport = reg } type Registry struct { mu sync.Mutex stubs []*Stub Requests []*http.Request } func (r *Registry) Register(m Matcher, resp Responder) { r.stubs = append(r.stubs, &Stub{ Stack: string(debug.Stack()), Matcher: m, Responder: resp, }) } func (r *Registry) Exclude(t *testing.T, m Matcher) { registrationStack := string(debug.Stack()) excludedStub := &Stub{ Matcher: m, Responder: func(req *http.Request) (*http.Response, error) { callStack := string(debug.Stack()) var errMsg strings.Builder errMsg.WriteString("HTTP call was made when it should have been excluded:\n") errMsg.WriteString(fmt.Sprintf("Request URL: %s\n", req.URL)) errMsg.WriteString(fmt.Sprintf("Was excluded by: %s\n", registrationStack)) errMsg.WriteString(fmt.Sprintf("Was called from: %s\n", callStack)) t.Error(errMsg.String()) t.FailNow() return nil, nil }, exclude: true, } r.stubs = append(r.stubs, excludedStub) } type Testing interface { Errorf(string, ...interface{}) Helper() } func (r *Registry) Verify(t Testing) { var unmatchedStubStacks []string for _, s := range r.stubs { if !s.matched && !s.exclude { unmatchedStubStacks = append(unmatchedStubStacks, s.Stack) } } if len(unmatchedStubStacks) > 0 { t.Helper() stacks := strings.Builder{} for i, stack := range unmatchedStubStacks { stacks.WriteString(fmt.Sprintf("Stub %d:\n", i+1)) stacks.WriteString(fmt.Sprintf("\t%s", stack)) if stack != unmatchedStubStacks[len(unmatchedStubStacks)-1] { stacks.WriteString("\n") } } // about dead stubs and what they were trying to match t.Errorf("%d HTTP stubs unmatched, stacks:\n%s", len(unmatchedStubStacks), stacks.String()) } } // RoundTrip satisfies http.RoundTripper func (r *Registry) RoundTrip(req *http.Request) (*http.Response, error) { var stub *Stub r.mu.Lock() for _, s := range r.stubs { if s.matched || !s.Matcher(req) { continue } // TODO: reinstate this check once the legacy layer has been cleaned up // if stub != nil { // r.mu.Unlock() // return nil, fmt.Errorf("more than 1 stub matched %v", req) // } stub = s break // TODO: remove } if stub != nil { stub.matched = true } if stub == nil { r.mu.Unlock() return nil, fmt.Errorf("no registered HTTP stubs matched %v", req) } r.Requests = append(r.Requests, req) r.mu.Unlock() return stub.Responder(req) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/httpmock/stub.go
pkg/httpmock/stub.go
package httpmock import ( "bytes" "encoding/json" "io" "net/http" "net/url" "os" "regexp" "strings" "github.com/cli/go-gh/v2/pkg/api" ) type Matcher func(req *http.Request) bool type Responder func(req *http.Request) (*http.Response, error) type Stub struct { Stack string matched bool Matcher Matcher Responder Responder exclude bool } func MatchAny(*http.Request) bool { return true } // REST returns a matcher to a request for the HTTP method and URL escaped path p. // For example, to match a GET request to `/api/v3/repos/octocat/hello-world/` // use REST("GET", "api/v3/repos/octocat/hello-world") // To match a GET request to `/user` use REST("GET", "user") func REST(method, p string) Matcher { return func(req *http.Request) bool { if !strings.EqualFold(req.Method, method) { return false } return req.URL.EscapedPath() == "/"+p } } func GraphQL(q string) Matcher { re := regexp.MustCompile(q) return func(req *http.Request) bool { if !strings.EqualFold(req.Method, "POST") { return false } if req.URL.Path != "/graphql" && req.URL.Path != "/api/graphql" { return false } var bodyData struct { Query string } _ = decodeJSONBody(req, &bodyData) return re.MatchString(bodyData.Query) } } func GraphQLMutationMatcher(q string, cb func(map[string]interface{}) bool) Matcher { re := regexp.MustCompile(q) return func(req *http.Request) bool { if !strings.EqualFold(req.Method, "POST") { return false } if req.URL.Path != "/graphql" && req.URL.Path != "/api/graphql" { return false } var bodyData struct { Query string Variables struct { Input map[string]interface{} } } _ = decodeJSONBody(req, &bodyData) if re.MatchString(bodyData.Query) { return cb(bodyData.Variables.Input) } return false } } func QueryMatcher(method string, path string, query url.Values) Matcher { return func(req *http.Request) bool { if !REST(method, path)(req) { return false } actualQuery := req.URL.Query() for param := range query { if !(actualQuery.Get(param) == query.Get(param)) { return false } } return true } } func readBody(req *http.Request) ([]byte, error) { bodyCopy := &bytes.Buffer{} r := io.TeeReader(req.Body, bodyCopy) req.Body = io.NopCloser(bodyCopy) return io.ReadAll(r) } func decodeJSONBody(req *http.Request, dest interface{}) error { b, err := readBody(req) if err != nil { return err } return json.Unmarshal(b, dest) } func StringResponse(body string) Responder { return func(req *http.Request) (*http.Response, error) { return httpResponse(200, req, bytes.NewBufferString(body)), nil } } func BinaryResponse(body []byte) Responder { return func(req *http.Request) (*http.Response, error) { return httpResponse(200, req, bytes.NewBuffer(body)), nil } } func WithHost(matcher Matcher, host string) Matcher { return func(req *http.Request) bool { if !strings.EqualFold(req.Host, host) { return false } return matcher(req) } } func WithHeader(responder Responder, header string, value string) Responder { return func(req *http.Request) (*http.Response, error) { resp, _ := responder(req) if resp.Header == nil { resp.Header = make(http.Header) } resp.Header.Set(header, value) return resp, nil } } func StatusStringResponse(status int, body string) Responder { return func(req *http.Request) (*http.Response, error) { return httpResponse(status, req, bytes.NewBufferString(body)), nil } } func JSONResponse(body interface{}) Responder { return func(req *http.Request) (*http.Response, error) { b, _ := json.Marshal(body) header := http.Header{ "Content-Type": []string{"application/json"}, } return httpResponseWithHeader(200, req, bytes.NewBuffer(b), header), nil } } // StatusJSONResponse turns the given argument into a JSON response. // // The argument is not meant to be a JSON string, unless it's intentional. func StatusJSONResponse(status int, body interface{}) Responder { return func(req *http.Request) (*http.Response, error) { b, _ := json.Marshal(body) header := http.Header{ "Content-Type": []string{"application/json"}, } return httpResponseWithHeader(status, req, bytes.NewBuffer(b), header), nil } } // JSONErrorResponse is a type-safe helper to avoid confusion around the // provided argument. func JSONErrorResponse(status int, err api.HTTPError) Responder { return StatusJSONResponse(status, err) } func FileResponse(filename string) Responder { return func(req *http.Request) (*http.Response, error) { f, err := os.Open(filename) if err != nil { return nil, err } return httpResponse(200, req, f), nil } } func RESTPayload(responseStatus int, responseBody string, cb func(payload map[string]interface{})) Responder { return func(req *http.Request) (*http.Response, error) { bodyData := make(map[string]interface{}) err := decodeJSONBody(req, &bodyData) if err != nil { return nil, err } cb(bodyData) header := http.Header{ "Content-Type": []string{"application/json"}, } return httpResponseWithHeader(responseStatus, req, bytes.NewBufferString(responseBody), header), nil } } func GraphQLMutation(body string, cb func(map[string]interface{})) Responder { return func(req *http.Request) (*http.Response, error) { var bodyData struct { Variables struct { Input map[string]interface{} } } err := decodeJSONBody(req, &bodyData) if err != nil { return nil, err } cb(bodyData.Variables.Input) return httpResponse(200, req, bytes.NewBufferString(body)), nil } } func GraphQLQuery(body string, cb func(string, map[string]interface{})) Responder { return func(req *http.Request) (*http.Response, error) { var bodyData struct { Query string Variables map[string]interface{} } err := decodeJSONBody(req, &bodyData) if err != nil { return nil, err } cb(bodyData.Query, bodyData.Variables) return httpResponse(200, req, bytes.NewBufferString(body)), nil } } // ScopesResponder returns a response with a 200 status code and the given OAuth scopes. func ScopesResponder(scopes string) func(*http.Request) (*http.Response, error) { //nolint:bodyclose return StatusScopesResponder(http.StatusOK, scopes) } // StatusScopesResponder returns a response with the given status code and OAuth scopes. func StatusScopesResponder(status int, scopes string) func(*http.Request) (*http.Response, error) { return func(req *http.Request) (*http.Response, error) { return &http.Response{ StatusCode: status, Request: req, Header: map[string][]string{ "X-Oauth-Scopes": {scopes}, }, Body: io.NopCloser(bytes.NewBufferString("")), }, nil } } func httpResponse(status int, req *http.Request, body io.Reader) *http.Response { return httpResponseWithHeader(status, req, body, http.Header{}) } func httpResponseWithHeader(status int, req *http.Request, body io.Reader, header http.Header) *http.Response { return &http.Response{ StatusCode: status, Request: req, Body: io.NopCloser(body), Header: header, } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/httpmock/legacy.go
pkg/httpmock/legacy.go
package httpmock import ( "fmt" ) // TODO: clean up methods in this file when there are no more callers func (r *Registry) StubRepoInfoResponse(owner, repo, branch string) { r.Register( GraphQL(`query RepositoryInfo\b`), StringResponse(fmt.Sprintf(` { "data": { "repository": { "id": "REPOID", "name": "%s", "owner": {"login": "%s"}, "description": "", "defaultBranchRef": {"name": "%s"}, "hasIssuesEnabled": true, "viewerPermission": "WRITE" } } } `, repo, owner, branch))) } func (r *Registry) StubRepoResponse(owner, repo string) { r.StubRepoResponseWithPermission(owner, repo, "WRITE") } func (r *Registry) StubRepoResponseWithPermission(owner, repo, permission string) { r.Register(GraphQL(`query RepositoryNetwork\b`), StringResponse(RepoNetworkStubResponse(owner, repo, "master", permission))) } func RepoNetworkStubResponse(owner, repo, defaultBranch, permission string) string { return fmt.Sprintf(` { "data": { "repo_000": { "id": "REPOID", "name": "%s", "owner": {"login": "%s"}, "defaultBranchRef": { "name": "%s" }, "viewerPermission": "%s" } } } `, repo, owner, defaultBranch, permission) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/search/searcher_test.go
pkg/search/searcher_test.go
package search import ( "fmt" "net/http" "net/url" "strconv" "testing" "github.com/MakeNowJust/heredoc" fd "github.com/cli/cli/v2/internal/featuredetection" "github.com/cli/cli/v2/pkg/httpmock" "github.com/stretchr/testify/assert" ) func TestSearcherCode(t *testing.T) { query := Query{ Keywords: []string{"keyword"}, Kind: "code", Limit: 30, Qualifiers: Qualifiers{ Language: "go", }, } values := url.Values{ "page": []string{"1"}, "per_page": []string{"30"}, "q": []string{"keyword language:go"}, } tests := []struct { name string host string query Query result CodeResult wantErr bool errMsg string httpStubs func(reg *httpmock.Registry) }{ { name: "searches code", query: query, result: CodeResult{ IncompleteResults: false, Items: []Code{{Name: "file.go"}}, Total: 1, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.QueryMatcher("GET", "search/code", values), httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 1, "items": []interface{}{ map[string]interface{}{ "name": "file.go", }, }, }), ) }, }, { name: "searches code for enterprise host", host: "enterprise.com", query: query, result: CodeResult{ IncompleteResults: false, Items: []Code{{Name: "file.go"}}, Total: 1, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.QueryMatcher("GET", "api/v3/search/code", values), httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 1, "items": []interface{}{ map[string]interface{}{ "name": "file.go", }, }, }), ) }, }, { name: "paginates results", query: query, result: CodeResult{ IncompleteResults: false, Items: []Code{{Name: "file.go"}, {Name: "file2.go"}}, Total: 2, }, httpStubs: func(reg *httpmock.Registry) { firstReq := httpmock.QueryMatcher("GET", "search/code", values) firstRes := httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 2, "items": []interface{}{ map[string]interface{}{ "name": "file.go", }, }, }) firstRes = httpmock.WithHeader(firstRes, "Link", `<https://api.github.com/search/code?page=2&per_page=30&q=org%3Agithub>; rel="next"`) secondReq := httpmock.QueryMatcher("GET", "search/code", url.Values{ "page": []string{"2"}, "per_page": []string{"30"}, "q": []string{"keyword language:go"}, }) secondRes := httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 2, "items": []interface{}{ map[string]interface{}{ "name": "file2.go", }, }, }) reg.Register(firstReq, firstRes) reg.Register(secondReq, secondRes) }, }, { name: "paginates results with quoted multi-word query (#11228)", query: Query{ Keywords: []string{"keyword with whitespace"}, Kind: "code", Limit: 30, Qualifiers: Qualifiers{ Language: "go", }, }, result: CodeResult{ IncompleteResults: false, Items: []Code{{Name: "file.go"}, {Name: "file2.go"}}, Total: 2, }, httpStubs: func(reg *httpmock.Registry) { firstReq := httpmock.QueryMatcher("GET", "search/code", url.Values{ "page": []string{"1"}, "per_page": []string{"30"}, "q": []string{"\"keyword with whitespace\" language:go"}, }) firstRes := httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 2, "items": []interface{}{ map[string]interface{}{ "name": "file.go", }, }, }) firstRes = httpmock.WithHeader(firstRes, "Link", `<https://api.github.com/search/code?page=2&per_page=30&q=org%3Agithub>; rel="next"`) secondReq := httpmock.QueryMatcher("GET", "search/code", url.Values{ "page": []string{"2"}, "per_page": []string{"30"}, "q": []string{"\"keyword with whitespace\" language:go"}, }) secondRes := httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 2, "items": []interface{}{ map[string]interface{}{ "name": "file2.go", }, }, }) reg.Register(firstReq, firstRes) reg.Register(secondReq, secondRes) }, }, { name: "collect full and partial pages under total number of matching search results", query: Query{ Keywords: []string{"keyword"}, Kind: "code", Limit: 110, Qualifiers: Qualifiers{ Language: "go", }, }, result: CodeResult{ IncompleteResults: false, Items: initialize(0, 110, func(i int) Code { return Code{ Name: fmt.Sprintf("name%d.go", i), } }), Total: 287, }, httpStubs: func(reg *httpmock.Registry) { firstReq := httpmock.QueryMatcher("GET", "search/code", url.Values{ "page": []string{"1"}, "per_page": []string{"100"}, "q": []string{"keyword language:go"}, }) firstRes := httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 287, "items": initialize(0, 100, func(i int) interface{} { return map[string]interface{}{ "name": fmt.Sprintf("name%d.go", i), } }), }) firstRes = httpmock.WithHeader(firstRes, "Link", `<https://api.github.com/search/code?page=2&per_page=100&q=org%3Agithub>; rel="next"`) secondReq := httpmock.QueryMatcher("GET", "search/code", url.Values{ "page": []string{"2"}, "per_page": []string{"100"}, "q": []string{"keyword language:go"}, }) secondRes := httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 287, "items": initialize(100, 200, func(i int) interface{} { return map[string]interface{}{ "name": fmt.Sprintf("name%d.go", i), } }), }) reg.Register(firstReq, firstRes) reg.Register(secondReq, secondRes) }, }, { name: "handles search errors", query: query, wantErr: true, errMsg: heredoc.Doc(` Invalid search query "keyword language:go". "blah" is not a recognized date/time format. Please provide an ISO 8601 date/time value, such as YYYY-MM-DD.`), httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.QueryMatcher("GET", "search/code", values), httpmock.WithHeader( httpmock.StatusStringResponse(422, `{ "message": "Validation Failed", "errors": [ { "message":"\"blah\" is not a recognized date/time format. Please provide an ISO 8601 date/time value, such as YYYY-MM-DD.", "resource":"Search", "field":"q", "code":"invalid" } ], "documentation_url":"https://developer.github.com/v3/search/" }`, ), "Content-Type", "application/json"), ) }, }, } 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) } client := &http.Client{Transport: reg} if tt.host == "" { tt.host = "github.com" } searcher := NewSearcher(client, tt.host, &fd.DisabledDetectorMock{}) result, err := searcher.Code(tt.query) if tt.wantErr { assert.EqualError(t, err, tt.errMsg) return } assert.NoError(t, err) assert.Equal(t, tt.result, result) }) } } func TestSearcherCommits(t *testing.T) { query := Query{ Keywords: []string{"keyword"}, Kind: "commits", Limit: 30, Order: "desc", Sort: "committer-date", Qualifiers: Qualifiers{ Author: "foobar", CommitterDate: ">2021-02-28", }, } values := url.Values{ "page": []string{"1"}, "per_page": []string{"30"}, "order": []string{"desc"}, "sort": []string{"committer-date"}, "q": []string{"keyword author:foobar committer-date:>2021-02-28"}, } tests := []struct { name string host string query Query result CommitsResult wantErr bool errMsg string httpStubs func(*httpmock.Registry) }{ { name: "searches commits", query: query, result: CommitsResult{ IncompleteResults: false, Items: []Commit{{Sha: "abc"}}, Total: 1, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.QueryMatcher("GET", "search/commits", values), httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 1, "items": []interface{}{ map[string]interface{}{ "sha": "abc", }, }, }), ) }, }, { name: "searches commits for enterprise host", host: "enterprise.com", query: query, result: CommitsResult{ IncompleteResults: false, Items: []Commit{{Sha: "abc"}}, Total: 1, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.QueryMatcher("GET", "api/v3/search/commits", values), httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 1, "items": []interface{}{ map[string]interface{}{ "sha": "abc", }, }, }), ) }, }, { name: "paginates results with quoted multi-word query (#11228)", query: Query{ Keywords: []string{"keyword with whitespace"}, Kind: "commits", Limit: 30, Order: "desc", Sort: "committer-date", Qualifiers: Qualifiers{ Author: "foobar", CommitterDate: ">2021-02-28", }, }, result: CommitsResult{ IncompleteResults: false, Items: []Commit{{Sha: "abc"}, {Sha: "def"}}, Total: 2, }, httpStubs: func(reg *httpmock.Registry) { firstReq := httpmock.QueryMatcher("GET", "search/commits", url.Values{ "page": []string{"1"}, "per_page": []string{"30"}, "order": []string{"desc"}, "sort": []string{"committer-date"}, "q": []string{"\"keyword with whitespace\" author:foobar committer-date:>2021-02-28"}, }) firstRes := httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 2, "items": []interface{}{ map[string]interface{}{ "sha": "abc", }, }, }) firstRes = httpmock.WithHeader(firstRes, "Link", `<https://api.github.com/search/commits?page=2&per_page=30&q=org%3Agithub>; rel="next"`) secondReq := httpmock.QueryMatcher("GET", "search/commits", url.Values{ "page": []string{"2"}, "per_page": []string{"30"}, "order": []string{"desc"}, "sort": []string{"committer-date"}, "q": []string{"\"keyword with whitespace\" author:foobar committer-date:>2021-02-28"}, }) secondRes := httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 2, "items": []interface{}{ map[string]interface{}{ "sha": "def", }, }, }) reg.Register(firstReq, firstRes) reg.Register(secondReq, secondRes) }, }, { name: "paginates results", query: query, result: CommitsResult{ IncompleteResults: false, Items: []Commit{{Sha: "abc"}, {Sha: "def"}}, Total: 2, }, httpStubs: func(reg *httpmock.Registry) { firstReq := httpmock.QueryMatcher("GET", "search/commits", values) firstRes := httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 2, "items": []interface{}{ map[string]interface{}{ "sha": "abc", }, }, }) firstRes = httpmock.WithHeader(firstRes, "Link", `<https://api.github.com/search/commits?page=2&per_page=30&q=org%3Agithub>; rel="next"`) secondReq := httpmock.QueryMatcher("GET", "search/commits", url.Values{ "page": []string{"2"}, "per_page": []string{"30"}, "order": []string{"desc"}, "sort": []string{"committer-date"}, "q": []string{"keyword author:foobar committer-date:>2021-02-28"}, }) secondRes := httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 2, "items": []interface{}{ map[string]interface{}{ "sha": "def", }, }, }) reg.Register(firstReq, firstRes) reg.Register(secondReq, secondRes) }, }, { name: "collect full and partial pages under total number of matching search results", query: Query{ Keywords: []string{"keyword"}, Kind: "commits", Limit: 110, Order: "desc", Sort: "committer-date", Qualifiers: Qualifiers{ Author: "foobar", CommitterDate: ">2021-02-28", }, }, result: CommitsResult{ IncompleteResults: false, Items: initialize(0, 110, func(i int) Commit { return Commit{ Sha: strconv.Itoa(i), } }), Total: 287, }, httpStubs: func(reg *httpmock.Registry) { firstReq := httpmock.QueryMatcher("GET", "search/commits", url.Values{ "page": []string{"1"}, "per_page": []string{"100"}, "order": []string{"desc"}, "sort": []string{"committer-date"}, "q": []string{"keyword author:foobar committer-date:>2021-02-28"}, }) firstRes := httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 287, "items": initialize(0, 100, func(i int) map[string]interface{} { return map[string]interface{}{ "sha": strconv.Itoa(i), } }), }) firstRes = httpmock.WithHeader(firstRes, "Link", `<https://api.github.com/search/commits?page=2&per_page=100&q=org%3Agithub>; rel="next"`) secondReq := httpmock.QueryMatcher("GET", "search/commits", url.Values{ "page": []string{"2"}, "per_page": []string{"100"}, "order": []string{"desc"}, "sort": []string{"committer-date"}, "q": []string{"keyword author:foobar committer-date:>2021-02-28"}, }) secondRes := httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 287, "items": initialize(100, 200, func(i int) map[string]interface{} { return map[string]interface{}{ "sha": strconv.Itoa(i), } }), }) reg.Register(firstReq, firstRes) reg.Register(secondReq, secondRes) }, }, { name: "handles search errors", query: query, wantErr: true, errMsg: heredoc.Doc(` Invalid search query "keyword author:foobar committer-date:>2021-02-28". "blah" is not a recognized date/time format. Please provide an ISO 8601 date/time value, such as YYYY-MM-DD.`), httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.QueryMatcher("GET", "search/commits", values), httpmock.WithHeader( httpmock.StatusStringResponse(422, `{ "message":"Validation Failed", "errors":[ { "message":"\"blah\" is not a recognized date/time format. Please provide an ISO 8601 date/time value, such as YYYY-MM-DD.", "resource":"Search", "field":"q", "code":"invalid" } ], "documentation_url":"https://docs.github.com/v3/search/" }`, ), "Content-Type", "application/json"), ) }, }, } 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) } client := &http.Client{Transport: reg} if tt.host == "" { tt.host = "github.com" } searcher := NewSearcher(client, tt.host, &fd.DisabledDetectorMock{}) result, err := searcher.Commits(tt.query) if tt.wantErr { assert.EqualError(t, err, tt.errMsg) return } assert.NoError(t, err) assert.Equal(t, tt.result, result) }) } } func TestSearcherRepositories(t *testing.T) { query := Query{ Keywords: []string{"keyword"}, Kind: "repositories", Limit: 30, Order: "desc", Sort: "stars", Qualifiers: Qualifiers{ Stars: ">=5", Topic: []string{"topic"}, }, } values := url.Values{ "page": []string{"1"}, "per_page": []string{"30"}, "order": []string{"desc"}, "sort": []string{"stars"}, "q": []string{"keyword stars:>=5 topic:topic"}, } tests := []struct { name string host string query Query result RepositoriesResult wantErr bool errMsg string httpStubs func(*httpmock.Registry) }{ { name: "searches repositories", query: query, result: RepositoriesResult{ IncompleteResults: false, Items: []Repository{{Name: "test"}}, Total: 1, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.QueryMatcher("GET", "search/repositories", values), httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 1, "items": []interface{}{ map[string]interface{}{ "name": "test", }, }, }), ) }, }, { name: "searches repositories for enterprise host", host: "enterprise.com", query: query, result: RepositoriesResult{ IncompleteResults: false, Items: []Repository{{Name: "test"}}, Total: 1, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.QueryMatcher("GET", "api/v3/search/repositories", values), httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 1, "items": []interface{}{ map[string]interface{}{ "name": "test", }, }, }), ) }, }, { name: "paginates results", query: query, result: RepositoriesResult{ IncompleteResults: false, Items: []Repository{{Name: "test"}, {Name: "cli"}}, Total: 2, }, httpStubs: func(reg *httpmock.Registry) { firstReq := httpmock.QueryMatcher("GET", "search/repositories", values) firstRes := httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 2, "items": []interface{}{ map[string]interface{}{ "name": "test", }, }, }) firstRes = httpmock.WithHeader(firstRes, "Link", `<https://api.github.com/search/repositories?page=2&per_page=30&q=org%3Agithub>; rel="next"`) secondReq := httpmock.QueryMatcher("GET", "search/repositories", url.Values{ "page": []string{"2"}, "per_page": []string{"30"}, "order": []string{"desc"}, "sort": []string{"stars"}, "q": []string{"keyword stars:>=5 topic:topic"}, }) secondRes := httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 2, "items": []interface{}{ map[string]interface{}{ "name": "cli", }, }, }) reg.Register(firstReq, firstRes) reg.Register(secondReq, secondRes) }, }, { name: "paginates results with quoted multi-word query (#11228)", query: Query{ Keywords: []string{"keyword with whitespace"}, Kind: "repositories", Limit: 30, Order: "desc", Sort: "stars", Qualifiers: Qualifiers{ Stars: ">=5", Topic: []string{"topic"}, }, }, result: RepositoriesResult{ IncompleteResults: false, Items: []Repository{{Name: "test"}, {Name: "cli"}}, Total: 2, }, httpStubs: func(reg *httpmock.Registry) { firstReq := httpmock.QueryMatcher("GET", "search/repositories", url.Values{ "page": []string{"1"}, "per_page": []string{"30"}, "order": []string{"desc"}, "sort": []string{"stars"}, "q": []string{"\"keyword with whitespace\" stars:>=5 topic:topic"}, }) firstRes := httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 2, "items": []interface{}{ map[string]interface{}{ "name": "test", }, }, }) firstRes = httpmock.WithHeader(firstRes, "Link", `<https://api.github.com/search/repositories?page=2&per_page=30&q=org%3Agithub>; rel="next"`) secondReq := httpmock.QueryMatcher("GET", "search/repositories", url.Values{ "page": []string{"2"}, "per_page": []string{"30"}, "order": []string{"desc"}, "sort": []string{"stars"}, "q": []string{"\"keyword with whitespace\" stars:>=5 topic:topic"}, }) secondRes := httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 2, "items": []interface{}{ map[string]interface{}{ "name": "cli", }, }, }) reg.Register(firstReq, firstRes) reg.Register(secondReq, secondRes) }, }, { name: "collect full and partial pages under total number of matching search results", query: Query{ Keywords: []string{"keyword"}, Kind: "repositories", Limit: 110, Order: "desc", Sort: "stars", Qualifiers: Qualifiers{ Stars: ">=5", Topic: []string{"topic"}, }, }, result: RepositoriesResult{ IncompleteResults: false, Items: initialize(0, 110, func(i int) Repository { return Repository{ Name: fmt.Sprintf("name%d", i), } }), Total: 287, }, httpStubs: func(reg *httpmock.Registry) { firstReq := httpmock.QueryMatcher("GET", "search/repositories", url.Values{ "page": []string{"1"}, "per_page": []string{"100"}, "order": []string{"desc"}, "sort": []string{"stars"}, "q": []string{"keyword stars:>=5 topic:topic"}, }) firstRes := httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 287, "items": initialize(0, 100, func(i int) interface{} { return map[string]interface{}{ "name": fmt.Sprintf("name%d", i), } }), }) firstRes = httpmock.WithHeader(firstRes, "Link", `<https://api.github.com/search/repositories?page=2&per_page=100&q=org%3Agithub>; rel="next"`) secondReq := httpmock.QueryMatcher("GET", "search/repositories", url.Values{ "page": []string{"2"}, "per_page": []string{"100"}, "order": []string{"desc"}, "sort": []string{"stars"}, "q": []string{"keyword stars:>=5 topic:topic"}, }) secondRes := httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 287, "items": initialize(100, 200, func(i int) interface{} { return map[string]interface{}{ "name": fmt.Sprintf("name%d", i), } }), }) reg.Register(firstReq, firstRes) reg.Register(secondReq, secondRes) }, }, { name: "handles search errors", query: query, wantErr: true, errMsg: heredoc.Doc(` Invalid search query "keyword stars:>=5 topic:topic". "blah" is not a recognized date/time format. Please provide an ISO 8601 date/time value, such as YYYY-MM-DD.`), httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.QueryMatcher("GET", "search/repositories", values), httpmock.WithHeader( httpmock.StatusStringResponse(422, `{ "message":"Validation Failed", "errors":[ { "message":"\"blah\" is not a recognized date/time format. Please provide an ISO 8601 date/time value, such as YYYY-MM-DD.", "resource":"Search", "field":"q", "code":"invalid" } ], "documentation_url":"https://docs.github.com/v3/search/" }`, ), "Content-Type", "application/json"), ) }, }, } 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) } client := &http.Client{Transport: reg} if tt.host == "" { tt.host = "github.com" } searcher := NewSearcher(client, tt.host, &fd.DisabledDetectorMock{}) result, err := searcher.Repositories(tt.query) if tt.wantErr { assert.EqualError(t, err, tt.errMsg) return } assert.NoError(t, err) assert.Equal(t, tt.result, result) }) } } func TestSearcherIssues(t *testing.T) { query := Query{ Keywords: []string{"keyword"}, Kind: "issues", Limit: 30, Order: "desc", Sort: "comments", Qualifiers: Qualifiers{ Language: "go", Is: []string{"public", "locked"}, }, } values := url.Values{ "page": []string{"1"}, "per_page": []string{"30"}, "order": []string{"desc"}, "sort": []string{"comments"}, "q": []string{"keyword is:locked is:public language:go"}, } tests := []struct { name string host string query Query result IssuesResult wantErr bool errMsg string httpStubs func(*httpmock.Registry) }{ { name: "searches issues", query: query, result: IssuesResult{ IncompleteResults: false, Items: []Issue{{Number: 1234}}, Total: 1, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.QueryMatcher("GET", "search/issues", values), httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 1, "items": []interface{}{ map[string]interface{}{ "number": 1234, }, }, }), ) }, }, { name: "searches issues for enterprise host", host: "enterprise.com", query: query, result: IssuesResult{ IncompleteResults: false, Items: []Issue{{Number: 1234}}, Total: 1, }, httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.QueryMatcher("GET", "api/v3/search/issues", values), httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 1, "items": []interface{}{ map[string]interface{}{ "number": 1234, }, }, }), ) }, }, { name: "paginates results", query: query, result: IssuesResult{ IncompleteResults: false, Items: []Issue{{Number: 1234}, {Number: 5678}}, Total: 2, }, httpStubs: func(reg *httpmock.Registry) { firstReq := httpmock.QueryMatcher("GET", "search/issues", values) firstRes := httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 2, "items": []interface{}{ map[string]interface{}{ "number": 1234, }, }, }) firstRes = httpmock.WithHeader(firstRes, "Link", `<https://api.github.com/search/issues?page=2&per_page=30&q=org%3Agithub>; rel="next"`) secondReq := httpmock.QueryMatcher("GET", "search/issues", url.Values{ "page": []string{"2"}, "per_page": []string{"30"}, "order": []string{"desc"}, "sort": []string{"comments"}, "q": []string{"keyword is:locked is:public language:go"}, }) secondRes := httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 2, "items": []interface{}{ map[string]interface{}{ "number": 5678, }, }, }) reg.Register(firstReq, firstRes) reg.Register(secondReq, secondRes) }, }, { name: "paginates results with quoted multi-word query (#11228)", query: Query{ Keywords: []string{"keyword with whitespace"}, Kind: "issues", Limit: 30, Order: "desc", Sort: "comments", Qualifiers: Qualifiers{ Language: "go", Is: []string{"public", "locked"}, }, }, result: IssuesResult{ IncompleteResults: false, Items: []Issue{{Number: 1234}, {Number: 5678}}, Total: 2, }, httpStubs: func(reg *httpmock.Registry) { firstReq := httpmock.QueryMatcher("GET", "search/issues", url.Values{ "page": []string{"1"}, "per_page": []string{"30"}, "order": []string{"desc"}, "sort": []string{"comments"}, "q": []string{"\"keyword with whitespace\" is:locked is:public language:go"}, }) firstRes := httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 2, "items": []interface{}{ map[string]interface{}{ "number": 1234, }, }, }) firstRes = httpmock.WithHeader(firstRes, "Link", `<https://api.github.com/search/issues?page=2&per_page=30&q=org%3Agithub>; rel="next"`) secondReq := httpmock.QueryMatcher("GET", "search/issues", url.Values{ "page": []string{"2"}, "per_page": []string{"30"}, "order": []string{"desc"}, "sort": []string{"comments"}, "q": []string{"\"keyword with whitespace\" is:locked is:public language:go"}, }) secondRes := httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 2, "items": []interface{}{ map[string]interface{}{ "number": 5678, }, }, }) reg.Register(firstReq, firstRes) reg.Register(secondReq, secondRes) }, }, { name: "collect full and partial pages under total number of matching search results", query: Query{ Keywords: []string{"keyword"}, Kind: "issues", Limit: 110, Order: "desc", Sort: "comments", Qualifiers: Qualifiers{ Language: "go", Is: []string{"public", "locked"}, }, }, result: IssuesResult{ IncompleteResults: false, Items: initialize(0, 110, func(i int) Issue { return Issue{ Number: i, } }), Total: 287, }, httpStubs: func(reg *httpmock.Registry) { firstReq := httpmock.QueryMatcher("GET", "search/issues", url.Values{ "page": []string{"1"}, "per_page": []string{"100"}, "order": []string{"desc"}, "sort": []string{"comments"}, "q": []string{"keyword is:locked is:public language:go"}, }) firstRes := httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 287, "items": initialize(0, 100, func(i int) interface{} { return map[string]interface{}{ "number": i, } }), }) firstRes = httpmock.WithHeader(firstRes, "Link", `<https://api.github.com/search/issues?page=2&per_page=100&q=org%3Agithub>; rel="next"`) secondReq := httpmock.QueryMatcher("GET", "search/issues", url.Values{ "page": []string{"2"}, "per_page": []string{"100"}, "order": []string{"desc"}, "sort": []string{"comments"}, "q": []string{"keyword is:locked is:public language:go"}, }) secondRes := httpmock.JSONResponse(map[string]interface{}{ "incomplete_results": false, "total_count": 287, "items": initialize(100, 200, func(i int) interface{} { return map[string]interface{}{ "number": i, } }), }) reg.Register(firstReq, firstRes) reg.Register(secondReq, secondRes) }, }, { name: "handles search errors", query: query, wantErr: true, errMsg: heredoc.Doc(` Invalid search query "keyword is:locked is:public language:go". "blah" is not a recognized date/time format. Please provide an ISO 8601 date/time value, such as YYYY-MM-DD.`), httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.QueryMatcher("GET", "search/issues", values), httpmock.WithHeader( httpmock.StatusStringResponse(422, `{ "message":"Validation Failed", "errors":[ { "message":"\"blah\" is not a recognized date/time format. Please provide an ISO 8601 date/time value, such as YYYY-MM-DD.",
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
true
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/search/result.go
pkg/search/result.go
package search import ( "encoding/json" "reflect" "strings" "time" "github.com/cli/cli/v2/pkg/cmdutil" ) var CodeFields = []string{ "path", "repository", "sha", "textMatches", "url", } var textMatchFields = []string{ "fragment", "matches", "type", "property", } var CommitFields = []string{ "author", "commit", "committer", "sha", "id", "parents", "repository", "url", } var RepositoryFields = []string{ "createdAt", "defaultBranch", "description", "forksCount", "fullName", "hasDownloads", "hasIssues", "hasPages", "hasProjects", "hasWiki", "homepage", "id", "isArchived", "isDisabled", "isFork", "isPrivate", "language", "license", "name", "openIssuesCount", "owner", "pushedAt", "size", "stargazersCount", "updatedAt", "url", "visibility", "watchersCount", } var IssueFields = []string{ "assignees", "author", "authorAssociation", "body", "closedAt", "commentsCount", "createdAt", "id", "isLocked", "isPullRequest", "labels", "number", "repository", "state", "title", "updatedAt", "url", } var PullRequestFields = append(IssueFields, "isDraft", ) type CodeResult struct { IncompleteResults bool `json:"incomplete_results"` Items []Code `json:"items"` // Number of code search results matching the query on the server. Ignoring limit. Total int `json:"total_count"` } type CommitsResult struct { IncompleteResults bool `json:"incomplete_results"` Items []Commit `json:"items"` // Number of commits matching the query on the server. Ignoring limit. Total int `json:"total_count"` } type RepositoriesResult struct { IncompleteResults bool `json:"incomplete_results"` Items []Repository `json:"items"` // Number of repositories matching the query on the server. Ignoring limit. Total int `json:"total_count"` } type IssuesResult struct { IncompleteResults bool `json:"incomplete_results"` Items []Issue `json:"items"` // Number of isssues matching the query on the server. Ignoring limit. Total int `json:"total_count"` } type Code struct { Name string `json:"name"` Path string `json:"path"` Repository Repository `json:"repository"` Sha string `json:"sha"` TextMatches []TextMatch `json:"text_matches"` URL string `json:"html_url"` } type TextMatch struct { Fragment string `json:"fragment"` Matches []Match `json:"matches"` Type string `json:"object_type"` Property string `json:"property"` } type Match struct { Indices []int `json:"indices"` Text string `json:"text"` } type Commit struct { Author User `json:"author"` Committer User `json:"committer"` ID string `json:"node_id"` Info CommitInfo `json:"commit"` Parents []Parent `json:"parents"` Repo Repository `json:"repository"` Sha string `json:"sha"` URL string `json:"html_url"` } type CommitInfo struct { Author CommitUser `json:"author"` CommentCount int `json:"comment_count"` Committer CommitUser `json:"committer"` Message string `json:"message"` Tree Tree `json:"tree"` } type CommitUser struct { Date time.Time `json:"date"` Email string `json:"email"` Name string `json:"name"` } type Tree struct { Sha string `json:"sha"` } type Parent struct { Sha string `json:"sha"` URL string `json:"html_url"` } type Repository struct { CreatedAt time.Time `json:"created_at"` DefaultBranch string `json:"default_branch"` Description string `json:"description"` ForksCount int `json:"forks_count"` FullName string `json:"full_name"` HasDownloads bool `json:"has_downloads"` HasIssues bool `json:"has_issues"` HasPages bool `json:"has_pages"` HasProjects bool `json:"has_projects"` HasWiki bool `json:"has_wiki"` Homepage string `json:"homepage"` ID string `json:"node_id"` IsArchived bool `json:"archived"` IsDisabled bool `json:"disabled"` IsFork bool `json:"fork"` IsPrivate bool `json:"private"` Language string `json:"language"` License License `json:"license"` MasterBranch string `json:"master_branch"` Name string `json:"name"` OpenIssuesCount int `json:"open_issues_count"` Owner User `json:"owner"` PushedAt time.Time `json:"pushed_at"` Size int `json:"size"` StargazersCount int `json:"stargazers_count"` URL string `json:"html_url"` UpdatedAt time.Time `json:"updated_at"` Visibility string `json:"visibility"` WatchersCount int `json:"watchers_count"` } type License struct { Key string `json:"key"` Name string `json:"name"` URL string `json:"url"` } type User struct { GravatarID string `json:"gravatar_id"` ID string `json:"node_id"` Login string `json:"login"` SiteAdmin bool `json:"site_admin"` Type string `json:"type"` URL string `json:"html_url"` } type Issue struct { Assignees []User `json:"assignees"` Author User `json:"user"` AuthorAssociation string `json:"author_association"` Body string `json:"body"` ClosedAt time.Time `json:"closed_at"` CommentsCount int `json:"comments"` CreatedAt time.Time `json:"created_at"` ID string `json:"node_id"` Labels []Label `json:"labels"` // This is a PullRequest field which does not appear in issue results, // but lives outside the PullRequest object. IsDraft *bool `json:"draft,omitempty"` IsLocked bool `json:"locked"` Number int `json:"number"` PullRequest PullRequest `json:"pull_request"` RepositoryURL string `json:"repository_url"` // StateInternal should not be used directly. Use State() instead. StateInternal string `json:"state"` StateReason string `json:"state_reason"` Title string `json:"title"` URL string `json:"html_url"` UpdatedAt time.Time `json:"updated_at"` } type PullRequest struct { URL string `json:"html_url"` MergedAt time.Time `json:"merged_at"` } type Label struct { Color string `json:"color"` Description string `json:"description"` ID string `json:"node_id"` Name string `json:"name"` } func (u User) IsBot() bool { // copied from api/queries_issue.go // would ideally be shared, but it would require coordinating a "user" // abstraction in a bunch of places. return u.ID == "" } func (u User) ExportData() map[string]interface{} { isBot := u.IsBot() login := u.Login if isBot { login = "app/" + login } return map[string]interface{}{ "id": u.ID, "login": login, "type": u.Type, "url": u.URL, "is_bot": isBot, } } func (code Code) ExportData(fields []string) map[string]interface{} { v := reflect.ValueOf(code) data := map[string]interface{}{} for _, f := range fields { switch f { case "textMatches": matches := make([]interface{}, 0, len(code.TextMatches)) for _, match := range code.TextMatches { matches = append(matches, match.ExportData(textMatchFields)) } data[f] = matches default: sf := fieldByName(v, f) data[f] = sf.Interface() } } return data } func (textMatch TextMatch) ExportData(fields []string) map[string]interface{} { return cmdutil.StructExportData(textMatch, fields) } func (commit Commit) ExportData(fields []string) map[string]interface{} { v := reflect.ValueOf(commit) data := map[string]interface{}{} for _, f := range fields { switch f { case "author": data[f] = commit.Author.ExportData() case "commit": info := commit.Info data[f] = map[string]interface{}{ "author": map[string]interface{}{ "date": info.Author.Date, "email": info.Author.Email, "name": info.Author.Name, }, "committer": map[string]interface{}{ "date": info.Committer.Date, "email": info.Committer.Email, "name": info.Committer.Name, }, "comment_count": info.CommentCount, "message": info.Message, "tree": map[string]interface{}{"sha": info.Tree.Sha}, } case "committer": data[f] = commit.Committer.ExportData() case "parents": parents := make([]interface{}, 0, len(commit.Parents)) for _, parent := range commit.Parents { parents = append(parents, map[string]interface{}{ "sha": parent.Sha, "url": parent.URL, }) } data[f] = parents case "repository": repo := commit.Repo data[f] = map[string]interface{}{ "description": repo.Description, "fullName": repo.FullName, "name": repo.Name, "id": repo.ID, "isFork": repo.IsFork, "isPrivate": repo.IsPrivate, "owner": repo.Owner.ExportData(), "url": repo.URL, } default: sf := fieldByName(v, f) data[f] = sf.Interface() } } return data } func (repo Repository) ExportData(fields []string) map[string]interface{} { v := reflect.ValueOf(repo) data := map[string]interface{}{} for _, f := range fields { switch f { case "license": data[f] = map[string]interface{}{ "key": repo.License.Key, "name": repo.License.Name, "url": repo.License.URL, } case "owner": data[f] = repo.Owner.ExportData() default: sf := fieldByName(v, f) data[f] = sf.Interface() } } return data } func (repo Repository) MarshalJSON() ([]byte, error) { return json.Marshal(map[string]interface{}{ "id": repo.ID, "nameWithOwner": repo.FullName, "url": repo.URL, "isPrivate": repo.IsPrivate, "isFork": repo.IsFork, }) } // The state of an issue or a pull request, may be either open or closed. // For a pull request, the "merged" state is inferred from a value for merged_at and // which we take return instead of the "closed" state. func (issue Issue) State() string { if !issue.PullRequest.MergedAt.IsZero() { return "merged" } return issue.StateInternal } func (issue Issue) IsPullRequest() bool { return issue.PullRequest.URL != "" } func (issue Issue) ExportData(fields []string) map[string]interface{} { v := reflect.ValueOf(issue) data := map[string]interface{}{} for _, f := range fields { switch f { case "assignees": assignees := make([]interface{}, 0, len(issue.Assignees)) for _, assignee := range issue.Assignees { assignees = append(assignees, assignee.ExportData()) } data[f] = assignees case "author": data[f] = issue.Author.ExportData() case "isPullRequest": data[f] = issue.IsPullRequest() case "labels": labels := make([]interface{}, 0, len(issue.Labels)) for _, label := range issue.Labels { labels = append(labels, map[string]interface{}{ "color": label.Color, "description": label.Description, "id": label.ID, "name": label.Name, }) } data[f] = labels case "repository": comp := strings.Split(issue.RepositoryURL, "/") name := comp[len(comp)-1] nameWithOwner := strings.Join(comp[len(comp)-2:], "/") data[f] = map[string]interface{}{ "name": name, "nameWithOwner": nameWithOwner, } case "state": data[f] = issue.State() default: sf := fieldByName(v, f) data[f] = sf.Interface() } } return data } func fieldByName(v reflect.Value, field string) reflect.Value { return v.FieldByNameFunc(func(s string) bool { return strings.EqualFold(field, s) }) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/search/searcher_mock.go
pkg/search/searcher_mock.go
// Code generated by moq; DO NOT EDIT. // github.com/matryer/moq package search import ( "sync" ) // Ensure, that SearcherMock does implement Searcher. // If this is not the case, regenerate this file with moq. var _ Searcher = &SearcherMock{} // SearcherMock is a mock implementation of Searcher. // // func TestSomethingThatUsesSearcher(t *testing.T) { // // // make and configure a mocked Searcher // mockedSearcher := &SearcherMock{ // CodeFunc: func(query Query) (CodeResult, error) { // panic("mock out the Code method") // }, // CommitsFunc: func(query Query) (CommitsResult, error) { // panic("mock out the Commits method") // }, // IssuesFunc: func(query Query) (IssuesResult, error) { // panic("mock out the Issues method") // }, // RepositoriesFunc: func(query Query) (RepositoriesResult, error) { // panic("mock out the Repositories method") // }, // URLFunc: func(query Query) string { // panic("mock out the URL method") // }, // } // // // use mockedSearcher in code that requires Searcher // // and then make assertions. // // } type SearcherMock struct { // CodeFunc mocks the Code method. CodeFunc func(query Query) (CodeResult, error) // CommitsFunc mocks the Commits method. CommitsFunc func(query Query) (CommitsResult, error) // IssuesFunc mocks the Issues method. IssuesFunc func(query Query) (IssuesResult, error) // RepositoriesFunc mocks the Repositories method. RepositoriesFunc func(query Query) (RepositoriesResult, error) // URLFunc mocks the URL method. URLFunc func(query Query) string // calls tracks calls to the methods. calls struct { // Code holds details about calls to the Code method. Code []struct { // Query is the query argument value. Query Query } // Commits holds details about calls to the Commits method. Commits []struct { // Query is the query argument value. Query Query } // Issues holds details about calls to the Issues method. Issues []struct { // Query is the query argument value. Query Query } // Repositories holds details about calls to the Repositories method. Repositories []struct { // Query is the query argument value. Query Query } // URL holds details about calls to the URL method. URL []struct { // Query is the query argument value. Query Query } } lockCode sync.RWMutex lockCommits sync.RWMutex lockIssues sync.RWMutex lockRepositories sync.RWMutex lockURL sync.RWMutex } // Code calls CodeFunc. func (mock *SearcherMock) Code(query Query) (CodeResult, error) { if mock.CodeFunc == nil { panic("SearcherMock.CodeFunc: method is nil but Searcher.Code was just called") } callInfo := struct { Query Query }{ Query: query, } mock.lockCode.Lock() mock.calls.Code = append(mock.calls.Code, callInfo) mock.lockCode.Unlock() return mock.CodeFunc(query) } // CodeCalls gets all the calls that were made to Code. // Check the length with: // // len(mockedSearcher.CodeCalls()) func (mock *SearcherMock) CodeCalls() []struct { Query Query } { var calls []struct { Query Query } mock.lockCode.RLock() calls = mock.calls.Code mock.lockCode.RUnlock() return calls } // Commits calls CommitsFunc. func (mock *SearcherMock) Commits(query Query) (CommitsResult, error) { if mock.CommitsFunc == nil { panic("SearcherMock.CommitsFunc: method is nil but Searcher.Commits was just called") } callInfo := struct { Query Query }{ Query: query, } mock.lockCommits.Lock() mock.calls.Commits = append(mock.calls.Commits, callInfo) mock.lockCommits.Unlock() return mock.CommitsFunc(query) } // CommitsCalls gets all the calls that were made to Commits. // Check the length with: // // len(mockedSearcher.CommitsCalls()) func (mock *SearcherMock) CommitsCalls() []struct { Query Query } { var calls []struct { Query Query } mock.lockCommits.RLock() calls = mock.calls.Commits mock.lockCommits.RUnlock() return calls } // Issues calls IssuesFunc. func (mock *SearcherMock) Issues(query Query) (IssuesResult, error) { if mock.IssuesFunc == nil { panic("SearcherMock.IssuesFunc: method is nil but Searcher.Issues was just called") } callInfo := struct { Query Query }{ Query: query, } mock.lockIssues.Lock() mock.calls.Issues = append(mock.calls.Issues, callInfo) mock.lockIssues.Unlock() return mock.IssuesFunc(query) } // IssuesCalls gets all the calls that were made to Issues. // Check the length with: // // len(mockedSearcher.IssuesCalls()) func (mock *SearcherMock) IssuesCalls() []struct { Query Query } { var calls []struct { Query Query } mock.lockIssues.RLock() calls = mock.calls.Issues mock.lockIssues.RUnlock() return calls } // Repositories calls RepositoriesFunc. func (mock *SearcherMock) Repositories(query Query) (RepositoriesResult, error) { if mock.RepositoriesFunc == nil { panic("SearcherMock.RepositoriesFunc: method is nil but Searcher.Repositories was just called") } callInfo := struct { Query Query }{ Query: query, } mock.lockRepositories.Lock() mock.calls.Repositories = append(mock.calls.Repositories, callInfo) mock.lockRepositories.Unlock() return mock.RepositoriesFunc(query) } // RepositoriesCalls gets all the calls that were made to Repositories. // Check the length with: // // len(mockedSearcher.RepositoriesCalls()) func (mock *SearcherMock) RepositoriesCalls() []struct { Query Query } { var calls []struct { Query Query } mock.lockRepositories.RLock() calls = mock.calls.Repositories mock.lockRepositories.RUnlock() return calls } // URL calls URLFunc. func (mock *SearcherMock) URL(query Query) string { if mock.URLFunc == nil { panic("SearcherMock.URLFunc: method is nil but Searcher.URL was just called") } callInfo := struct { Query Query }{ Query: query, } mock.lockURL.Lock() mock.calls.URL = append(mock.calls.URL, callInfo) mock.lockURL.Unlock() return mock.URLFunc(query) } // URLCalls gets all the calls that were made to URL. // Check the length with: // // len(mockedSearcher.URLCalls()) func (mock *SearcherMock) URLCalls() []struct { Query Query } { var calls []struct { Query Query } mock.lockURL.RLock() calls = mock.calls.URL mock.lockURL.RUnlock() return calls }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/search/searcher.go
pkg/search/searcher.go
package search import ( "encoding/json" "fmt" "io" "net/http" "net/url" "regexp" "strconv" "strings" fd "github.com/cli/cli/v2/internal/featuredetection" "github.com/cli/cli/v2/internal/ghinstance" ) const ( // GitHub API has a limit of 100 per page maxPerPage = 100 orderKey = "order" sortKey = "sort" ) var linkRE = regexp.MustCompile(`<([^>]+)>;\s*rel="([^"]+)"`) var pageRE = regexp.MustCompile(`(\?|&)page=(\d*)`) var jsonTypeRE = regexp.MustCompile(`[/+]json($|;)`) //go:generate moq -rm -out searcher_mock.go . Searcher type Searcher interface { Code(Query) (CodeResult, error) Commits(Query) (CommitsResult, error) Repositories(Query) (RepositoriesResult, error) Issues(Query) (IssuesResult, error) URL(Query) string } type searcher struct { client *http.Client detector fd.Detector host string } type httpError struct { Errors []httpErrorItem Message string RequestURL *url.URL StatusCode int } type httpErrorItem struct { Code string Field string Message string Resource string } func NewSearcher(client *http.Client, host string, detector fd.Detector) Searcher { return &searcher{ client: client, host: host, detector: detector, } } func (s searcher) Code(query Query) (CodeResult, error) { result := CodeResult{} // We will request either the query limit if it's less than 1 page, or our max page size. // This number doesn't change to keep a valid offset. // // For example, say we want 150 items out of 500. // We request page #1 for 100 items and get items 0 to 99. // Then we request page #2 for 100 items, we get items 100 to 199 and only keep 100 to 149. // If we were to request page #2 for 50 items, we would instead get items 50 to 99. numItemsToRetrieve := query.Limit query.Limit = min(numItemsToRetrieve, maxPerPage) query.Page = 1 for numItemsToRetrieve > 0 { page := CodeResult{} link, err := s.search(query, &page) if err != nil { return result, err } // If we're going to reach the requested limit, only add that many items, // otherwise add all the results. numItemsToAdd := min(len(page.Items), numItemsToRetrieve) result.IncompleteResults = page.IncompleteResults // The API returns how many items match the query in every response. // With the example above, this would be 500. result.Total = page.Total result.Items = append(result.Items, page.Items[:numItemsToAdd]...) numItemsToRetrieve = numItemsToRetrieve - numItemsToAdd query.Page = nextPage(link) if query.Page == 0 { break } } return result, nil } func (s searcher) Commits(query Query) (CommitsResult, error) { result := CommitsResult{} numItemsToRetrieve := query.Limit query.Limit = min(numItemsToRetrieve, maxPerPage) query.Page = 1 for numItemsToRetrieve > 0 { page := CommitsResult{} link, err := s.search(query, &page) if err != nil { return result, err } numItemsToAdd := min(len(page.Items), numItemsToRetrieve) result.IncompleteResults = page.IncompleteResults result.Total = page.Total result.Items = append(result.Items, page.Items[:numItemsToAdd]...) numItemsToRetrieve = numItemsToRetrieve - numItemsToAdd query.Page = nextPage(link) if query.Page == 0 { break } } return result, nil } func (s searcher) Repositories(query Query) (RepositoriesResult, error) { result := RepositoriesResult{} numItemsToRetrieve := query.Limit query.Limit = min(numItemsToRetrieve, maxPerPage) query.Page = 1 for numItemsToRetrieve > 0 { page := RepositoriesResult{} link, err := s.search(query, &page) if err != nil { return result, err } numItemsToAdd := min(len(page.Items), numItemsToRetrieve) result.IncompleteResults = page.IncompleteResults result.Total = page.Total result.Items = append(result.Items, page.Items[:numItemsToAdd]...) numItemsToRetrieve = numItemsToRetrieve - numItemsToAdd query.Page = nextPage(link) if query.Page == 0 { break } } return result, nil } func (s searcher) Issues(query Query) (IssuesResult, error) { result := IssuesResult{} numItemsToRetrieve := query.Limit query.Limit = min(numItemsToRetrieve, maxPerPage) query.Page = 1 for numItemsToRetrieve > 0 { page := IssuesResult{} link, err := s.search(query, &page) if err != nil { return result, err } numItemsToAdd := min(len(page.Items), numItemsToRetrieve) result.IncompleteResults = page.IncompleteResults result.Total = page.Total result.Items = append(result.Items, page.Items[:numItemsToAdd]...) numItemsToRetrieve = numItemsToRetrieve - numItemsToAdd query.Page = nextPage(link) if query.Page == 0 { break } } return result, nil } // search makes a single-page REST search request for code, commits, issues, prs, or repos, // and returns the link header from response for further pagination calls. If the link header // is not set on the response, empty string is returned. // // The result argument is populated with the following information: // // - Total: the number of search results matching the query, which may exceed the number of items returned // - IncompleteResults: whether the search request exceeded search time limit, potentially being incomplete // - Items: the actual matching search results, up to 100 max items per page // // For more information, see https://docs.github.com/en/rest/search/search?apiVersion=2022-11-28. func (s searcher) search(query Query, result interface{}) (string, error) { path := fmt.Sprintf("%ssearch/%s", ghinstance.RESTPrefix(s.host), query.Kind) qs := url.Values{} qs.Set("page", strconv.Itoa(query.Page)) qs.Set("per_page", strconv.Itoa(query.Limit)) if query.Kind == KindIssues { // TODO advancedIssueSearchCleanup // We won't need feature detection when GHES 3.17 support ends, since // the advanced issue search is the only available search backend for // issues. features, err := s.detector.SearchFeatures() if err != nil { return "", err } if !features.AdvancedIssueSearchAPI { qs.Set("q", query.StandardSearchString()) } else { qs.Set("q", query.AdvancedIssueSearchString()) if features.AdvancedIssueSearchAPIOptIn { // Advanced syntax should be explicitly enabled qs.Set("advanced_search", "true") } } } else { qs.Set("q", query.StandardSearchString()) } if query.Order != "" { qs.Set(orderKey, query.Order) } if query.Sort != "" { qs.Set(sortKey, query.Sort) } url := fmt.Sprintf("%s?%s", path, qs.Encode()) req, err := http.NewRequest("GET", url, nil) if err != nil { return "", err } req.Header.Set("Content-Type", "application/json; charset=utf-8") req.Header.Set("Accept", "application/vnd.github.v3+json") if query.Kind == KindCode { req.Header.Set("Accept", "application/vnd.github.text-match+json") } resp, err := s.client.Do(req) if err != nil { return "", err } defer resp.Body.Close() link := resp.Header.Get("Link") success := resp.StatusCode >= 200 && resp.StatusCode < 300 if !success { return link, handleHTTPError(resp) } decoder := json.NewDecoder(resp.Body) err = decoder.Decode(result) if err != nil { return link, err } return link, nil } // URL returns URL to the global search in web GUI (i.e. github.com/search). func (s searcher) URL(query Query) string { path := fmt.Sprintf("https://%s/search", s.host) qs := url.Values{} qs.Set("type", query.Kind) // TODO advancedSearchFuture // Currently, the global search GUI does not support the advanced issue // search syntax (even for the issues/PRs tab on the sidebar). When the GUI // is updated, we can use feature detection, and, if available, use the // advanced search syntax. qs.Set("q", query.StandardSearchString()) if query.Order != "" { qs.Set(orderKey, query.Order) } if query.Sort != "" { qs.Set(sortKey, query.Sort) } url := fmt.Sprintf("%s?%s", path, qs.Encode()) return url } func (err httpError) Error() string { if err.StatusCode != 422 || len(err.Errors) == 0 { return fmt.Sprintf("HTTP %d: %s (%s)", err.StatusCode, err.Message, err.RequestURL) } query := strings.TrimSpace(err.RequestURL.Query().Get("q")) return fmt.Sprintf("Invalid search query %q.\n%s", query, err.Errors[0].Message) } func handleHTTPError(resp *http.Response) error { httpError := httpError{ RequestURL: resp.Request.URL, StatusCode: resp.StatusCode, } if !jsonTypeRE.MatchString(resp.Header.Get("Content-Type")) { httpError.Message = resp.Status return httpError } body, err := io.ReadAll(resp.Body) if err != nil { return err } if err := json.Unmarshal(body, &httpError); err != nil { return err } return httpError } // nextPage extracts the next page number from an API response's link header. if // the provided link header is empty or there is no next page, zero is returned. // // See API [docs] on pagination for more information. // // [docs]: https://docs.github.com/en/rest/using-the-rest-api/using-pagination-in-the-rest-api func nextPage(link string) (page int) { // When using pagination, responses get a "Link" field in their header. // When a next page is available, "Link" contains a link to the next page // tagged with rel="next". for _, m := range linkRE.FindAllStringSubmatch(link, -1) { if !(len(m) > 2 && m[2] == "next") { continue } p := pageRE.FindStringSubmatch(m[1]) if len(p) == 3 { i, err := strconv.Atoi(p[2]) if err == nil { return i } } } return 0 } func min(a, b int) int { if a < b { return a } return b }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/search/result_test.go
pkg/search/result_test.go
package search import ( "bytes" "encoding/json" "strings" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestCodeExportData(t *testing.T) { tests := []struct { name string fields []string code Code output string }{ { name: "exports requested fields", fields: []string{"path", "textMatches"}, code: Code{ Repository: Repository{ Name: "repo", }, Path: "path", Name: "name", TextMatches: []TextMatch{ { Fragment: "fragment", Matches: []Match{ { Text: "fr", Indices: []int{ 0, 1, }, }, }, Property: "property", Type: "type", }, }, }, output: `{"path":"path","textMatches":[{"fragment":"fragment","matches":[{"indices":[0,1],"text":"fr"}],"property":"property","type":"type"}]}`, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { exported := tt.code.ExportData(tt.fields) buf := bytes.Buffer{} enc := json.NewEncoder(&buf) require.NoError(t, enc.Encode(exported)) assert.Equal(t, tt.output, strings.TrimSpace(buf.String())) }) } } func TestCommitExportData(t *testing.T) { var authoredAt = time.Date(2021, 2, 27, 11, 30, 0, 0, time.UTC) var committedAt = time.Date(2021, 2, 28, 12, 30, 0, 0, time.UTC) tests := []struct { name string fields []string commit Commit output string }{ { name: "exports requested fields", fields: []string{"author", "commit", "committer", "sha"}, commit: Commit{ Author: User{Login: "foo"}, Committer: User{Login: "bar", ID: "123"}, Info: CommitInfo{ Author: CommitUser{Date: authoredAt, Name: "Foo"}, Committer: CommitUser{Date: committedAt, Name: "Bar"}, Message: "test message", }, Sha: "8dd03144ffdc6c0d", }, output: `{"author":{"id":"","is_bot":true,"login":"app/foo","type":"","url":""},"commit":{"author":{"date":"2021-02-27T11:30:00Z","email":"","name":"Foo"},"comment_count":0,"committer":{"date":"2021-02-28T12:30:00Z","email":"","name":"Bar"},"message":"test message","tree":{"sha":""}},"committer":{"id":"123","is_bot":false,"login":"bar","type":"","url":""},"sha":"8dd03144ffdc6c0d"}`, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { exported := tt.commit.ExportData(tt.fields) buf := bytes.Buffer{} enc := json.NewEncoder(&buf) require.NoError(t, enc.Encode(exported)) assert.Equal(t, tt.output, strings.TrimSpace(buf.String())) }) } } func TestRepositoryExportData(t *testing.T) { var createdAt = time.Date(2021, 2, 28, 12, 30, 0, 0, time.UTC) tests := []struct { name string fields []string repo Repository output string }{ { name: "exports requested fields", fields: []string{"createdAt", "description", "fullName", "isArchived", "isFork", "isPrivate", "pushedAt"}, repo: Repository{ CreatedAt: createdAt, Description: "description", FullName: "cli/cli", IsArchived: true, IsFork: false, IsPrivate: false, PushedAt: createdAt, }, output: `{"createdAt":"2021-02-28T12:30:00Z","description":"description","fullName":"cli/cli","isArchived":true,"isFork":false,"isPrivate":false,"pushedAt":"2021-02-28T12:30:00Z"}`, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { exported := tt.repo.ExportData(tt.fields) buf := bytes.Buffer{} enc := json.NewEncoder(&buf) require.NoError(t, enc.Encode(exported)) assert.Equal(t, tt.output, strings.TrimSpace(buf.String())) }) } } func TestIssueExportData(t *testing.T) { var updatedAt = time.Date(2021, 2, 28, 12, 30, 0, 0, time.UTC) trueValue := true tests := []struct { name string fields []string issue Issue output string }{ { name: "exports requested fields", fields: []string{"assignees", "body", "commentsCount", "labels", "isLocked", "repository", "title", "updatedAt"}, issue: Issue{ Assignees: []User{{Login: "test", ID: "123"}, {Login: "foo"}}, Body: "body", CommentsCount: 1, Labels: []Label{{Name: "label1"}, {Name: "label2"}}, IsLocked: true, RepositoryURL: "https://github.com/owner/repo", Title: "title", UpdatedAt: updatedAt, }, output: `{"assignees":[{"id":"123","is_bot":false,"login":"test","type":"","url":""},{"id":"","is_bot":true,"login":"app/foo","type":"","url":""}],"body":"body","commentsCount":1,"isLocked":true,"labels":[{"color":"","description":"","id":"","name":"label1"},{"color":"","description":"","id":"","name":"label2"}],"repository":{"name":"repo","nameWithOwner":"owner/repo"},"title":"title","updatedAt":"2021-02-28T12:30:00Z"}`, }, { name: "state when issue", fields: []string{"isPullRequest", "state"}, issue: Issue{ StateInternal: "closed", }, output: `{"isPullRequest":false,"state":"closed"}`, }, { name: "state when pull request", fields: []string{"isPullRequest", "state"}, issue: Issue{ PullRequest: PullRequest{ MergedAt: time.Now(), URL: "a-url", }, StateInternal: "closed", }, output: `{"isPullRequest":true,"state":"merged"}`, }, { name: "isDraft when pull request", fields: []string{"isDraft", "state"}, issue: Issue{ PullRequest: PullRequest{ URL: "a-url", }, StateInternal: "open", IsDraft: &trueValue, }, output: `{"isDraft":true,"state":"open"}`, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { exported := tt.issue.ExportData(tt.fields) buf := bytes.Buffer{} enc := json.NewEncoder(&buf) require.NoError(t, enc.Encode(exported)) assert.Equal(t, tt.output, strings.TrimSpace(buf.String())) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/search/query_test.go
pkg/search/query_test.go
package search import ( "testing" "github.com/stretchr/testify/assert" ) var trueBool = true func TestStandardSearchString(t *testing.T) { tests := []struct { name string query Query out string }{ { name: "empty query", out: "", }, { name: "converts query to string", query: Query{ Keywords: []string{"some", "keywords"}, Qualifiers: Qualifiers{ Archived: &trueBool, AuthorEmail: "foo@example.com", CommitterDate: "2021-02-28", Created: "created", Extension: "go", Filename: ".vimrc", 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{"user1", "user2"}, Is: []string{"public"}, }, }, out: "some keywords archived:true author-email:foo@example.com committer-date:2021-02-28 " + "created:created extension:go filename:.vimrc followers:1 fork:true forks:2 good-first-issues:3 help-wanted-issues:4 " + "in:description in:readme is:public language:language license:license pushed:updated size:5 " + "stars:6 topic:topic topics:7 user:user1 user:user2", }, { name: "quotes keywords", query: Query{ Keywords: []string{"quote keywords"}, }, out: `"quote keywords"`, }, { name: "quotes keywords that are qualifiers", query: Query{ Keywords: []string{"quote:keywords", "quote:multiword keywords"}, }, out: `quote:keywords quote:"multiword keywords"`, }, { name: "quotes qualifiers", query: Query{ Qualifiers: Qualifiers{ Topic: []string{"quote qualifier"}, }, }, out: `topic:"quote qualifier"`, }, { name: "respects immutable keywords", query: Query{ ImmutableKeywords: "immutable keyword that should be left as is", }, out: `immutable keyword that should be left as is`, }, { name: "respects immutable keywords, with qualifiers", query: Query{ ImmutableKeywords: "immutable keyword that should be left as is", Qualifiers: Qualifiers{ Topic: []string{"quote qualifier"}, }, }, out: `immutable keyword that should be left as is topic:"quote qualifier"`, }, { name: "prioritises immutable keywords over keywords slice", query: Query{ Keywords: []string{"foo", "bar"}, ImmutableKeywords: "immutable keyword", }, out: `immutable keyword`, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert.Equal(t, tt.out, tt.query.StandardSearchString()) }) } } func TestAdvancedIssueSearchString(t *testing.T) { tests := []struct { name string query Query out string }{ { name: "empty query", out: "", }, { name: "quotes keywords", query: Query{ Keywords: []string{"quote keywords"}, }, out: `"quote keywords"`, }, { name: "quotes keywords that are qualifiers", query: Query{ Keywords: []string{"quote:keywords", "quote:multiword keywords"}, }, out: `quote:keywords quote:"multiword keywords"`, }, { name: "quotes qualifiers", query: Query{ Qualifiers: Qualifiers{ Label: []string{"quote qualifier"}, }, }, out: `label:"quote qualifier"`, }, { name: "respects immutable keywords", query: Query{ ImmutableKeywords: "immutable keyword that should be left as is", }, out: `immutable keyword that should be left as is`, }, { name: "respects immutable keywords, with qualifiers", query: Query{ ImmutableKeywords: "immutable keyword that should be left as is", Qualifiers: Qualifiers{ Topic: []string{"quote qualifier"}, }, }, out: `( immutable keyword that should be left as is ) topic:"quote qualifier"`, }, { name: "prioritises immutable keywords over keywords slice", query: Query{ Keywords: []string{"foo", "bar"}, ImmutableKeywords: "immutable keyword", }, out: `immutable keyword`, }, { name: "unused qualifiers should not appear in query", query: Query{ Keywords: []string{"keyword"}, Qualifiers: Qualifiers{ Label: []string{"foo", "bar"}, }, }, out: `( keyword ) label:bar label:foo`, }, { name: "special qualifiers when used once", query: Query{ Keywords: []string{"keyword"}, Qualifiers: Qualifiers{ Repo: []string{"foo/bar"}, Is: []string{"private"}, User: []string{"johndoe"}, In: []string{"title"}, }, }, out: `( keyword ) in:title is:private repo:foo/bar user:johndoe`, }, { name: "special qualifiers are OR-ed when used multiple times", query: Query{ Keywords: []string{"keyword"}, Qualifiers: Qualifiers{ Repo: []string{"foo/bar", "foo/baz"}, Is: []string{"private", "public", "issue", "pr", "open", "closed", "locked", "unlocked", "merged", "unmerged", "blocked", "blocking", "foo"}, // "foo" is to ensure only "public" and "private" are grouped User: []string{"johndoe", "janedoe"}, In: []string{"title", "body", "comments", "foo"}, // "foo" is to ensure only "title", "body", and "comments" are grouped }, }, out: `( keyword ) (in:body OR in:comments OR in:title) in:foo (is:blocked OR is:blocking) (is:closed OR is:open) (is:issue OR is:pr) (is:locked OR is:unlocked) (is:merged OR is:unmerged) (is:private OR is:public) is:foo (repo:foo/bar OR repo:foo/baz) (user:janedoe OR user:johndoe)`, }, { // Since this is a general purpose package, we can't assume with know all // use cases of special qualifiers. So, here we ensure unknown values are // not OR-ed by default. name: "special qualifiers without special values", query: Query{ Keywords: []string{"keyword"}, Qualifiers: Qualifiers{ Is: []string{"foo", "bar"}, In: []string{"foo", "bar"}, }, }, out: `( keyword ) in:bar in:foo is:bar is:foo`, }, { name: "non-special qualifiers used multiple times", query: Query{ Keywords: []string{"keyword"}, Qualifiers: Qualifiers{ In: []string{"foo", "bar"}, // "in:" is a special qualifier but its values here are not special Is: []string{"foo", "bar"}, // "is:" is a special qualifier but its values here are not special Label: []string{"foo", "bar"}, License: []string{"foo", "bar"}, No: []string{"foo", "bar"}, Topic: []string{"foo", "bar"}, }, }, out: `( keyword ) in:bar in:foo is:bar is:foo label:bar label:foo license:bar license:foo no:bar no:foo topic:bar topic:foo`, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert.Equal(t, tt.out, tt.query.AdvancedIssueSearchString()) }) } } func TestQualifiersMap(t *testing.T) { tests := []struct { name string qualifiers Qualifiers out map[string][]string }{ { name: "changes qualifiers to map", qualifiers: Qualifiers{ Archived: &trueBool, AuthorEmail: "foo@example.com", CommitterDate: "2021-02-28", Created: "created", Extension: "go", Filename: ".vimrc", Followers: "1", Fork: "true", Forks: "2", GoodFirstIssues: "3", HelpWantedIssues: "4", In: []string{"readme"}, Is: []string{"public"}, Language: "language", License: []string{"license"}, Pushed: "updated", Size: "5", Stars: "6", Topic: []string{"topic"}, Topics: "7", User: []string{"user1", "user2"}, }, out: map[string][]string{ "archived": {"true"}, "author-email": {"foo@example.com"}, "committer-date": {"2021-02-28"}, "created": {"created"}, "extension": {"go"}, "filename": {".vimrc"}, "followers": {"1"}, "fork": {"true"}, "forks": {"2"}, "good-first-issues": {"3"}, "help-wanted-issues": {"4"}, "in": {"readme"}, "is": {"public"}, "language": {"language"}, "license": {"license"}, "pushed": {"updated"}, "size": {"5"}, "stars": {"6"}, "topic": {"topic"}, "topics": {"7"}, "user": {"user1", "user2"}, }, }, { name: "excludes unset qualifiers from map", qualifiers: Qualifiers{ Pushed: "updated", Size: "5", Stars: "6", User: []string{"user"}, }, out: map[string][]string{ "pushed": {"updated"}, "size": {"5"}, "stars": {"6"}, "user": {"user"}, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert.Equal(t, tt.out, tt.qualifiers.Map()) }) } } func TestCamelToKebab(t *testing.T) { tests := []struct { name string in string out string }{ { name: "single lowercase word", in: "test", out: "test", }, { name: "multiple mixed words", in: "testTestTest", out: "test-test-test", }, { name: "multiple uppercase words", in: "TestTest", out: "test-test", }, { name: "multiple lowercase words", in: "testtest", out: "testtest", }, { name: "multiple mixed words with number", in: "test2Test", out: "test2-test", }, { name: "multiple lowercase words with number", in: "test2test", out: "test2test", }, { name: "multiple lowercase words with dash", in: "test-test", out: "test-test", }, { name: "multiple uppercase words with dash", in: "Test-Test", out: "test--test", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert.Equal(t, tt.out, camelToKebab(tt.in)) }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/search/query.go
pkg/search/query.go
package search import ( "fmt" "reflect" "slices" "strings" "unicode" ) const ( KindRepositories = "repositories" KindCode = "code" KindIssues = "issues" KindCommits = "commits" ) type Query struct { // Keywords holds the list of keywords to search for. These keywords are // treated as individual components of a search query, and will get quoted // as needed. This is useful when the input can be supplied as a list of // search keywords. // // This field is overridden by ImmutableKeywords. Keywords []string // ImmutableKeywords holds the search keywords as a single string, and will // be treated as is (e.g. no additional quoting). This is useful when the // input is meant to be taken verbatim from the user. // // This field takes precedence over Keywords. ImmutableKeywords string Kind string Limit int Order string Page int Qualifiers Qualifiers Sort string } type Qualifiers struct { Archived *bool Assignee string Author string AuthorDate string AuthorEmail string AuthorName string Base string Closed string Commenter string Comments string Committer string CommitterDate string CommitterEmail string CommitterName string Created string Draft *bool Extension string Filename string Followers string Fork string Forks string GoodFirstIssues string Hash string Head string HelpWantedIssues string In []string Interactions string Involves string Is []string Label []string Language string License []string Mentions string Merge *bool Merged string Milestone string No []string Parent string Path string Project string Pushed string Reactions string Repo []string Review string ReviewRequested string ReviewedBy string Size string Stars string State string Status string Team string TeamReviewRequested string Topic []string Topics string Tree string Type string Updated string User []string } // String returns the string representation of the query which can be used with // the legacy search backend, which is used in global search GUI (i.e. // github.com/search), or Pull Requests tab (in repositories). Note that this is // a common query format that can be used to search for various entity types // (e.g., issues, commits, repositories, etc) // // With the legacy search backend, the query is made of concatenating keywords // and qualifiers with whitespaces. Note that at the backend side, most of the // repeated qualifiers are AND-ed, while a handful of qualifiers (i.e. // is:private/public, repo:, user:, or in:) are implicitly OR-ed. The legacy // search backend does not support the advanced syntax which allows for nested // queries and explicit OR operators. // // At the moment, the advanced search syntax is only available for searching // issues, and it's called advanced issue search. func (q Query) StandardSearchString() string { qualifiers := formatQualifiers(q.Qualifiers, nil) var keywords []string if q.ImmutableKeywords != "" { keywords = []string{q.ImmutableKeywords} } else if ks := formatKeywords(q.Keywords); len(ks) > 0 { keywords = ks } all := append(keywords, qualifiers...) return strings.TrimSpace(strings.Join(all, " ")) } // AdvancedIssueSearchString returns the string representation of the query // compatible with the advanced issue search syntax. The query can be used in // Issues tab (of repositories) and the Issues dashboard (i.e. // github.com/issues). // // As the name suggests, this query syntax is only supported for searching // issues (i.e. issues and PRs). The advanced syntax allows nested queries and // explicit OR operators. Unlike the legacy search backend, the advanced issue // search does not OR repeated instances of special qualifiers (i.e. // is:private/public, repo:, user:, or in:). // // To keep the gh experience consistent and backward-compatible, the mentioned // special qualifiers are explicitly grouped and combined with an OR operator. // // The advanced syntax is documented at https://github.blog/changelog/2025-03-06-github-issues-projects-api-support-for-issues-advanced-search-and-more func (q Query) AdvancedIssueSearchString() string { qualifiers := strings.Join(formatQualifiers(q.Qualifiers, formatAdvancedIssueSearch), " ") keywords := q.ImmutableKeywords if keywords == "" { keywords = strings.Join(formatKeywords(q.Keywords), " ") } if qualifiers == "" && keywords == "" { return "" } if qualifiers != "" && keywords != "" { // We should surround keywords with brackets to avoid leaking of any operators, especially "OR"s. return fmt.Sprintf("( %s ) %s", keywords, qualifiers) } if keywords != "" { return keywords } return qualifiers } func formatAdvancedIssueSearch(qualifier string, vs []string) (s []string, applicable bool) { switch qualifier { case "in": return formatSpecialQualifiers("in", vs, [][]string{{"title", "body", "comments"}}), true case "is": return formatSpecialQualifiers("is", vs, [][]string{{"blocked", "blocking"}, {"closed", "open"}, {"issue", "pr"}, {"locked", "unlocked"}, {"merged", "unmerged"}, {"private", "public"}}), true case "user", "repo": return []string{groupWithOR(qualifier, vs)}, true } // Let the default formatting take over return nil, false } func formatSpecialQualifiers(qualifier string, vs []string, specialGroupsToOR [][]string) []string { specialGroups := make([][]string, len(specialGroupsToOR)) rest := make([]string, 0, len(vs)) for _, v := range vs { var isSpecial bool for i, subValuesToOR := range specialGroupsToOR { if slices.Contains(subValuesToOR, v) { specialGroups[i] = append(specialGroups[i], v) isSpecial = true break } } if isSpecial { continue } rest = append(rest, v) } all := make([]string, 0, len(specialGroups)+len(rest)) for _, group := range specialGroups { if len(group) == 0 { continue } all = append(all, groupWithOR(qualifier, group)) } if len(rest) > 0 { for _, v := range rest { all = append(all, fmt.Sprintf("%s:%s", qualifier, quote(v))) } } slices.Sort(all) return all } func groupWithOR(qualifier string, vs []string) string { if len(vs) == 0 { return "" } all := make([]string, 0, len(vs)) for _, v := range vs { all = append(all, fmt.Sprintf("%s:%s", qualifier, quote(v))) } if len(all) == 1 { return all[0] } slices.Sort(all) return fmt.Sprintf("(%s)", strings.Join(all, " OR ")) } func (q Qualifiers) Map() map[string][]string { m := map[string][]string{} v := reflect.ValueOf(q) t := reflect.TypeOf(q) for i := 0; i < v.NumField(); i++ { fieldName := t.Field(i).Name key := camelToKebab(fieldName) typ := v.FieldByName(fieldName).Kind() value := v.FieldByName(fieldName) switch typ { case reflect.Ptr: if value.IsNil() { continue } v := reflect.Indirect(value) m[key] = []string{fmt.Sprintf("%v", v)} case reflect.Slice: if value.IsNil() { continue } s := []string{} for i := 0; i < value.Len(); i++ { if value.Index(i).IsZero() { continue } s = append(s, fmt.Sprintf("%v", value.Index(i))) } m[key] = s default: if value.IsZero() { continue } m[key] = []string{fmt.Sprintf("%v", value)} } } return m } func quote(s string) string { if strings.ContainsAny(s, " \"\t\r\n") { return fmt.Sprintf("%q", s) } return s } // formatQualifiers renders qualifiers into a plain query. // // The formatter is a custom formatting function that can be used to modify the // output of each qualifier. If the formatter returns (nil, false) the default // formatting will be applied. func formatQualifiers(qs Qualifiers, formatter func(qualifier string, vs []string) (s []string, applicable bool)) []string { type entry struct { key string values []string } var all []entry for k, vs := range qs.Map() { if len(vs) == 0 { continue } e := entry{key: k} if formatter != nil { if s, applicable := formatter(k, vs); applicable { e.values = s all = append(all, e) continue } } for _, v := range vs { e.values = append(e.values, fmt.Sprintf("%s:%s", k, quote(v))) } if len(e.values) > 1 { slices.Sort(e.values) } all = append(all, e) } slices.SortFunc(all, func(a, b entry) int { return strings.Compare(a.key, b.key) }) result := make([]string, 0, len(all)) for _, e := range all { result = append(result, e.values...) } return result } func formatKeywords(ks []string) []string { result := make([]string, len(ks)) for i, k := range ks { before, after, found := strings.Cut(k, ":") if !found { result[i] = quote(k) } else { result[i] = fmt.Sprintf("%s:%s", before, quote(after)) } } return result } // CamelToKebab returns a copy of the string s that is converted from camel case form to '-' separated form. func camelToKebab(s string) string { var output []rune var segment []rune for _, r := range s { if !unicode.IsLower(r) && string(r) != "-" && !unicode.IsNumber(r) { output = addSegment(output, segment) segment = nil } segment = append(segment, unicode.ToLower(r)) } output = addSegment(output, segment) return string(output) } func addSegment(inrune, segment []rune) []rune { if len(segment) == 0 { return inrune } if len(inrune) != 0 { inrune = append(inrune, '-') } inrune = append(inrune, segment...) return inrune }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/githubtemplate/github_template.go
pkg/githubtemplate/github_template.go
package githubtemplate import ( "fmt" "io/fs" "os" "path" "regexp" "sort" "strings" "gopkg.in/yaml.v3" ) // FindNonLegacy returns the list of template file paths from the template folder (according to the "upgraded multiple template builder") func FindNonLegacy(rootDir string, name string) []string { results := []string{} // https://help.github.com/en/github/building-a-strong-community/creating-a-pull-request-template-for-your-repository candidateDirs := []string{ path.Join(rootDir, ".github"), rootDir, path.Join(rootDir, "docs"), } mainLoop: for _, dir := range candidateDirs { files, err := os.ReadDir(dir) if err != nil { continue } // detect multiple templates in a subdirectory for _, file := range files { if strings.EqualFold(file.Name(), name) && file.IsDir() { templates, err := os.ReadDir(path.Join(dir, file.Name())) if err != nil { break } for _, tf := range templates { if strings.HasSuffix(tf.Name(), ".md") && file.Type() != fs.ModeSymlink { results = append(results, path.Join(dir, file.Name(), tf.Name())) } } if len(results) > 0 { break mainLoop } break } } } sort.Strings(results) return results } // FindLegacy returns the file path of the default(legacy) template func FindLegacy(rootDir string, name string) string { namePattern := regexp.MustCompile(fmt.Sprintf(`(?i)^%s(\.|$)`, strings.ReplaceAll(name, "_", "[_-]"))) // https://help.github.com/en/github/building-a-strong-community/creating-a-pull-request-template-for-your-repository candidateDirs := []string{ path.Join(rootDir, ".github"), rootDir, path.Join(rootDir, "docs"), } for _, dir := range candidateDirs { files, err := os.ReadDir(dir) if err != nil { continue } // detect a single template file for _, file := range files { if namePattern.MatchString(file.Name()) && !file.IsDir() && file.Type() != fs.ModeSymlink { return path.Join(dir, file.Name()) } } } return "" } // ExtractName returns the name of the template from YAML front-matter func ExtractName(filePath string) string { contents, err := os.ReadFile(filePath) frontmatterBoundaries := detectFrontmatter(contents) if err == nil && frontmatterBoundaries[0] == 0 { templateData := struct { Name string }{} if err := yaml.Unmarshal(contents[0:frontmatterBoundaries[1]], &templateData); err == nil && templateData.Name != "" { return templateData.Name } } return path.Base(filePath) } // ExtractTitle returns the title of the template from YAML front-matter func ExtractTitle(filePath string) string { contents, err := os.ReadFile(filePath) frontmatterBoundaries := detectFrontmatter(contents) if err == nil && frontmatterBoundaries[0] == 0 { templateData := struct { Title string }{} if err := yaml.Unmarshal(contents[0:frontmatterBoundaries[1]], &templateData); err == nil && templateData.Title != "" { return templateData.Title } } return "" } // ExtractContents returns the template contents without the YAML front-matter func ExtractContents(filePath string) []byte { contents, err := os.ReadFile(filePath) if err != nil { return []byte{} } if frontmatterBoundaries := detectFrontmatter(contents); frontmatterBoundaries[0] == 0 { return contents[frontmatterBoundaries[1]:] } return contents } var yamlPattern = regexp.MustCompile(`(?m)^---\r?\n(\s*\r?\n)?`) func detectFrontmatter(c []byte) []int { if matches := yamlPattern.FindAllIndex(c, 2); len(matches) > 1 { return []int{matches[0][0], matches[1][1]} } return []int{-1, -1} }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/githubtemplate/github_template_test.go
pkg/githubtemplate/github_template_test.go
package githubtemplate import ( "os" "path" "reflect" "testing" ) func TestFindNonLegacy(t *testing.T) { tmpdir, err := os.MkdirTemp("", "gh-cli") if err != nil { t.Fatal(err) } type args struct { rootDir string name string } tests := []struct { name string prepare []string args args want []string }{ { name: "Legacy templates ignored", prepare: []string{ "README.md", "ISSUE_TEMPLATE", "issue_template.md", "issue_template.txt", "pull_request_template.md", ".github/issue_template.md", "docs/issue_template.md", }, args: args{ rootDir: tmpdir, name: "ISSUE_TEMPLATE", }, want: []string{}, }, { name: "Template folder in .github takes precedence", prepare: []string{ "ISSUE_TEMPLATE.md", "docs/ISSUE_TEMPLATE/abc.md", "ISSUE_TEMPLATE/abc.md", ".github/ISSUE_TEMPLATE/abc.md", }, args: args{ rootDir: tmpdir, name: "ISSUE_TEMPLATE", }, want: []string{ path.Join(tmpdir, ".github/ISSUE_TEMPLATE/abc.md"), }, }, { name: "Template folder in root", prepare: []string{ "ISSUE_TEMPLATE.md", "docs/ISSUE_TEMPLATE/abc.md", "ISSUE_TEMPLATE/abc.md", }, args: args{ rootDir: tmpdir, name: "ISSUE_TEMPLATE", }, want: []string{ path.Join(tmpdir, "ISSUE_TEMPLATE/abc.md"), }, }, { name: "Template folder in docs", prepare: []string{ "ISSUE_TEMPLATE.md", "docs/ISSUE_TEMPLATE/abc.md", }, args: args{ rootDir: tmpdir, name: "ISSUE_TEMPLATE", }, want: []string{ path.Join(tmpdir, "docs/ISSUE_TEMPLATE/abc.md"), }, }, { name: "Multiple templates in template folder", prepare: []string{ ".github/ISSUE_TEMPLATE/nope.md", ".github/PULL_REQUEST_TEMPLATE.md", ".github/PULL_REQUEST_TEMPLATE/one.md", ".github/PULL_REQUEST_TEMPLATE/two.md", ".github/PULL_REQUEST_TEMPLATE/three.md", "docs/pull_request_template.md", }, args: args{ rootDir: tmpdir, name: "PuLl_ReQuEsT_TeMpLaTe", }, want: []string{ path.Join(tmpdir, ".github/PULL_REQUEST_TEMPLATE/one.md"), path.Join(tmpdir, ".github/PULL_REQUEST_TEMPLATE/three.md"), path.Join(tmpdir, ".github/PULL_REQUEST_TEMPLATE/two.md"), }, }, { name: "Empty template directories", prepare: []string{ ".github/ISSUE_TEMPLATE/.keep", ".docs/ISSUE_TEMPLATE/.keep", "ISSUE_TEMPLATE/.keep", }, args: args{ rootDir: tmpdir, name: "ISSUE_TEMPLATE", }, want: []string{}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { for _, p := range tt.prepare { fp := path.Join(tmpdir, p) _ = os.MkdirAll(path.Dir(fp), 0700) file, err := os.Create(fp) if err != nil { t.Fatal(err) } file.Close() } if got := FindNonLegacy(tt.args.rootDir, tt.args.name); !reflect.DeepEqual(got, tt.want) { t.Errorf("Find() = %v, want %v", got, tt.want) } }) os.RemoveAll(tmpdir) } } func TestFindLegacy(t *testing.T) { tmpdir, err := os.MkdirTemp("", "gh-cli") if err != nil { t.Fatal(err) } type args struct { rootDir string name string } tests := []struct { name string prepare []string args args want string }{ { name: "Template in root", prepare: []string{ "README.md", "issue_template.md", "issue_template.txt", "pull_request_template.md", "docs/issue_template.md", }, args: args{ rootDir: tmpdir, name: "ISSUE_TEMPLATE", }, want: path.Join(tmpdir, "issue_template.md"), }, { name: "No extension", prepare: []string{ "README.md", "issue_template", "docs/issue_template.md", }, args: args{ rootDir: tmpdir, name: "ISSUE_TEMPLATE", }, want: path.Join(tmpdir, "issue_template"), }, { name: "Dash instead of underscore", prepare: []string{ "README.md", "issue-template.txt", "docs/issue_template.md", }, args: args{ rootDir: tmpdir, name: "ISSUE_TEMPLATE", }, want: path.Join(tmpdir, "issue-template.txt"), }, { name: "Template in .github takes precedence", prepare: []string{ "ISSUE_TEMPLATE.md", ".github/issue_template.md", "docs/issue_template.md", }, args: args{ rootDir: tmpdir, name: "ISSUE_TEMPLATE", }, want: path.Join(tmpdir, ".github/issue_template.md"), }, { name: "Template in docs", prepare: []string{ "README.md", "docs/issue_template.md", }, args: args{ rootDir: tmpdir, name: "ISSUE_TEMPLATE", }, want: path.Join(tmpdir, "docs/issue_template.md"), }, { name: "Non legacy templates ignored", prepare: []string{ ".github/PULL_REQUEST_TEMPLATE/abc.md", "PULL_REQUEST_TEMPLATE/abc.md", "docs/PULL_REQUEST_TEMPLATE/abc.md", ".github/PULL_REQUEST_TEMPLATE.md", }, args: args{ rootDir: tmpdir, name: "PuLl_ReQuEsT_TeMpLaTe", }, want: path.Join(tmpdir, ".github/PULL_REQUEST_TEMPLATE.md"), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { for _, p := range tt.prepare { fp := path.Join(tmpdir, p) _ = os.MkdirAll(path.Dir(fp), 0700) file, err := os.Create(fp) if err != nil { t.Fatal(err) } file.Close() } got := FindLegacy(tt.args.rootDir, tt.args.name) if got == "" { t.Errorf("FindLegacy() = nil, want %v", tt.want) } else if got != tt.want { t.Errorf("FindLegacy() = %v, want %v", got, tt.want) } }) os.RemoveAll(tmpdir) } } func TestExtractName(t *testing.T) { tmpfile, err := os.CreateTemp(t.TempDir(), "gh-cli") if err != nil { t.Fatal(err) } defer tmpfile.Close() type args struct { filePath string } tests := []struct { name string prepare string args args want string }{ { name: "Complete front-matter", prepare: `--- name: Bug Report about: This is how you report bugs --- **Template contents** `, args: args{ filePath: tmpfile.Name(), }, want: "Bug Report", }, { name: "Incomplete front-matter", prepare: `--- about: This is how you report bugs --- `, args: args{ filePath: tmpfile.Name(), }, want: path.Base(tmpfile.Name()), }, { name: "No front-matter", prepare: `name: This is not yaml!`, args: args{ filePath: tmpfile.Name(), }, want: path.Base(tmpfile.Name()), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { _ = os.WriteFile(tmpfile.Name(), []byte(tt.prepare), 0600) if got := ExtractName(tt.args.filePath); got != tt.want { t.Errorf("ExtractName() = %v, want %v", got, tt.want) } }) } } func TestExtractTitle(t *testing.T) { tmpfile, err := os.CreateTemp(t.TempDir(), "gh-cli") if err != nil { t.Fatal(err) } defer tmpfile.Close() type args struct { filePath string } tests := []struct { name string prepare string args args want string }{ { name: "Complete front-matter", prepare: `--- name: Bug Report title: 'bug: ' about: This is how you report bugs --- **Template contents** `, args: args{ filePath: tmpfile.Name(), }, want: "bug: ", }, { name: "Incomplete front-matter", prepare: `--- about: This is how you report bugs --- `, args: args{ filePath: tmpfile.Name(), }, want: "", }, { name: "No front-matter", prepare: `name: This is not yaml!`, args: args{ filePath: tmpfile.Name(), }, want: "", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { _ = os.WriteFile(tmpfile.Name(), []byte(tt.prepare), 0600) if got := ExtractTitle(tt.args.filePath); got != tt.want { t.Errorf("ExtractTitle() = %v, want %v", got, tt.want) } }) } } func TestExtractContents(t *testing.T) { tmpfile, err := os.CreateTemp(t.TempDir(), "gh-cli") if err != nil { t.Fatal(err) } defer tmpfile.Close() type args struct { filePath string } tests := []struct { name string prepare string args args want string }{ { name: "Has front-matter", prepare: `--- name: Bug Report --- Template contents --- More of template `, args: args{ filePath: tmpfile.Name(), }, want: `Template contents --- More of template `, }, { name: "No front-matter", prepare: `Template contents --- More of template --- Even more `, args: args{ filePath: tmpfile.Name(), }, want: `Template contents --- More of template --- Even more `, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { _ = os.WriteFile(tmpfile.Name(), []byte(tt.prepare), 0600) if got := ExtractContents(tt.args.filePath); string(got) != tt.want { t.Errorf("ExtractContents() = %v, want %v", string(got), tt.want) } }) } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/markdown/markdown.go
pkg/markdown/markdown.go
package markdown import ( "os" "strconv" "github.com/charmbracelet/glamour" ghMarkdown "github.com/cli/go-gh/v2/pkg/markdown" ) func WithoutIndentation() glamour.TermRendererOption { return ghMarkdown.WithoutIndentation() } // WithWrap is a rendering option that set the character limit for soft // wrapping the markdown rendering. There is a max limit of 120 characters, // unless the user overrides with an environment variable. // If 0 is passed then wrapping is disabled. func WithWrap(w int) glamour.TermRendererOption { width, err := strconv.Atoi(os.Getenv("GH_MDWIDTH")) if err != nil { width = 120 } if w > width { w = width } return ghMarkdown.WithWrap(w) } func WithTheme(theme string) glamour.TermRendererOption { return ghMarkdown.WithTheme(theme) } func WithBaseURL(u string) glamour.TermRendererOption { return ghMarkdown.WithBaseURL(u) } func Render(text string, opts ...glamour.TermRendererOption) (string, error) { return ghMarkdown.Render(text, opts...) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/set/string_set_test.go
pkg/set/string_set_test.go
package set import ( "testing" "github.com/stretchr/testify/assert" ) func Test_StringSlice_ToSlice(t *testing.T) { s := NewStringSet() s.Add("one") s.Add("two") s.Add("three") s.Add("two") assert.Equal(t, []string{"one", "two", "three"}, s.ToSlice()) } func Test_StringSlice_Remove(t *testing.T) { s := NewStringSet() s.Add("one") s.Add("two") s.Add("three") s.Remove("two") assert.Equal(t, []string{"one", "three"}, s.ToSlice()) assert.False(t, s.Contains("two")) assert.Equal(t, 2, s.Len()) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/set/string_set.go
pkg/set/string_set.go
package set var exists = struct{}{} type stringSet struct { v []string m map[string]struct{} } func NewStringSet() *stringSet { s := &stringSet{} s.m = make(map[string]struct{}) s.v = []string{} return s } func (s *stringSet) Add(value string) { if s.Contains(value) { return } s.m[value] = exists s.v = append(s.v, value) } func (s *stringSet) AddValues(values []string) { for _, v := range values { s.Add(v) } } func (s *stringSet) Remove(value string) { if !s.Contains(value) { return } delete(s.m, value) s.v = sliceWithout(s.v, value) } func sliceWithout(s []string, v string) []string { idx := -1 for i, item := range s { if item == v { idx = i break } } if idx < 0 { return s } return append(s[:idx], s[idx+1:]...) } func (s *stringSet) RemoveValues(values []string) { for _, v := range values { s.Remove(v) } } func (s *stringSet) Contains(value string) bool { _, c := s.m[value] return c } func (s *stringSet) Len() int { return len(s.m) } func (s *stringSet) ToSlice() []string { return s.v } func (s1 *stringSet) Equal(s2 *stringSet) bool { if s1.Len() != s2.Len() { return false } isEqual := true for _, v := range s1.v { if !s2.Contains(v) { isEqual = false break } } return isEqual }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/surveyext/editor_test.go
pkg/surveyext/editor_test.go
package surveyext import ( "bytes" "errors" "fmt" "os" "strings" "sync" "testing" "time" "github.com/AlecAivazis/survey/v2" "github.com/AlecAivazis/survey/v2/terminal" pseudotty "github.com/creack/pty" "github.com/stretchr/testify/assert" ) func testLookPath(s string) ([]string, []string, error) { return []string{os.Args[0], "-test.run=TestHelperProcess", "--", s}, []string{"GH_WANT_HELPER_PROCESS=1"}, nil } func TestHelperProcess(t *testing.T) { if os.Getenv("GH_WANT_HELPER_PROCESS") != "1" { return } if err := func(args []string) error { switch args[0] { // "vim" appends a message to the file case "vim": f, err := os.OpenFile(args[1], os.O_APPEND|os.O_WRONLY, 0) if err != nil { return err } defer f.Close() _, err = f.WriteString(" - added by vim") return err // "nano" truncates the contents of the file case "nano": f, err := os.OpenFile(args[1], os.O_TRUNC|os.O_WRONLY, 0) if err != nil { return err } return f.Close() default: return fmt.Errorf("unrecognized arguments: %#v\n", args) } }(os.Args[3:]); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } os.Exit(0) } func Test_GhEditor_Prompt_skip(t *testing.T) { pty := newTerminal(t) e := &GhEditor{ BlankAllowed: true, EditorCommand: "vim", Editor: &survey.Editor{ Message: "Body", FileName: "*.md", Default: "initial value", HideDefault: true, AppendDefault: true, }, lookPath: func(s string) ([]string, []string, error) { return nil, nil, errors.New("no editor allowed") }, } e.WithStdio(pty.Stdio()) // wait until the prompt is rendered and send the Enter key go func() { pty.WaitForOutput("Body") assert.Equal(t, "\x1b[0G\x1b[2K\x1b[0;1;92m? \x1b[0m\x1b[0;1;99mBody \x1b[0m\x1b[0;36m[(e) to launch vim, enter to skip] \x1b[0m", normalizeANSI(pty.Output())) pty.ResetOutput() assert.NoError(t, pty.SendKey('\n')) }() res, err := e.Prompt(defaultPromptConfig()) assert.NoError(t, err) assert.Equal(t, "initial value", res) assert.Equal(t, "", normalizeANSI(pty.Output())) } func Test_GhEditor_Prompt_editorAppend(t *testing.T) { pty := newTerminal(t) e := &GhEditor{ BlankAllowed: true, EditorCommand: "vim", Editor: &survey.Editor{ Message: "Body", FileName: "*.md", Default: "initial value", HideDefault: true, AppendDefault: true, }, lookPath: testLookPath, } e.WithStdio(pty.Stdio()) // wait until the prompt is rendered and send the 'e' key go func() { pty.WaitForOutput("Body") assert.Equal(t, "\x1b[0G\x1b[2K\x1b[0;1;92m? \x1b[0m\x1b[0;1;99mBody \x1b[0m\x1b[0;36m[(e) to launch vim, enter to skip] \x1b[0m", normalizeANSI(pty.Output())) pty.ResetOutput() assert.NoError(t, pty.SendKey('e')) }() res, err := e.Prompt(defaultPromptConfig()) assert.NoError(t, err) assert.Equal(t, "initial value - added by vim", res) assert.Equal(t, "", normalizeANSI(pty.Output())) } func Test_GhEditor_Prompt_editorTruncate(t *testing.T) { pty := newTerminal(t) e := &GhEditor{ BlankAllowed: true, EditorCommand: "nano", Editor: &survey.Editor{ Message: "Body", FileName: "*.md", Default: "initial value", HideDefault: true, AppendDefault: true, }, lookPath: testLookPath, } e.WithStdio(pty.Stdio()) // wait until the prompt is rendered and send the 'e' key go func() { pty.WaitForOutput("Body") assert.Equal(t, "\x1b[0G\x1b[2K\x1b[0;1;92m? \x1b[0m\x1b[0;1;99mBody \x1b[0m\x1b[0;36m[(e) to launch nano, enter to skip] \x1b[0m", normalizeANSI(pty.Output())) pty.ResetOutput() assert.NoError(t, pty.SendKey('e')) }() res, err := e.Prompt(defaultPromptConfig()) assert.NoError(t, err) assert.Equal(t, "", res) assert.Equal(t, "", normalizeANSI(pty.Output())) } // survey doesn't expose this func defaultPromptConfig() *survey.PromptConfig { return &survey.PromptConfig{ PageSize: 7, HelpInput: "?", SuggestInput: "tab", Icons: survey.IconSet{ Error: survey.Icon{ Text: "X", Format: "red", }, Help: survey.Icon{ Text: "?", Format: "cyan", }, Question: survey.Icon{ Text: "?", Format: "green+hb", }, MarkedOption: survey.Icon{ Text: "[x]", Format: "green", }, UnmarkedOption: survey.Icon{ Text: "[ ]", Format: "default+hb", }, SelectFocus: survey.Icon{ Text: ">", Format: "cyan+b", }, }, Filter: func(filter string, value string, index int) (include bool) { filter = strings.ToLower(filter) return strings.Contains(strings.ToLower(value), filter) }, KeepFilter: false, } } type testTerminal struct { pty *os.File tty *os.File stdout *teeWriter stderr *teeWriter } func newTerminal(t *testing.T) *testTerminal { t.Helper() pty, tty, err := pseudotty.Open() if errors.Is(err, pseudotty.ErrUnsupported) { t.SkipNow() return nil } if err != nil { t.Fatal(err) } t.Cleanup(func() { pty.Close() tty.Close() }) if err := pseudotty.Setsize(tty, &pseudotty.Winsize{Cols: 72, Rows: 30}); err != nil { t.Fatal(err) } return &testTerminal{pty: pty, tty: tty} } func (t *testTerminal) SendKey(c rune) error { _, err := t.pty.WriteString(string(c)) return err } func (t *testTerminal) WaitForOutput(s string) { for { time.Sleep(time.Millisecond) if strings.Contains(t.stdout.String(), s) { return } } } func (t *testTerminal) Output() string { return t.stdout.String() } func (t *testTerminal) ResetOutput() { t.stdout.Reset() } func (t *testTerminal) Stdio() terminal.Stdio { t.stdout = &teeWriter{File: t.tty} t.stderr = t.stdout return terminal.Stdio{ In: t.tty, Out: t.stdout, Err: t.stderr, } } // teeWriter is a writer that duplicates all writes to a file into a buffer type teeWriter struct { *os.File buf bytes.Buffer mu sync.Mutex } func (f *teeWriter) Write(p []byte) (n int, err error) { f.mu.Lock() defer f.mu.Unlock() _, _ = f.buf.Write(p) return f.File.Write(p) } func (f *teeWriter) String() string { f.mu.Lock() s := f.buf.String() f.mu.Unlock() return s } func (f *teeWriter) Reset() { f.mu.Lock() f.buf.Reset() f.mu.Unlock() } // strips some ANSI escape sequences that we do not want tests to be concerned with func normalizeANSI(t string) string { t = strings.ReplaceAll(t, "\x1b[?25h", "") // strip sequence that shows cursor t = strings.ReplaceAll(t, "\x1b[?25l", "") // strip sequence that hides cursor return t }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/surveyext/editor.go
pkg/surveyext/editor.go
package surveyext // This file extends survey.Editor to give it more flexible behavior. For more context, read // https://github.com/cli/cli/issues/70 // To see what we extended, search through for EXTENDED comments. import ( "os" "path/filepath" "runtime" "github.com/AlecAivazis/survey/v2" "github.com/AlecAivazis/survey/v2/terminal" shellquote "github.com/kballard/go-shellquote" ) var ( bom = []byte{0xef, 0xbb, 0xbf} defaultEditor = "nano" // EXTENDED to switch from vim as a default editor ) func init() { if g := os.Getenv("GIT_EDITOR"); g != "" { defaultEditor = g } else if v := os.Getenv("VISUAL"); v != "" { defaultEditor = v } else if e := os.Getenv("EDITOR"); e != "" { defaultEditor = e } else if runtime.GOOS == "windows" { defaultEditor = "notepad" } } // EXTENDED to enable different prompting behavior type GhEditor struct { *survey.Editor EditorCommand string BlankAllowed bool lookPath func(string) ([]string, []string, error) } // EXTENDED to change prompt text var EditorQuestionTemplate = ` {{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }} {{ .Help }}{{color "reset"}}{{"\n"}}{{end}} {{- color .Config.Icons.Question.Format }}{{ .Config.Icons.Question.Text }} {{color "reset"}} {{- color "default+hb"}}{{ .Message }} {{color "reset"}} {{- if .ShowAnswer}} {{- color "cyan"}}{{.Answer}}{{color "reset"}}{{"\n"}} {{- else }} {{- if and .Help (not .ShowHelp)}}{{color "cyan"}}[{{ .Config.HelpInput }} for help]{{color "reset"}} {{end}} {{- if and .Default (not .HideDefault)}}{{color "white"}}({{.Default}}) {{color "reset"}}{{end}} {{- color "cyan"}}[(e) to launch {{ .EditorCommand }}{{- if .BlankAllowed }}, enter to skip{{ end }}] {{color "reset"}} {{- end}}` // EXTENDED to pass editor name (to use in prompt) type EditorTemplateData struct { survey.Editor EditorCommand string BlankAllowed bool Answer string ShowAnswer bool ShowHelp bool Config *survey.PromptConfig } // EXTENDED to augment prompt text and keypress handling func (e *GhEditor) prompt(initialValue string, config *survey.PromptConfig) (interface{}, error) { err := e.Render( EditorQuestionTemplate, // EXTENDED to support printing editor in prompt and BlankAllowed EditorTemplateData{ Editor: *e.Editor, BlankAllowed: e.BlankAllowed, EditorCommand: EditorName(e.EditorCommand), Config: config, }, ) if err != nil { return "", err } // start reading runes from the standard in rr := e.NewRuneReader() _ = rr.SetTermMode() defer func() { _ = rr.RestoreTermMode() }() cursor := e.NewCursor() _ = cursor.Hide() defer func() { _ = cursor.Show() }() for { // EXTENDED to handle the e to edit / enter to skip behavior + BlankAllowed r, _, err := rr.ReadRune() if err != nil { return "", err } if r == 'e' { break } if r == '\r' || r == '\n' { if e.BlankAllowed { return initialValue, nil } else { continue } } if r == terminal.KeyInterrupt { return "", terminal.InterruptErr } if r == terminal.KeyEndTransmission { break } if string(r) == config.HelpInput && e.Help != "" { err = e.Render( EditorQuestionTemplate, EditorTemplateData{ // EXTENDED to support printing editor in prompt, BlankAllowed Editor: *e.Editor, BlankAllowed: e.BlankAllowed, EditorCommand: EditorName(e.EditorCommand), ShowHelp: true, Config: config, }, ) if err != nil { return "", err } } continue } stdio := e.Stdio() lookPath := e.lookPath if lookPath == nil { lookPath = defaultLookPath } text, err := edit(e.EditorCommand, e.FileName, initialValue, stdio.In, stdio.Out, stdio.Err, cursor, lookPath) if err != nil { return "", err } // check length, return default value on empty if len(text) == 0 && !e.AppendDefault { return e.Default, nil } return text, nil } // EXTENDED This is straight copypasta from survey to get our overridden prompt called.; func (e *GhEditor) Prompt(config *survey.PromptConfig) (interface{}, error) { initialValue := "" if e.Default != "" && e.AppendDefault { initialValue = e.Default } return e.prompt(initialValue, config) } func EditorName(editorCommand string) string { if editorCommand == "" { editorCommand = defaultEditor } if args, err := shellquote.Split(editorCommand); err == nil { editorCommand = args[0] } return filepath.Base(editorCommand) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/pkg/surveyext/editor_manual.go
pkg/surveyext/editor_manual.go
package surveyext import ( "bytes" "io" "os" "os/exec" "runtime" "github.com/cli/safeexec" shellquote "github.com/kballard/go-shellquote" ) type showable interface { Show() error } func Edit(editorCommand, fn, initialValue string, stdin io.Reader, stdout io.Writer, stderr io.Writer) (string, error) { return edit(editorCommand, fn, initialValue, stdin, stdout, stderr, nil, defaultLookPath) } func defaultLookPath(name string) ([]string, []string, error) { exe, err := safeexec.LookPath(name) if err != nil { return nil, nil, err } return []string{exe}, nil, nil } func needsBom() bool { // The reason why we do this is because notepad.exe on Windows determines the // encoding of an "empty" text file by the locale, for example, GBK in China, // while golang string only handles utf8 well. However, a text file with utf8 // BOM header is not considered "empty" on Windows, and the encoding will then // be determined utf8 by notepad.exe, instead of GBK or other encodings. // This could be enhanced in the future by doing this only when a non-utf8 // locale is in use, and possibly doing that for any OS, not just windows. return runtime.GOOS == "windows" } func edit(editorCommand, fn, initialValue string, stdin io.Reader, stdout io.Writer, stderr io.Writer, cursor showable, lookPath func(string) ([]string, []string, error)) (string, error) { // prepare the temp file pattern := fn if pattern == "" { pattern = "survey*.txt" } f, err := os.CreateTemp("", pattern) if err != nil { return "", err } defer os.Remove(f.Name()) // write utf8 BOM header if necessary for the current platform and/or locale if needsBom() { if _, err := f.Write(bom); err != nil { return "", err } } // write initial value if _, err := f.WriteString(initialValue); err != nil { return "", err } // close the fd to prevent the editor unable to save file if err := f.Close(); err != nil { return "", err } if editorCommand == "" { editorCommand = defaultEditor } args, err := shellquote.Split(editorCommand) if err != nil { return "", err } args = append(args, f.Name()) editorExe, env, err := lookPath(args[0]) if err != nil { return "", err } args = append(editorExe, args[1:]...) cmd := exec.Command(args[0], args[1:]...) cmd.Env = env cmd.Stdin = stdin cmd.Stdout = stdout cmd.Stderr = stderr if cursor != nil { _ = cursor.Show() } // open the editor if err := cmd.Run(); err != nil { return "", err } // raw is a BOM-unstripped UTF8 byte slice raw, err := os.ReadFile(f.Name()) if err != nil { return "", err } // strip BOM header return string(bytes.TrimPrefix(raw, bom)), nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/cmd/gh/main.go
cmd/gh/main.go
package main import ( "os" "github.com/cli/cli/v2/internal/ghcmd" ) func main() { code := ghcmd.Main() os.Exit(int(code)) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/cmd/gen-docs/main_test.go
cmd/gen-docs/main_test.go
package main import ( "os" "strings" "testing" ) func Test_run(t *testing.T) { dir := t.TempDir() args := []string{"--man-page", "--website", "--doc-path", dir} err := run(args) if err != nil { t.Fatalf("got error: %v", err) } manPage, err := os.ReadFile(dir + "/gh-issue-create.1") if err != nil { t.Fatalf("error reading `gh-issue-create.1`: %v", err) } if !strings.Contains(string(manPage), `\fBgh issue create`) { t.Fatal("man page corrupted") } markdownPage, err := os.ReadFile(dir + "/gh_issue_create.md") if err != nil { t.Fatalf("error reading `gh_issue_create.md`: %v", err) } if !strings.Contains(string(markdownPage), `## gh issue create`) { t.Fatal("markdown page corrupted") } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/cmd/gen-docs/main.go
cmd/gen-docs/main.go
package main import ( "fmt" "io" "os" "path/filepath" "strings" "github.com/cli/cli/v2/internal/config" "github.com/cli/cli/v2/internal/docs" "github.com/cli/cli/v2/internal/gh" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/cmd/root" "github.com/cli/cli/v2/pkg/cmdutil" "github.com/cli/cli/v2/pkg/extensions" "github.com/cli/cli/v2/pkg/iostreams" "github.com/spf13/pflag" ) func main() { if err := run(os.Args); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } func run(args []string) error { flags := pflag.NewFlagSet("", pflag.ContinueOnError) manPage := flags.BoolP("man-page", "", false, "Generate manual pages") website := flags.BoolP("website", "", false, "Generate website pages") dir := flags.StringP("doc-path", "", "", "Path directory where you want generate doc files") help := flags.BoolP("help", "h", false, "Help about any command") if err := flags.Parse(args); err != nil { return err } if *help { fmt.Fprintf(os.Stderr, "Usage of %s:\n\n%s", filepath.Base(args[0]), flags.FlagUsages()) return nil } if *dir == "" { return fmt.Errorf("error: --doc-path not set") } ios, _, _, _ := iostreams.Test() rootCmd, _ := root.NewCmdRoot(&cmdutil.Factory{ IOStreams: ios, Browser: &browser{}, Config: func() (gh.Config, error) { return config.NewFromString(""), nil }, ExtensionManager: &em{}, }, "", "") rootCmd.InitDefaultHelpCmd() if err := os.MkdirAll(*dir, 0755); err != nil { return err } if *website { if err := docs.GenMarkdownTreeCustom(rootCmd, *dir, filePrepender, linkHandler); err != nil { return err } } if *manPage { if err := docs.GenManTree(rootCmd, *dir); err != nil { return err } } return nil } func filePrepender(filename string) string { return `--- layout: manual permalink: /:path/:basename --- ` } func linkHandler(name string) string { return fmt.Sprintf("./%s", strings.TrimSuffix(name, ".md")) } // Implements browser.Browser interface. type browser struct{} func (b *browser) Browse(_ string) error { return nil } // Implements extensions.ExtensionManager interface. type em struct{} func (e *em) List() []extensions.Extension { return nil } func (e *em) Install(_ ghrepo.Interface, _ string) error { return nil } func (e *em) InstallLocal(_ string) error { return nil } func (e *em) Upgrade(_ string, _ bool) error { return nil } func (e *em) Remove(_ string) error { return nil } func (e *em) Dispatch(_ []string, _ io.Reader, _, _ io.Writer) (bool, error) { return false, nil } func (e *em) Create(_ string, _ extensions.ExtTemplateType) error { return nil } func (e *em) EnableDryRunMode() {} func (e *em) UpdateDir(_ string) string { return "" }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/test/helpers.go
test/helpers.go
package test import ( "bytes" "regexp" ) // TODO copypasta from command package type CmdOut struct { OutBuf *bytes.Buffer ErrBuf *bytes.Buffer BrowsedURL string } func (c CmdOut) String() string { return c.OutBuf.String() } func (c CmdOut) Stderr() string { return c.ErrBuf.String() } // OutputStub implements a simple utils.Runnable type OutputStub struct { Out []byte Error error } func (s OutputStub) Output() ([]byte, error) { if s.Error != nil { return s.Out, s.Error } return s.Out, nil } func (s OutputStub) Run() error { if s.Error != nil { return s.Error } return nil } type T interface { Helper() Errorf(string, ...interface{}) } // Deprecated: prefer exact matches for command output func ExpectLines(t T, output string, lines ...string) { t.Helper() var r *regexp.Regexp for _, l := range lines { r = regexp.MustCompile(l) if !r.MatchString(output) { t.Errorf("output did not match regexp /%s/\n> output\n%s\n", r, output) return } } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/acceptance/acceptance_test.go
acceptance/acceptance_test.go
//go:build acceptance package acceptance_test import ( "fmt" "os" "path" "strconv" "strings" "testing" "time" "math/rand" "github.com/cli/cli/v2/internal/ghcmd" "github.com/cli/go-internal/testscript" ) func ghMain() int { return int(ghcmd.Main()) } func TestMain(m *testing.M) { os.Exit(testscript.RunMain(m, map[string]func() int{ "gh": ghMain, })) } func TestAPI(t *testing.T) { var tsEnv testScriptEnv if err := tsEnv.fromEnv(); err != nil { t.Fatal(err) } testscript.Run(t, testScriptParamsFor(tsEnv, "api")) } func TestAuth(t *testing.T) { var tsEnv testScriptEnv if err := tsEnv.fromEnv(); err != nil { t.Fatal(err) } testscript.Run(t, testScriptParamsFor(tsEnv, "auth")) } func TestGPGKeys(t *testing.T) { var tsEnv testScriptEnv if err := tsEnv.fromEnv(); err != nil { t.Fatal(err) } testscript.Run(t, testScriptParamsFor(tsEnv, "gpg-key")) } func TestExtensions(t *testing.T) { var tsEnv testScriptEnv if err := tsEnv.fromEnv(); err != nil { t.Fatal(err) } testscript.Run(t, testScriptParamsFor(tsEnv, "extension")) } func TestIssues(t *testing.T) { var tsEnv testScriptEnv if err := tsEnv.fromEnv(); err != nil { t.Fatal(err) } testscript.Run(t, testScriptParamsFor(tsEnv, "issue")) } func TestLabels(t *testing.T) { var tsEnv testScriptEnv if err := tsEnv.fromEnv(); err != nil { t.Fatal(err) } testscript.Run(t, testScriptParamsFor(tsEnv, "label")) } func TestOrg(t *testing.T) { var tsEnv testScriptEnv if err := tsEnv.fromEnv(); err != nil { t.Fatal(err) } testscript.Run(t, testScriptParamsFor(tsEnv, "org")) } func TestProject(t *testing.T) { var tsEnv testScriptEnv if err := tsEnv.fromEnv(); err != nil { t.Fatal(err) } testscript.Run(t, testScriptParamsFor(tsEnv, "project")) } func TestPullRequests(t *testing.T) { var tsEnv testScriptEnv if err := tsEnv.fromEnv(); err != nil { t.Fatal(err) } testscript.Run(t, testScriptParamsFor(tsEnv, "pr")) } func TestReleases(t *testing.T) { var tsEnv testScriptEnv if err := tsEnv.fromEnv(); err != nil { t.Fatal(err) } testscript.Run(t, testScriptParamsFor(tsEnv, "release")) } func TestRepo(t *testing.T) { var tsEnv testScriptEnv if err := tsEnv.fromEnv(); err != nil { t.Fatal(err) } testscript.Run(t, testScriptParamsFor(tsEnv, "repo")) } func TestRulesets(t *testing.T) { var tsEnv testScriptEnv if err := tsEnv.fromEnv(); err != nil { t.Fatal(err) } testscript.Run(t, testScriptParamsFor(tsEnv, "ruleset")) } func TestSearches(t *testing.T) { var tsEnv testScriptEnv if err := tsEnv.fromEnv(); err != nil { t.Fatal(err) } testscript.Run(t, testScriptParamsFor(tsEnv, "search")) } func TestSecrets(t *testing.T) { var tsEnv testScriptEnv if err := tsEnv.fromEnv(); err != nil { t.Fatal(err) } testscript.Run(t, testScriptParamsFor(tsEnv, "secret")) } func TestSSHKeys(t *testing.T) { var tsEnv testScriptEnv if err := tsEnv.fromEnv(); err != nil { t.Fatal(err) } testscript.Run(t, testScriptParamsFor(tsEnv, "ssh-key")) } func TestVariables(t *testing.T) { var tsEnv testScriptEnv if err := tsEnv.fromEnv(); err != nil { t.Fatal(err) } testscript.Run(t, testScriptParamsFor(tsEnv, "variable")) } func TestWorkflows(t *testing.T) { var tsEnv testScriptEnv if err := tsEnv.fromEnv(); err != nil { t.Fatal(err) } testscript.Run(t, testScriptParamsFor(tsEnv, "workflow")) } func testScriptParamsFor(tsEnv testScriptEnv, command string) testscript.Params { var files []string if tsEnv.script != "" { files = []string{path.Join("testdata", command, tsEnv.script)} } var dir string if len(files) == 0 { dir = path.Join("testdata", command) } return testscript.Params{ Dir: dir, Files: files, Setup: sharedSetup(tsEnv), Cmds: sharedCmds(tsEnv), RequireExplicitExec: true, RequireUniqueNames: true, TestWork: tsEnv.preserveWorkDir, } } var keyT struct{} func sharedSetup(tsEnv testScriptEnv) func(ts *testscript.Env) error { return func(ts *testscript.Env) error { scriptName, ok := extractScriptName(ts.Vars) if !ok { ts.T().Fatal("script name not found") } // When using script name to uniquely identify where test data comes from, // some places like GitHub Actions secret names don't accept hyphens. // Replace them with underscores until such a time this becomes a problem. ts.Setenv("SCRIPT_NAME", strings.ReplaceAll(scriptName, "-", "_")) ts.Setenv("HOME", ts.Cd) ts.Setenv("GH_CONFIG_DIR", ts.Cd) ts.Setenv("GH_HOST", tsEnv.host) ts.Setenv("ORG", tsEnv.org) ts.Setenv("GH_TOKEN", tsEnv.token) ts.Setenv("RANDOM_STRING", randomString(10)) ts.Values[keyT] = ts.T() return nil } } // sharedCmds defines a collection of custom testscript commands for our use. func sharedCmds(tsEnv testScriptEnv) map[string]func(ts *testscript.TestScript, neg bool, args []string) { return map[string]func(ts *testscript.TestScript, neg bool, args []string){ "defer": func(ts *testscript.TestScript, neg bool, args []string) { if neg { ts.Fatalf("unsupported: ! defer") } if tsEnv.skipDefer { return } tt, ok := ts.Value(keyT).(testscript.T) if !ok { ts.Fatalf("%v is not a testscript.T", ts.Value(keyT)) } ts.Defer(func() { // If you're wondering why we're not using ts.Check here, it's because it raises a panic, and testscript // only catches the panics directly from commands, not from the deferred functions. So what we do // instead is grab the `t` in the setup function and store it as a value. It's important that we use // `t` from the setup function because it represents the subtest created for each individual script, // rather than each top-level test. // See: https://github.com/rogpeppe/go-internal/issues/276 if err := ts.Exec(args[0], args[1:]...); err != nil { tt.FailNow() } }) }, "env2upper": func(ts *testscript.TestScript, neg bool, args []string) { if neg { ts.Fatalf("unsupported: ! env2upper") } if len(args) == 0 { ts.Fatalf("usage: env2upper name=value ...") } for _, env := range args { i := strings.Index(env, "=") if i < 0 { ts.Fatalf("env2upper: argument does not match name=value") } ts.Setenv(env[:i], strings.ToUpper(env[i+1:])) } }, "replace": func(ts *testscript.TestScript, neg bool, args []string) { if neg { ts.Fatalf("unsupported: ! replace") } if len(args) < 2 { ts.Fatalf("usage: replace file env...") } src := ts.MkAbs(args[0]) ts.Logf("replace src: %s", src) // Preserve the existing file mode while replacing the contents similar to native cp behavior info, err := os.Stat(src) ts.Check(err) mode := info.Mode() & 0o777 data, err := os.ReadFile(src) ts.Check(err) for _, arg := range args[1:] { i := strings.Index(arg, "=") if i < 0 { ts.Fatalf("replace: %s argument does not match name=value", arg) } name := fmt.Sprintf("$%s", arg[:i]) value := arg[i+1:] ts.Logf("replace %s: %s", name, value) // `replace` was originally built similar to `cp` and `cmpenv`, expanding environment variables within a file. // However files with content that looks like environments variable such as GitHub Actions workflows // were being modified unexpectedly. Thus `replace` has been designed to using string replacement // looking for `$KEY` specifically. data = []byte(strings.ReplaceAll(string(data), name, value)) } ts.Check(os.WriteFile(src, data, mode)) }, "stdout2env": func(ts *testscript.TestScript, neg bool, args []string) { if neg { ts.Fatalf("unsupported: ! stdout2env") } if len(args) != 1 { ts.Fatalf("usage: stdout2env name") } ts.Setenv(args[0], strings.TrimRight(ts.ReadFile("stdout"), "\n")) }, "sleep": func(ts *testscript.TestScript, neg bool, args []string) { if neg { ts.Fatalf("unsupported: ! sleep") } if len(args) != 1 { ts.Fatalf("usage: sleep seconds") } // sleep for the given number of seconds seconds, err := strconv.Atoi(args[0]) if err != nil { ts.Fatalf("invalid number of seconds: %v", err) } d := time.Duration(seconds) * time.Second time.Sleep(d) }, } } var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") func randomString(n int) string { b := make([]rune, n) for i := range b { b[i] = letters[rand.Intn(len(letters))] } return string(b) } func extractScriptName(vars []string) (string, bool) { for _, kv := range vars { if strings.HasPrefix(kv, "WORK=") { v := strings.Split(kv, "=")[1] return strings.CutPrefix(path.Base(v), "script-") } } return "", false } type missingEnvError struct { missingEnvs []string } func (e missingEnvError) Error() string { return fmt.Sprintf("environment variable(s) %s must be set and non-empty", strings.Join(e.missingEnvs, ", ")) } type testScriptEnv struct { host string org string token string script string skipDefer bool preserveWorkDir bool } func (e *testScriptEnv) fromEnv() error { envMap := map[string]string{} requiredEnvVars := []string{ "GH_ACCEPTANCE_HOST", "GH_ACCEPTANCE_ORG", "GH_ACCEPTANCE_TOKEN", } var missingEnvs []string for _, key := range requiredEnvVars { val, ok := os.LookupEnv(key) if val == "" || !ok { missingEnvs = append(missingEnvs, key) continue } envMap[key] = val } if len(missingEnvs) > 0 { return missingEnvError{missingEnvs: missingEnvs} } if envMap["GH_ACCEPTANCE_ORG"] == "github" || envMap["GH_ACCEPTANCE_ORG"] == "cli" { return fmt.Errorf("GH_ACCEPTANCE_ORG cannot be 'github' or 'cli'") } e.host = envMap["GH_ACCEPTANCE_HOST"] e.org = envMap["GH_ACCEPTANCE_ORG"] e.token = envMap["GH_ACCEPTANCE_TOKEN"] e.script = os.Getenv("GH_ACCEPTANCE_SCRIPT") e.preserveWorkDir = os.Getenv("GH_ACCEPTANCE_PRESERVE_WORK_DIR") == "true" e.skipDefer = os.Getenv("GH_ACCEPTANCE_SKIP_DEFER") == "true" return nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/utils/utils.go
utils/utils.go
package utils import ( "fmt" "os" "golang.org/x/term" ) func IsDebugEnabled() (bool, string) { debugValue, isDebugSet := os.LookupEnv("GH_DEBUG") legacyDebugValue := os.Getenv("DEBUG") if !isDebugSet { switch legacyDebugValue { case "true", "1", "yes", "api": return true, legacyDebugValue default: return false, legacyDebugValue } } switch debugValue { case "false", "0", "no", "": return false, debugValue default: return true, debugValue } } var TerminalSize = func(w interface{}) (int, int, error) { if f, isFile := w.(*os.File); isFile { return term.GetSize(int(f.Fd())) } return 0, 0, fmt.Errorf("%v is not a file", w) }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/api/queries_projects_v2_test.go
api/queries_projects_v2_test.go
package api import ( "errors" "fmt" "sort" "strings" "testing" "unicode" "github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/pkg/httpmock" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestUpdateProjectV2Items(t *testing.T) { var tests = []struct { name string httpStubs func(*httpmock.Registry) expectError bool }{ { name: "updates project items", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`mutation UpdateProjectV2Items\b`), httpmock.GraphQLQuery(`{"data":{"add_000":{"item":{"id":"1"}},"delete_001":{"item":{"id":"2"}}}}`, func(mutations string, inputs map[string]interface{}) { expectedMutations := ` mutation UpdateProjectV2Items( $input_000: AddProjectV2ItemByIdInput! $input_001: AddProjectV2ItemByIdInput! $input_002: DeleteProjectV2ItemInput! $input_003: DeleteProjectV2ItemInput! ) { add_000: addProjectV2ItemById(input: $input_000) { item { id } } add_001: addProjectV2ItemById(input: $input_001) { item { id } } delete_002: deleteProjectV2Item(input: $input_002) { deletedItemId } delete_003: deleteProjectV2Item(input: $input_003) { deletedItemId } }` assert.Equal(t, stripSpace(expectedMutations), stripSpace(mutations)) if len(inputs) != 4 { t.Fatalf("expected 4 inputs, got %d", len(inputs)) } i0 := inputs["input_000"].(map[string]interface{}) i1 := inputs["input_001"].(map[string]interface{}) i2 := inputs["input_002"].(map[string]interface{}) i3 := inputs["input_003"].(map[string]interface{}) adds := []string{ fmt.Sprintf("%v -> %v", i0["contentId"], i0["projectId"]), fmt.Sprintf("%v -> %v", i1["contentId"], i1["projectId"]), } removes := []string{ fmt.Sprintf("%v x %v", i2["itemId"], i2["projectId"]), fmt.Sprintf("%v x %v", i3["itemId"], i3["projectId"]), } sort.Strings(adds) sort.Strings(removes) assert.Equal(t, []string{"item1 -> project1", "item2 -> project2"}, adds) assert.Equal(t, []string{"item3 x project3", "item4 x project4"}, removes) })) }, }, { name: "fails to update project items", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`mutation UpdateProjectV2Items\b`), httpmock.GraphQLMutation(`{"data":{}, "errors": [{"message": "some gql error"}]}`, func(inputs map[string]interface{}) {}), ) }, expectError: true, }, } 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) } client := newTestClient(reg) repo, _ := ghrepo.FromFullName("OWNER/REPO") addProjectItems := map[string]string{"project1": "item1", "project2": "item2"} deleteProjectItems := map[string]string{"project3": "item3", "project4": "item4"} err := UpdateProjectV2Items(client, repo, addProjectItems, deleteProjectItems) if tt.expectError { assert.Error(t, err) } else { assert.NoError(t, err) } }) } } func TestProjectsV2ItemsForIssue(t *testing.T) { var tests = []struct { name string httpStubs func(*httpmock.Registry) expectItems ProjectItems expectError bool }{ { name: "retrieves project items for issue", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueProjectItems\b`), httpmock.GraphQLQuery(`{"data":{"repository":{"issue":{"projectItems":{"nodes": [{"id":"projectItem1"},{"id":"projectItem2"}]}}}}}`, func(query string, inputs map[string]interface{}) {}), ) }, expectItems: ProjectItems{ Nodes: []*ProjectV2Item{ {ID: "projectItem1"}, {ID: "projectItem2"}, }, }, }, { name: "fails to retrieve project items for issue", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueProjectItems\b`), httpmock.GraphQLQuery(`{"data":{}, "errors": [{"message": "some gql error"}]}`, func(query string, inputs map[string]interface{}) {}), ) }, expectError: true, }, { name: "skips null project items for issue", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query IssueProjectItems\b`), httpmock.GraphQLQuery(`{"data":{"repository":{"issue":{"projectItems":{"totalCount":1,"nodes":[null]}}}}}`, func(query string, inputs map[string]interface{}) {}), ) }, expectItems: ProjectItems{}, }, } 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) } client := newTestClient(reg) repo, _ := ghrepo.FromFullName("OWNER/REPO") issue := &Issue{Number: 1} err := ProjectsV2ItemsForIssue(client, repo, issue) if tt.expectError { assert.Error(t, err) } else { assert.NoError(t, err) } assert.Equal(t, tt.expectItems, issue.ProjectItems) }) } } func TestProjectsV2ItemsForPullRequest(t *testing.T) { var tests = []struct { name string httpStubs func(*httpmock.Registry) expectItems ProjectItems expectError bool }{ { name: "retrieves project items for pull request", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query PullRequestProjectItems\b`), httpmock.GraphQLQuery(`{"data":{"repository":{"pullRequest":{"projectItems":{"nodes": [{"id":"projectItem3"},{"id":"projectItem4"}]}}}}}`, func(query string, inputs map[string]interface{}) {}), ) }, expectItems: ProjectItems{ Nodes: []*ProjectV2Item{ {ID: "projectItem3"}, {ID: "projectItem4"}, }, }, }, { name: "fails to retrieve project items for pull request", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query PullRequestProjectItems\b`), httpmock.GraphQLQuery(`{"data":{}, "errors": [{"message": "some gql error"}]}`, func(query string, inputs map[string]interface{}) {}), ) }, expectError: true, }, { name: "skips null project items for pull request", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query PullRequestProjectItems\b`), httpmock.GraphQLQuery(`{"data":{"repository":{"pullRequest":{"projectItems":{"totalCount":1,"nodes":[null]}}}}}`, func(query string, inputs map[string]interface{}) {}), ) }, expectItems: ProjectItems{}, }, { name: "retrieves project items that have status columns", httpStubs: func(reg *httpmock.Registry) { reg.Register( httpmock.GraphQL(`query PullRequestProjectItems\b`), httpmock.GraphQLQuery(`{ "data": { "repository": { "pullRequest": { "projectItems": { "nodes": [ { "id": "PVTI_lADOB-vozM4AVk16zgK6U50", "project": { "id": "PVT_kwDOB-vozM4AVk16", "title": "Test Project" }, "status": { "optionId": "47fc9ee4", "name": "In Progress" } } ], "pageInfo": { "hasNextPage": false, "endCursor": "MQ" } } } } } }`, func(query string, inputs map[string]interface{}) { require.Equal(t, float64(1), inputs["number"]) require.Equal(t, "OWNER", inputs["owner"]) require.Equal(t, "REPO", inputs["name"]) }), ) }, expectItems: ProjectItems{ Nodes: []*ProjectV2Item{ { ID: "PVTI_lADOB-vozM4AVk16zgK6U50", Project: ProjectV2ItemProject{ ID: "PVT_kwDOB-vozM4AVk16", Title: "Test Project", }, Status: ProjectV2ItemStatus{ OptionID: "47fc9ee4", Name: "In Progress", }, }, }, }, }, } 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) } client := newTestClient(reg) repo, _ := ghrepo.FromFullName("OWNER/REPO") pr := &PullRequest{Number: 1} err := ProjectsV2ItemsForPullRequest(client, repo, pr) if tt.expectError { require.Error(t, err) } else { require.NoError(t, err) } require.Equal(t, tt.expectItems, pr.ProjectItems) }) } } func TestProjectsV2IgnorableError(t *testing.T) { var tests = []struct { name string errMsg string expectOut bool }{ { name: "read scope error", errMsg: "field requires one of the following scopes: ['read:project']", expectOut: true, }, { name: "repository projectsV2 field error", errMsg: "Field 'projectsV2' doesn't exist on type 'Repository'", expectOut: true, }, { name: "organization projectsV2 field error", errMsg: "Field 'projectsV2' doesn't exist on type 'Organization'", expectOut: true, }, { name: "issue projectItems field error", errMsg: "Field 'projectItems' doesn't exist on type 'Issue'", expectOut: true, }, { name: "pullRequest projectItems field error", errMsg: "Field 'projectItems' doesn't exist on type 'PullRequest'", expectOut: true, }, { name: "other error", errMsg: "some other graphql error message", expectOut: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := errors.New(tt.errMsg) out := ProjectsV2IgnorableError(err) assert.Equal(t, tt.expectOut, out) }) } } func stripSpace(str string) string { var b strings.Builder b.Grow(len(str)) for _, ch := range str { if !unicode.IsSpace(ch) { b.WriteRune(ch) } } return b.String() }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/api/queries_branch_issue_reference.go
api/queries_branch_issue_reference.go
package api import ( "fmt" "github.com/cli/cli/v2/internal/ghrepo" "github.com/shurcooL/githubv4" ) type LinkedBranch struct { BranchName string URL string } func CreateLinkedBranch(client *Client, host string, repoID, issueID, branchID, branchName string) (string, error) { var mutation struct { CreateLinkedBranch struct { LinkedBranch struct { ID string Ref struct { Name string } } } `graphql:"createLinkedBranch(input: $input)"` } input := githubv4.CreateLinkedBranchInput{ IssueID: githubv4.ID(issueID), Oid: githubv4.GitObjectID(branchID), } if repoID != "" { repo := githubv4.ID(repoID) input.RepositoryID = &repo } if branchName != "" { name := githubv4.String(branchName) input.Name = &name } variables := map[string]interface{}{ "input": input, } err := client.Mutate(host, "CreateLinkedBranch", &mutation, variables) if err != nil { return "", err } return mutation.CreateLinkedBranch.LinkedBranch.Ref.Name, nil } func ListLinkedBranches(client *Client, repo ghrepo.Interface, issueNumber int) ([]LinkedBranch, error) { var query struct { Repository struct { Issue struct { LinkedBranches struct { Nodes []struct { Ref struct { Name string Repository struct { Url string } } } } `graphql:"linkedBranches(first: 30)"` } `graphql:"issue(number: $number)"` } `graphql:"repository(owner: $owner, name: $name)"` } variables := map[string]interface{}{ "number": githubv4.Int(issueNumber), "owner": githubv4.String(repo.RepoOwner()), "name": githubv4.String(repo.RepoName()), } if err := client.Query(repo.RepoHost(), "ListLinkedBranches", &query, variables); err != nil { return []LinkedBranch{}, err } var branchNames []LinkedBranch for _, node := range query.Repository.Issue.LinkedBranches.Nodes { branch := LinkedBranch{ BranchName: node.Ref.Name, URL: fmt.Sprintf("%s/tree/%s", node.Ref.Repository.Url, node.Ref.Name), } branchNames = append(branchNames, branch) } return branchNames, nil } func CheckLinkedBranchFeature(client *Client, host string) error { var query struct { Name struct { Fields []struct { Name string } } `graphql:"LinkedBranch: __type(name: \"LinkedBranch\")"` } if err := client.Query(host, "LinkedBranchFeature", &query, nil); err != nil { return err } if len(query.Name.Fields) == 0 { return fmt.Errorf("the `gh issue develop` command is not currently available") } return nil } func FindRepoBranchID(client *Client, repo ghrepo.Interface, ref string) (string, string, error) { var query struct { Repository struct { Id string DefaultBranchRef struct { Target struct { Oid string } } Ref struct { Target struct { Oid string } } `graphql:"ref(qualifiedName: $ref)"` } `graphql:"repository(owner: $owner, name: $name)"` } variables := map[string]interface{}{ "ref": githubv4.String(ref), "owner": githubv4.String(repo.RepoOwner()), "name": githubv4.String(repo.RepoName()), } if err := client.Query(repo.RepoHost(), "FindRepoBranchID", &query, variables); err != nil { return "", "", err } branchID := query.Repository.Ref.Target.Oid if branchID == "" { if ref != "" { return "", "", fmt.Errorf("could not find branch %q in %s", ref, ghrepo.FullName(repo)) } branchID = query.Repository.DefaultBranchRef.Target.Oid } return query.Repository.Id, branchID, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/api/export_repo.go
api/export_repo.go
package api import ( "reflect" ) func (repo *Repository) ExportData(fields []string) map[string]interface{} { v := reflect.ValueOf(repo).Elem() data := map[string]interface{}{} for _, f := range fields { switch f { case "parent": data[f] = miniRepoExport(repo.Parent) case "templateRepository": data[f] = miniRepoExport(repo.TemplateRepository) case "languages": data[f] = repo.Languages.Edges case "labels": data[f] = repo.Labels.Nodes case "assignableUsers": data[f] = repo.AssignableUsers.Nodes case "mentionableUsers": data[f] = repo.MentionableUsers.Nodes case "milestones": data[f] = repo.Milestones.Nodes case "projects": data[f] = repo.Projects.Nodes case "repositoryTopics": var topics []RepositoryTopic for _, n := range repo.RepositoryTopics.Nodes { topics = append(topics, n.Topic) } data[f] = topics default: sf := fieldByName(v, f) data[f] = sf.Interface() } } return data } func miniRepoExport(r *Repository) map[string]interface{} { if r == nil { return nil } return map[string]interface{}{ "id": r.ID, "name": r.Name, "owner": r.Owner, } }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/api/queries_user.go
api/queries_user.go
package api type Organization struct { Login string } func CurrentLoginName(client *Client, hostname string) (string, error) { var query struct { Viewer struct { Login string } } err := client.Query(hostname, "UserCurrent", &query, nil) return query.Viewer.Login, err } func CurrentLoginNameAndOrgs(client *Client, hostname string) (string, []string, error) { var query struct { Viewer struct { Login string Organizations struct { Nodes []Organization } `graphql:"organizations(first: 100)"` } } err := client.Query(hostname, "UserCurrent", &query, nil) if err != nil { return "", nil, err } orgNames := []string{} for _, org := range query.Viewer.Organizations.Nodes { orgNames = append(orgNames, org.Login) } return query.Viewer.Login, orgNames, nil } func CurrentUserID(client *Client, hostname string) (string, error) { var query struct { Viewer struct { ID string } } err := client.Query(hostname, "UserCurrent", &query, nil) return query.Viewer.ID, err }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/api/queries_pr.go
api/queries_pr.go
package api import ( "bytes" "encoding/json" "fmt" "net/http" "net/url" "time" "github.com/cli/cli/v2/internal/ghrepo" "github.com/shurcooL/githubv4" ) type PullRequestAndTotalCount struct { TotalCount int PullRequests []PullRequest SearchCapped bool } type PullRequestMergeable string const ( PullRequestMergeableConflicting PullRequestMergeable = "CONFLICTING" PullRequestMergeableMergeable PullRequestMergeable = "MERGEABLE" PullRequestMergeableUnknown PullRequestMergeable = "UNKNOWN" ) type PullRequest struct { ID string FullDatabaseID string Number int Title string State string Closed bool URL string BaseRefName string BaseRefOid string HeadRefName string HeadRefOid string Body string Mergeable PullRequestMergeable Additions int Deletions int ChangedFiles int MergeStateStatus string IsInMergeQueue bool IsMergeQueueEnabled bool // Indicates whether the pull request's base ref has a merge queue enabled. CreatedAt time.Time UpdatedAt time.Time ClosedAt *time.Time MergedAt *time.Time AutoMergeRequest *AutoMergeRequest MergeCommit *Commit PotentialMergeCommit *Commit Files struct { Nodes []PullRequestFile } Author Author MergedBy *Author HeadRepositoryOwner Owner HeadRepository *PRRepository Repository *PRRepository IsCrossRepository bool IsDraft bool MaintainerCanModify bool BaseRef struct { BranchProtectionRule struct { RequiresStrictStatusChecks bool RequiredApprovingReviewCount int } } ReviewDecision string Commits struct { TotalCount int Nodes []PullRequestCommit } StatusCheckRollup struct { Nodes []StatusCheckRollupNode } Assignees Assignees AssignedActors AssignedActors Labels Labels ProjectCards ProjectCards ProjectItems ProjectItems Milestone *Milestone Comments Comments ReactionGroups ReactionGroups Reviews PullRequestReviews LatestReviews PullRequestReviews ReviewRequests ReviewRequests ClosingIssuesReferences ClosingIssuesReferences } type StatusCheckRollupNode struct { Commit StatusCheckRollupCommit } type StatusCheckRollupCommit struct { StatusCheckRollup CommitStatusCheckRollup } type CommitStatusCheckRollup struct { Contexts CheckContexts } type ClosingIssuesReferences struct { Nodes []struct { ID string Number int URL string Repository struct { ID string Name string Owner struct { ID string Login string } } } PageInfo struct { HasNextPage bool EndCursor string } } // https://docs.github.com/en/graphql/reference/enums#checkrunstate type CheckRunState string const ( CheckRunStateActionRequired CheckRunState = "ACTION_REQUIRED" CheckRunStateCancelled CheckRunState = "CANCELLED" CheckRunStateCompleted CheckRunState = "COMPLETED" CheckRunStateFailure CheckRunState = "FAILURE" CheckRunStateInProgress CheckRunState = "IN_PROGRESS" CheckRunStateNeutral CheckRunState = "NEUTRAL" CheckRunStatePending CheckRunState = "PENDING" CheckRunStateQueued CheckRunState = "QUEUED" CheckRunStateSkipped CheckRunState = "SKIPPED" CheckRunStateStale CheckRunState = "STALE" CheckRunStateStartupFailure CheckRunState = "STARTUP_FAILURE" CheckRunStateSuccess CheckRunState = "SUCCESS" CheckRunStateTimedOut CheckRunState = "TIMED_OUT" CheckRunStateWaiting CheckRunState = "WAITING" ) type CheckRunCountByState struct { State CheckRunState Count int } // https://docs.github.com/en/graphql/reference/enums#statusstate type StatusState string const ( StatusStateError StatusState = "ERROR" StatusStateExpected StatusState = "EXPECTED" StatusStateFailure StatusState = "FAILURE" StatusStatePending StatusState = "PENDING" StatusStateSuccess StatusState = "SUCCESS" ) type StatusContextCountByState struct { State StatusState Count int } // https://docs.github.com/en/graphql/reference/enums#checkstatusstate type CheckStatusState string const ( CheckStatusStateCompleted CheckStatusState = "COMPLETED" CheckStatusStateInProgress CheckStatusState = "IN_PROGRESS" CheckStatusStatePending CheckStatusState = "PENDING" CheckStatusStateQueued CheckStatusState = "QUEUED" CheckStatusStateRequested CheckStatusState = "REQUESTED" CheckStatusStateWaiting CheckStatusState = "WAITING" ) // https://docs.github.com/en/graphql/reference/enums#checkconclusionstate type CheckConclusionState string const ( CheckConclusionStateActionRequired CheckConclusionState = "ACTION_REQUIRED" CheckConclusionStateCancelled CheckConclusionState = "CANCELLED" CheckConclusionStateFailure CheckConclusionState = "FAILURE" CheckConclusionStateNeutral CheckConclusionState = "NEUTRAL" CheckConclusionStateSkipped CheckConclusionState = "SKIPPED" CheckConclusionStateStale CheckConclusionState = "STALE" CheckConclusionStateStartupFailure CheckConclusionState = "STARTUP_FAILURE" CheckConclusionStateSuccess CheckConclusionState = "SUCCESS" CheckConclusionStateTimedOut CheckConclusionState = "TIMED_OUT" ) type CheckContexts struct { // These fields are available on newer versions of the GraphQL API // to support summary counts by state CheckRunCount int CheckRunCountsByState []CheckRunCountByState StatusContextCount int StatusContextCountsByState []StatusContextCountByState // These are available on older versions and provide more details // required for checks Nodes []CheckContext PageInfo struct { HasNextPage bool EndCursor string } } type CheckContext struct { TypeName string `json:"__typename"` Name string `json:"name"` IsRequired bool `json:"isRequired"` CheckSuite CheckSuite `json:"checkSuite"` // QUEUED IN_PROGRESS COMPLETED WAITING PENDING REQUESTED Status string `json:"status"` // ACTION_REQUIRED TIMED_OUT CANCELLED FAILURE SUCCESS NEUTRAL SKIPPED STARTUP_FAILURE STALE Conclusion CheckConclusionState `json:"conclusion"` StartedAt time.Time `json:"startedAt"` CompletedAt time.Time `json:"completedAt"` DetailsURL string `json:"detailsUrl"` /* StatusContext fields */ Context string `json:"context"` Description string `json:"description"` // EXPECTED ERROR FAILURE PENDING SUCCESS State StatusState `json:"state"` TargetURL string `json:"targetUrl"` CreatedAt time.Time `json:"createdAt"` } type CheckSuite struct { WorkflowRun WorkflowRun `json:"workflowRun"` } type WorkflowRun struct { Event string `json:"event"` Workflow Workflow `json:"workflow"` } type Workflow struct { Name string `json:"name"` } type PRRepository struct { ID string `json:"id"` Name string `json:"name"` NameWithOwner string `json:"nameWithOwner"` } type AutoMergeRequest struct { AuthorEmail *string `json:"authorEmail"` CommitBody *string `json:"commitBody"` CommitHeadline *string `json:"commitHeadline"` // MERGE, REBASE, SQUASH MergeMethod string `json:"mergeMethod"` EnabledAt time.Time `json:"enabledAt"` EnabledBy Author `json:"enabledBy"` } // Commit loads just the commit SHA and nothing else type Commit struct { OID string `json:"oid"` } type PullRequestCommit struct { Commit PullRequestCommitCommit } // PullRequestCommitCommit contains full information about a commit type PullRequestCommitCommit struct { OID string `json:"oid"` Authors struct { Nodes []struct { Name string Email string User GitHubUser } } MessageHeadline string MessageBody string CommittedDate time.Time AuthoredDate time.Time } type PullRequestFile struct { Path string `json:"path"` Additions int `json:"additions"` Deletions int `json:"deletions"` } type ReviewRequests struct { Nodes []struct { RequestedReviewer RequestedReviewer } } type RequestedReviewer struct { TypeName string `json:"__typename"` Login string `json:"login"` Name string `json:"name"` Slug string `json:"slug"` Organization struct { Login string `json:"login"` } `json:"organization"` } func (r RequestedReviewer) LoginOrSlug() string { if r.TypeName == teamTypeName { return fmt.Sprintf("%s/%s", r.Organization.Login, r.Slug) } return r.Login } const teamTypeName = "Team" func (r ReviewRequests) Logins() []string { logins := make([]string, len(r.Nodes)) for i, r := range r.Nodes { logins[i] = r.RequestedReviewer.LoginOrSlug() } return logins } func (pr PullRequest) HeadLabel() string { if pr.IsCrossRepository { return fmt.Sprintf("%s:%s", pr.HeadRepositoryOwner.Login, pr.HeadRefName) } return pr.HeadRefName } func (pr PullRequest) Link() string { return pr.URL } func (pr PullRequest) Identifier() string { return pr.ID } func (pr PullRequest) CurrentUserComments() []Comment { return pr.Comments.CurrentUserComments() } func (pr PullRequest) IsOpen() bool { return pr.State == "OPEN" } type PullRequestReviewStatus struct { ChangesRequested bool Approved bool ReviewRequired bool } func (pr *PullRequest) ReviewStatus() PullRequestReviewStatus { var status PullRequestReviewStatus switch pr.ReviewDecision { case "CHANGES_REQUESTED": status.ChangesRequested = true case "APPROVED": status.Approved = true case "REVIEW_REQUIRED": status.ReviewRequired = true } return status } type PullRequestChecksStatus struct { Pending int Failing int Passing int Total int } func (pr *PullRequest) ChecksStatus() PullRequestChecksStatus { var summary PullRequestChecksStatus if len(pr.StatusCheckRollup.Nodes) == 0 { return summary } contexts := pr.StatusCheckRollup.Nodes[0].Commit.StatusCheckRollup.Contexts // If this commit has counts by state then we can summarise check status from those if len(contexts.CheckRunCountsByState) != 0 && len(contexts.StatusContextCountsByState) != 0 { summary.Total = contexts.CheckRunCount + contexts.StatusContextCount for _, countByState := range contexts.CheckRunCountsByState { switch parseCheckStatusFromCheckRunState(countByState.State) { case passing: summary.Passing += countByState.Count case failing: summary.Failing += countByState.Count default: summary.Pending += countByState.Count } } for _, countByState := range contexts.StatusContextCountsByState { switch parseCheckStatusFromStatusState(countByState.State) { case passing: summary.Passing += countByState.Count case failing: summary.Failing += countByState.Count default: summary.Pending += countByState.Count } } return summary } // If we don't have the counts by state, then we'll need to summarise by looking at the more detailed contexts for _, c := range contexts.Nodes { // Nodes are a discriminated union of CheckRun or StatusContext and we can match on // the TypeName to narrow the type. if c.TypeName == "CheckRun" { // https://docs.github.com/en/graphql/reference/enums#checkstatusstate // If the status is completed then we can check the conclusion field if c.Status == "COMPLETED" { switch parseCheckStatusFromCheckConclusionState(c.Conclusion) { case passing: summary.Passing++ case failing: summary.Failing++ default: summary.Pending++ } // otherwise we're in some form of pending state: // "COMPLETED", "IN_PROGRESS", "PENDING", "QUEUED", "REQUESTED", "WAITING" or otherwise unknown } else { summary.Pending++ } } else { // c.TypeName == StatusContext switch parseCheckStatusFromStatusState(c.State) { case passing: summary.Passing++ case failing: summary.Failing++ default: summary.Pending++ } } summary.Total++ } return summary } type checkStatus int const ( passing checkStatus = iota failing pending ) func parseCheckStatusFromStatusState(state StatusState) checkStatus { switch state { case StatusStateSuccess: return passing case StatusStateFailure, StatusStateError: return failing case StatusStateExpected, StatusStatePending: return pending // Currently, we treat anything unknown as pending, which includes any future unknown // states we might get back from the API. It might be interesting to do some work to add an additional // unknown state. default: return pending } } func parseCheckStatusFromCheckRunState(state CheckRunState) checkStatus { switch state { case CheckRunStateNeutral, CheckRunStateSkipped, CheckRunStateSuccess: return passing case CheckRunStateActionRequired, CheckRunStateCancelled, CheckRunStateFailure, CheckRunStateTimedOut: return failing case CheckRunStateCompleted, CheckRunStateInProgress, CheckRunStatePending, CheckRunStateQueued, CheckRunStateStale, CheckRunStateStartupFailure, CheckRunStateWaiting: return pending // Currently, we treat anything unknown as pending, which includes any future unknown // states we might get back from the API. It might be interesting to do some work to add an additional // unknown state. default: return pending } } func parseCheckStatusFromCheckConclusionState(state CheckConclusionState) checkStatus { switch state { case CheckConclusionStateNeutral, CheckConclusionStateSkipped, CheckConclusionStateSuccess: return passing case CheckConclusionStateActionRequired, CheckConclusionStateCancelled, CheckConclusionStateFailure, CheckConclusionStateTimedOut: return failing case CheckConclusionStateStale, CheckConclusionStateStartupFailure: return pending // Currently, we treat anything unknown as pending, which includes any future unknown // states we might get back from the API. It might be interesting to do some work to add an additional // unknown state. default: return pending } } func (pr *PullRequest) DisplayableReviews() PullRequestReviews { published := []PullRequestReview{} for _, prr := range pr.Reviews.Nodes { //Dont display pending reviews //Dont display commenting reviews without top level comment body if prr.State != "PENDING" && !(prr.State == "COMMENTED" && prr.Body == "") { published = append(published, prr) } } return PullRequestReviews{Nodes: published, TotalCount: len(published)} } // CreatePullRequest creates a pull request in a GitHub repository func CreatePullRequest(client *Client, repo *Repository, params map[string]interface{}) (*PullRequest, error) { query := ` mutation PullRequestCreate($input: CreatePullRequestInput!) { createPullRequest(input: $input) { pullRequest { id url } } }` inputParams := map[string]interface{}{ "repositoryId": repo.ID, } for key, val := range params { switch key { case "title", "body", "draft", "baseRefName", "headRefName", "maintainerCanModify": inputParams[key] = val } } variables := map[string]interface{}{ "input": inputParams, } result := struct { CreatePullRequest struct { PullRequest PullRequest } }{} err := client.GraphQL(repo.RepoHost(), query, variables, &result) if err != nil { return nil, err } pr := &result.CreatePullRequest.PullRequest // metadata parameters aren't currently available in `createPullRequest`, // but they are in `updatePullRequest` updateParams := make(map[string]interface{}) for key, val := range params { switch key { case "assigneeIds", "labelIds", "projectIds", "milestoneId": if !isBlank(val) { updateParams[key] = val } } } if len(updateParams) > 0 { updateQuery := ` mutation PullRequestCreateMetadata($input: UpdatePullRequestInput!) { updatePullRequest(input: $input) { clientMutationId } }` updateParams["pullRequestId"] = pr.ID variables := map[string]interface{}{ "input": updateParams, } err := client.GraphQL(repo.RepoHost(), updateQuery, variables, &result) if err != nil { return pr, err } } // reviewers are requested in yet another additional mutation reviewParams := make(map[string]interface{}) if ids, ok := params["userReviewerIds"]; ok && !isBlank(ids) { reviewParams["userIds"] = ids } if ids, ok := params["teamReviewerIds"]; ok && !isBlank(ids) { reviewParams["teamIds"] = ids } //TODO: How much work to extract this into own method and use for create and edit? if len(reviewParams) > 0 { reviewQuery := ` mutation PullRequestCreateRequestReviews($input: RequestReviewsInput!) { requestReviews(input: $input) { clientMutationId } }` reviewParams["pullRequestId"] = pr.ID reviewParams["union"] = true variables := map[string]interface{}{ "input": reviewParams, } err := client.GraphQL(repo.RepoHost(), reviewQuery, variables, &result) if err != nil { return pr, err } } // projectsV2 are added in yet another mutation projectV2Ids, ok := params["projectV2Ids"].([]string) if ok { projectItems := make(map[string]string, len(projectV2Ids)) for _, p := range projectV2Ids { projectItems[p] = pr.ID } err = UpdateProjectV2Items(client, repo, projectItems, nil) if err != nil { return pr, err } } return pr, nil } // AddPullRequestReviews adds the given user and team reviewers to a pull request using the REST API. func AddPullRequestReviews(client *Client, repo ghrepo.Interface, prNumber int, users, teams []string) error { if len(users) == 0 && len(teams) == 0 { return nil } // The API requires empty arrays instead of null values if users == nil { users = []string{} } if teams == nil { teams = []string{} } path := fmt.Sprintf( "repos/%s/%s/pulls/%d/requested_reviewers", url.PathEscape(repo.RepoOwner()), url.PathEscape(repo.RepoName()), prNumber, ) body := struct { Reviewers []string `json:"reviewers"` TeamReviewers []string `json:"team_reviewers"` }{ Reviewers: users, TeamReviewers: teams, } buf := &bytes.Buffer{} if err := json.NewEncoder(buf).Encode(body); err != nil { return err } // The endpoint responds with the updated pull request object; we don't need it here. return client.REST(repo.RepoHost(), "POST", path, buf, nil) } // RemovePullRequestReviews removes requested reviewers from a pull request using the REST API. func RemovePullRequestReviews(client *Client, repo ghrepo.Interface, prNumber int, users, teams []string) error { if len(users) == 0 && len(teams) == 0 { return nil } // The API requires empty arrays instead of null values if users == nil { users = []string{} } if teams == nil { teams = []string{} } path := fmt.Sprintf( "repos/%s/%s/pulls/%d/requested_reviewers", url.PathEscape(repo.RepoOwner()), url.PathEscape(repo.RepoName()), prNumber, ) body := struct { Reviewers []string `json:"reviewers"` TeamReviewers []string `json:"team_reviewers"` }{ Reviewers: users, TeamReviewers: teams, } buf := &bytes.Buffer{} if err := json.NewEncoder(buf).Encode(body); err != nil { return err } // The endpoint responds with the updated pull request object; we don't need it here. return client.REST(repo.RepoHost(), "DELETE", path, buf, nil) } func UpdatePullRequestBranch(client *Client, repo ghrepo.Interface, params githubv4.UpdatePullRequestBranchInput) error { var mutation struct { UpdatePullRequestBranch struct { PullRequest struct { ID string } } `graphql:"updatePullRequestBranch(input: $input)"` } variables := map[string]interface{}{"input": params} return client.Mutate(repo.RepoHost(), "PullRequestUpdateBranch", &mutation, variables) } func isBlank(v interface{}) bool { switch vv := v.(type) { case string: return vv == "" case []string: return len(vv) == 0 default: return true } } func PullRequestClose(httpClient *http.Client, repo ghrepo.Interface, prID string) error { var mutation struct { ClosePullRequest struct { PullRequest struct { ID githubv4.ID } } `graphql:"closePullRequest(input: $input)"` } variables := map[string]interface{}{ "input": githubv4.ClosePullRequestInput{ PullRequestID: prID, }, } client := NewClientFromHTTP(httpClient) return client.Mutate(repo.RepoHost(), "PullRequestClose", &mutation, variables) } func PullRequestReopen(httpClient *http.Client, repo ghrepo.Interface, prID string) error { var mutation struct { ReopenPullRequest struct { PullRequest struct { ID githubv4.ID } } `graphql:"reopenPullRequest(input: $input)"` } variables := map[string]interface{}{ "input": githubv4.ReopenPullRequestInput{ PullRequestID: prID, }, } client := NewClientFromHTTP(httpClient) return client.Mutate(repo.RepoHost(), "PullRequestReopen", &mutation, variables) } func PullRequestReady(client *Client, repo ghrepo.Interface, pr *PullRequest) error { var mutation struct { MarkPullRequestReadyForReview struct { PullRequest struct { ID githubv4.ID } } `graphql:"markPullRequestReadyForReview(input: $input)"` } variables := map[string]interface{}{ "input": githubv4.MarkPullRequestReadyForReviewInput{ PullRequestID: pr.ID, }, } return client.Mutate(repo.RepoHost(), "PullRequestReadyForReview", &mutation, variables) } func PullRequestRevert(client *Client, repo ghrepo.Interface, params githubv4.RevertPullRequestInput) (*PullRequest, error) { var mutation struct { RevertPullRequest struct { PullRequest struct { ID githubv4.ID } RevertPullRequest struct { ID string Number int URL string } } `graphql:"revertPullRequest(input: $input)"` } variables := map[string]interface{}{ "input": params, } err := client.Mutate(repo.RepoHost(), "PullRequestRevert", &mutation, variables) if err != nil { return nil, err } pr := &mutation.RevertPullRequest.RevertPullRequest revertPR := &PullRequest{ ID: pr.ID, Number: pr.Number, URL: pr.URL, } return revertPR, nil } func ConvertPullRequestToDraft(client *Client, repo ghrepo.Interface, pr *PullRequest) error { var mutation struct { ConvertPullRequestToDraft struct { PullRequest struct { ID githubv4.ID } } `graphql:"convertPullRequestToDraft(input: $input)"` } variables := map[string]interface{}{ "input": githubv4.ConvertPullRequestToDraftInput{ PullRequestID: pr.ID, }, } return client.Mutate(repo.RepoHost(), "ConvertPullRequestToDraft", &mutation, variables) } func BranchDeleteRemote(client *Client, repo ghrepo.Interface, branch string) error { path := fmt.Sprintf("repos/%s/%s/git/refs/heads/%s", repo.RepoOwner(), repo.RepoName(), url.PathEscape(branch)) return client.REST(repo.RepoHost(), "DELETE", path, nil, nil) } type RefComparison struct { AheadBy int BehindBy int Status string } func ComparePullRequestBaseBranchWith(client *Client, repo ghrepo.Interface, prNumber int, headRef string) (*RefComparison, error) { query := `query ComparePullRequestBaseBranchWith($owner: String!, $repo: String!, $pullRequestNumber: Int!, $headRef: String!) { repository(owner: $owner, name: $repo) { pullRequest(number: $pullRequestNumber) { baseRef { compare (headRef: $headRef) { aheadBy, behindBy, status } } } } }` var result struct { Repository struct { PullRequest struct { BaseRef struct { Compare RefComparison } } } } variables := map[string]interface{}{ "owner": repo.RepoOwner(), "repo": repo.RepoName(), "pullRequestNumber": prNumber, "headRef": headRef, } if err := client.GraphQL(repo.RepoHost(), query, variables, &result); err != nil { return nil, err } return &result.Repository.PullRequest.BaseRef.Compare, nil }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false
cli/cli
https://github.com/cli/cli/blob/c534a758887878331dda780aeb696b113f37b4ab/api/http_client.go
api/http_client.go
package api import ( "fmt" "io" "net/http" "strings" "time" "github.com/cli/cli/v2/utils" ghAPI "github.com/cli/go-gh/v2/pkg/api" ghauth "github.com/cli/go-gh/v2/pkg/auth" ) type tokenGetter interface { ActiveToken(string) (string, string) } type HTTPClientOptions struct { AppVersion string CacheTTL time.Duration Config tokenGetter EnableCache bool Log io.Writer LogColorize bool LogVerboseHTTP bool SkipDefaultHeaders bool } func NewHTTPClient(opts HTTPClientOptions) (*http.Client, error) { // Provide invalid host, and token values so gh.HTTPClient will not automatically resolve them. // The real host and token are inserted at request time. clientOpts := ghAPI.ClientOptions{ Host: "none", AuthToken: "none", LogIgnoreEnv: true, SkipDefaultHeaders: opts.SkipDefaultHeaders, } debugEnabled, debugValue := utils.IsDebugEnabled() if strings.Contains(debugValue, "api") { opts.LogVerboseHTTP = true } if opts.LogVerboseHTTP || debugEnabled { clientOpts.Log = opts.Log clientOpts.LogColorize = opts.LogColorize clientOpts.LogVerboseHTTP = opts.LogVerboseHTTP } headers := map[string]string{ userAgent: fmt.Sprintf("GitHub CLI %s", opts.AppVersion), } clientOpts.Headers = headers if opts.EnableCache { clientOpts.EnableCache = opts.EnableCache clientOpts.CacheTTL = opts.CacheTTL } client, err := ghAPI.NewHTTPClient(clientOpts) if err != nil { return nil, err } if opts.Config != nil { client.Transport = AddAuthTokenHeader(client.Transport, opts.Config) } return client, nil } func NewCachedHTTPClient(httpClient *http.Client, ttl time.Duration) *http.Client { newClient := *httpClient newClient.Transport = AddCacheTTLHeader(httpClient.Transport, ttl) return &newClient } // AddCacheTTLHeader adds an header to the request telling the cache that the request // should be cached for a specified amount of time. func AddCacheTTLHeader(rt http.RoundTripper, ttl time.Duration) http.RoundTripper { return &funcTripper{roundTrip: func(req *http.Request) (*http.Response, error) { // If the header is already set in the request, don't overwrite it. if req.Header.Get(cacheTTL) == "" { req.Header.Set(cacheTTL, ttl.String()) } return rt.RoundTrip(req) }} } // AddAuthTokenHeader adds an authentication token header for the host specified by the request. func AddAuthTokenHeader(rt http.RoundTripper, cfg tokenGetter) http.RoundTripper { return &funcTripper{roundTrip: func(req *http.Request) (*http.Response, error) { // If the header is already set in the request, don't overwrite it. if req.Header.Get(authorization) == "" { var redirectHostnameChange bool if req.Response != nil && req.Response.Request != nil { redirectHostnameChange = getHost(req) != getHost(req.Response.Request) } // Only set header if an initial request or redirect request to the same host as the initial request. // If the host has changed during a redirect do not add the authentication token header. if !redirectHostnameChange { hostname := ghauth.NormalizeHostname(getHost(req)) if token, _ := cfg.ActiveToken(hostname); token != "" { req.Header.Set(authorization, fmt.Sprintf("token %s", token)) } } } return rt.RoundTrip(req) }} } // ExtractHeader extracts a named header from any response received by this client and, // if non-blank, saves it to dest. func ExtractHeader(name string, dest *string) func(http.RoundTripper) http.RoundTripper { return func(tr http.RoundTripper) http.RoundTripper { return &funcTripper{roundTrip: func(req *http.Request) (*http.Response, error) { res, err := tr.RoundTrip(req) if err == nil { if value := res.Header.Get(name); value != "" { *dest = value } } return res, err }} } } type funcTripper struct { roundTrip func(*http.Request) (*http.Response, error) } func (tr funcTripper) RoundTrip(req *http.Request) (*http.Response, error) { return tr.roundTrip(req) } func getHost(r *http.Request) string { if r.Host != "" { return r.Host } return r.URL.Host }
go
MIT
c534a758887878331dda780aeb696b113f37b4ab
2026-01-07T08:35:47.579368Z
false