From f7d77388caaa14370887606b8d1570ec9af17242 Mon Sep 17 00:00:00 2001 From: William Bezuidenhout Date: Fri, 5 Dec 2025 10:45:29 +0200 Subject: [PATCH] run modernize -fix - replace interface{} with any - use min / max functions - use fmt.Appendf for byte[] slice creation with strings - use slices package --- cmd/src/api.go | 4 +- cmd/src/cmd.go | 9 +--- cmd/src/code_intel_upload.go | 4 +- cmd/src/codeowners_create.go | 2 +- cmd/src/codeowners_delete.go | 2 +- cmd/src/codeowners_get.go | 2 +- cmd/src/codeowners_update.go | 2 +- cmd/src/config.go | 2 +- cmd/src/config_edit.go | 6 +-- cmd/src/config_get.go | 4 +- cmd/src/config_list.go | 4 +- cmd/src/debug_compose.go | 2 - cmd/src/extsvc.go | 2 +- cmd/src/extsvc_create.go | 4 +- cmd/src/extsvc_edit.go | 18 +++---- cmd/src/extsvc_list.go | 4 +- cmd/src/format.go | 26 ++++------ cmd/src/headers.go | 4 +- cmd/src/main.go | 7 +-- cmd/src/orgs_create.go | 2 +- cmd/src/orgs_delete.go | 2 +- cmd/src/orgs_get.go | 2 +- cmd/src/orgs_list.go | 2 +- cmd/src/orgs_members_add.go | 2 +- cmd/src/orgs_members_remove.go | 2 +- cmd/src/repos.go | 2 +- cmd/src/repos_add_metadata.go | 2 +- cmd/src/repos_delete.go | 2 +- cmd/src/repos_delete_metadata.go | 2 +- cmd/src/repos_get.go | 2 +- cmd/src/repos_list.go | 2 +- cmd/src/repos_update_metadata.go | 2 +- cmd/src/sbom_utils.go | 4 +- cmd/src/search.go | 50 +++++++++---------- cmd/src/search_jobs.go | 2 +- cmd/src/search_jobs_cancel.go | 2 +- cmd/src/search_jobs_delete.go | 2 +- cmd/src/search_jobs_get.go | 2 +- cmd/src/search_jobs_list.go | 2 +- cmd/src/search_stream.go | 6 +-- cmd/src/snapshot_upload.go | 3 +- cmd/src/snapshot_upload_test.go | 8 +-- cmd/src/team_members_list.go | 2 +- cmd/src/teams_create.go | 2 +- cmd/src/teams_delete.go | 2 +- cmd/src/teams_list.go | 2 +- cmd/src/teams_members_add.go | 2 +- cmd/src/teams_members_remove.go | 2 +- cmd/src/teams_update.go | 2 +- cmd/src/users_create.go | 2 +- cmd/src/users_delete.go | 2 +- cmd/src/users_get.go | 2 +- cmd/src/users_list.go | 2 +- cmd/src/users_prune.go | 8 +-- cmd/src/users_tag.go | 2 +- internal/api/api.go | 24 ++++----- internal/api/errors.go | 8 +-- internal/api/gzip_test.go | 2 +- internal/api/mock/api.go | 8 +-- internal/batches/docker/info_test.go | 2 +- internal/batches/executor/coordinator_test.go | 10 ++-- internal/batches/executor/execution_cache.go | 4 +- .../batches/executor/execution_cache_test.go | 2 +- internal/batches/executor/executor_test.go | 6 +-- internal/batches/executor/run_steps.go | 15 +++--- internal/batches/executor/ui.go | 4 +- internal/batches/log/disk_manager.go | 4 +- internal/batches/log/disk_task_logger.go | 6 +-- internal/batches/log/logger.go | 2 +- internal/batches/log/noop_task_logger.go | 2 +- internal/batches/mock/logger.go | 2 +- internal/batches/service/remote.go | 8 +-- internal/batches/service/remote_test.go | 8 +-- internal/batches/service/service.go | 16 +++--- internal/batches/service/service_test.go | 2 +- internal/batches/ui/json_lines.go | 10 ++-- internal/batches/ui/task_exec_tui.go | 11 ++-- internal/batches/ui/task_exec_tui_test.go | 5 +- internal/batches/watchdog/watchdog_test.go | 2 +- internal/batches/workspace/bind_workspace.go | 2 +- .../batches/workspace/bind_workspace_test.go | 9 ++-- internal/cmderrors/errors.go | 2 +- internal/streaming/client_test.go | 2 +- internal/streaming/writer.go | 2 +- internal/validate/install/insight.go | 16 +++--- internal/validate/install/install.go | 10 ++-- internal/validate/kube/eks.go | 15 +++--- internal/validate/kube/eks_test.go | 4 -- internal/validate/kube/kube_test.go | 3 -- 89 files changed, 219 insertions(+), 256 deletions(-) diff --git a/cmd/src/api.go b/cmd/src/api.go index 0dd1b73b77..e8788424ed 100644 --- a/cmd/src/api.go +++ b/cmd/src/api.go @@ -76,7 +76,7 @@ Examples: } // Determine which variables to use in the request. - vars := map[string]interface{}{} + vars := map[string]any{} if *varsFlag != "" { if err := json.Unmarshal([]byte(*varsFlag), &vars); err != nil { return err @@ -93,7 +93,7 @@ Examples: } // Perform the request. - var result interface{} + var result any if ok, err := cfg.apiClient(apiFlags, flagSet.Output()).NewRequest(query, vars).DoRaw(context.Background(), &result); err != nil || !ok { return err } diff --git a/cmd/src/cmd.go b/cmd/src/cmd.go index d0b20efb1c..93d0accbe3 100644 --- a/cmd/src/cmd.go +++ b/cmd/src/cmd.go @@ -5,6 +5,7 @@ import ( "fmt" "log" "os" + "slices" "github.com/sourcegraph/src-cli/internal/cmderrors" ) @@ -30,12 +31,7 @@ func (c *command) matches(name string) bool { if name == c.flagSet.Name() { return true } - for _, alias := range c.aliases { - if name == alias { - return true - } - } - return false + return slices.Contains(c.aliases, name) } // commander represents a top-level command with subcommands. @@ -60,7 +56,6 @@ func (c commander) run(flagSet *flag.FlagSet, cmdName, usageText string, args [] // Configure default usage funcs for commands. for _, cmd := range c { - cmd := cmd if cmd.usageFunc != nil { cmd.flagSet.Usage = cmd.usageFunc continue diff --git a/cmd/src/code_intel_upload.go b/cmd/src/code_intel_upload.go index 24fab8eed6..8030b31a9a 100644 --- a/cmd/src/code_intel_upload.go +++ b/cmd/src/code_intel_upload.go @@ -98,7 +98,7 @@ func handleCodeIntelUpload(args []string) error { } if codeintelUploadFlags.json { - serialized, err := json.Marshal(map[string]interface{}{ + serialized, err := json.Marshal(map[string]any{ "repo": codeintelUploadFlags.repo, "commit": codeintelUploadFlags.commit, "root": codeintelUploadFlags.root, @@ -202,7 +202,7 @@ func makeCodeIntelUploadURL(uploadID int) (string, error) { return "", err } - graphqlID := base64.URLEncoding.EncodeToString([]byte(fmt.Sprintf(`SCIPUpload:%d`, uploadID))) + graphqlID := base64.URLEncoding.EncodeToString(fmt.Appendf(nil, `SCIPUpload:%d`, uploadID)) url.Path = codeintelUploadFlags.repo + "/-/code-intelligence/uploads/" + graphqlID url.User = nil return url.String(), nil diff --git a/cmd/src/codeowners_create.go b/cmd/src/codeowners_create.go index 7daf00ba21..cb489b0695 100644 --- a/cmd/src/codeowners_create.go +++ b/cmd/src/codeowners_create.go @@ -88,7 +88,7 @@ Examples: var result struct { AddCodeownersFile CodeownersIngestedFile } - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "repoName": *repoFlag, "content": string(content), }).Do(context.Background(), &result); err != nil || !ok { diff --git a/cmd/src/codeowners_delete.go b/cmd/src/codeowners_delete.go index 00ab581023..f6655c30e7 100644 --- a/cmd/src/codeowners_delete.go +++ b/cmd/src/codeowners_delete.go @@ -57,7 +57,7 @@ Examples: var result struct { DeleteCodeownersFile CodeownersIngestedFile } - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "repoName": *repoFlag, }).Do(context.Background(), &result); err != nil || !ok { var gqlErr api.GraphQlErrors diff --git a/cmd/src/codeowners_get.go b/cmd/src/codeowners_get.go index ce4e78a855..e1e1e2fa03 100644 --- a/cmd/src/codeowners_get.go +++ b/cmd/src/codeowners_get.go @@ -59,7 +59,7 @@ Examples: IngestedCodeowners *CodeownersIngestedFile } } - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "repoName": *repoFlag, }).Do(context.Background(), &result); err != nil || !ok { return err diff --git a/cmd/src/codeowners_update.go b/cmd/src/codeowners_update.go index d27292cd0c..222482e656 100644 --- a/cmd/src/codeowners_update.go +++ b/cmd/src/codeowners_update.go @@ -86,7 +86,7 @@ Examples: var result struct { UpdateCodeownersFile CodeownersIngestedFile } - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "repoName": *repoFlag, "content": string(content), }).Do(context.Background(), &result); err != nil || !ok { diff --git a/cmd/src/config.go b/cmd/src/config.go index ffd3b3a24e..f04966b972 100644 --- a/cmd/src/config.go +++ b/cmd/src/config.go @@ -159,7 +159,7 @@ query SettingsSubjectLatestSettingsID($subject: ID!) { } } - if _, err := client.NewRequest(query, map[string]interface{}{ + if _, err := client.NewRequest(query, map[string]any{ "subject": subjectID, }).Do(ctx, &result); err != nil { return nil, err diff --git a/cmd/src/config_edit.go b/cmd/src/config_edit.go index 4a7c65380b..aea7aa893d 100644 --- a/cmd/src/config_edit.go +++ b/cmd/src/config_edit.go @@ -109,12 +109,12 @@ mutation EditSettings($input: SettingsMutationGroupInput!, $edit: SettingsEdit!) } } }` - queryVars := map[string]interface{}{ - "input": map[string]interface{}{ + queryVars := map[string]any{ + "input": map[string]any{ "subject": subjectID, "lastID": lastID, }, - "edit": map[string]interface{}{ + "edit": map[string]any{ "keyPath": keyPath, "value": value, "valueIsJSONCEncodedString": true, diff --git a/cmd/src/config_get.go b/cmd/src/config_get.go index a6d2073e61..41efccea74 100644 --- a/cmd/src/config_get.go +++ b/cmd/src/config_get.go @@ -50,12 +50,12 @@ Examples: } var query string - var queryVars map[string]interface{} + var queryVars map[string]any if *subjectFlag == "" { query = viewerSettingsQuery } else { query = settingsSubjectCascadeQuery - queryVars = map[string]interface{}{ + queryVars = map[string]any{ "subject": api.NullString(*subjectFlag), } } diff --git a/cmd/src/config_list.go b/cmd/src/config_list.go index d2e7038b9e..04d172dbf9 100644 --- a/cmd/src/config_list.go +++ b/cmd/src/config_list.go @@ -57,12 +57,12 @@ Examples: } var query string - var queryVars map[string]interface{} + var queryVars map[string]any if *subjectFlag == "" { query = viewerSettingsQuery } else { query = settingsSubjectCascadeQuery - queryVars = map[string]interface{}{ + queryVars = map[string]any{ "subject": api.NullString(*subjectFlag), } } diff --git a/cmd/src/debug_compose.go b/cmd/src/debug_compose.go index 8bc3b01095..8e26d95b04 100644 --- a/cmd/src/debug_compose.go +++ b/cmd/src/debug_compose.go @@ -138,13 +138,11 @@ func archiveCompose(ctx context.Context, zw *zip.Writer, verbose, archiveConfigs // start goroutine to run docker container logs for _, container := range containers { - container := container run(func() *archiveFile { return getContainerLog(ctx, container, baseDir) }) } // start goroutine to run docker container inspect for _, container := range containers { - container := container run(func() *archiveFile { return getInspect(ctx, container, baseDir) }) } diff --git a/cmd/src/extsvc.go b/cmd/src/extsvc.go index a716aebc00..c3a9aed37f 100644 --- a/cmd/src/extsvc.go +++ b/cmd/src/extsvc.go @@ -61,7 +61,7 @@ func lookupExternalService(ctx context.Context, client api.Client, byID, byName Nodes []*externalService } } - if ok, err := client.NewRequest(externalServicesListQuery, map[string]interface{}{ + if ok, err := client.NewRequest(externalServicesListQuery, map[string]any{ "first": 99999, }).Do(ctx, &result); err != nil || !ok { return nil, err diff --git a/cmd/src/extsvc_create.go b/cmd/src/extsvc_create.go index d79ac48540..317b1e970b 100644 --- a/cmd/src/extsvc_create.go +++ b/cmd/src/extsvc_create.go @@ -59,12 +59,12 @@ func init() { } } - createExternalServiceInput := map[string]interface{}{ + createExternalServiceInput := map[string]any{ "kind": strings.ToUpper(*kindFlag), "displayName": *nameFlag, "config": string(createJSON), } - queryVars := map[string]interface{}{ + queryVars := map[string]any{ "input": createExternalServiceInput, } var result struct{} // TODO: future: allow formatting resulting external service diff --git a/cmd/src/extsvc_edit.go b/cmd/src/extsvc_edit.go index b38bf6c4a2..3cca0fda8e 100644 --- a/cmd/src/extsvc_edit.go +++ b/cmd/src/extsvc_edit.go @@ -102,7 +102,7 @@ Examples: updateJSON = []byte(updated) } - updateExternalServiceInput := map[string]interface{}{ + updateExternalServiceInput := map[string]any{ "id": id, } if *renameFlag != "" { @@ -115,7 +115,7 @@ Examples: return nil // nothing to update } - queryVars := map[string]interface{}{ + queryVars := map[string]any{ "input": updateExternalServiceInput, } var result struct{} // TODO: future: allow formatting resulting external service @@ -151,23 +151,23 @@ mutation ($input: UpdateExternalServiceInput!) { // doesn't exist. func appendExcludeRepositories(input string, excludeRepoNames []string) (string, error) { // Known issue: Comments are not retained in the existing array value. - var m interface{} + var m any if err := jsonxUnmarshal(input, &m); err != nil { return "", err } - root, ok := m.(map[string]interface{}) + root, ok := m.(map[string]any) if !ok { return "", errors.New("existing JSONx external service configuration is invalid (not an object)") } - var exclude []interface{} + var exclude []any alreadyExcludedNames := map[string]struct{}{} if existing, ok := root["exclude"]; ok { - exclude, ok = existing.([]interface{}) + exclude, ok = existing.([]any) if !ok { return "", errors.New("existing JSONx external service configuration is invalid (exclude is not an array)") } for i, exclude := range exclude { - obj, ok := exclude.(map[string]interface{}) + obj, ok := exclude.(map[string]any) if !ok { return "", fmt.Errorf("existing JSONx external service configuration is invalid (exclude.%d is not object)", i) } @@ -189,7 +189,7 @@ func appendExcludeRepositories(input string, excludeRepoNames []string) (string, if _, already := alreadyExcludedNames[repoName]; already { continue } - exclude = append(exclude, map[string]interface{}{ + exclude = append(exclude, map[string]any{ "name": repoName, }) } @@ -218,7 +218,7 @@ func jsonxToJSON(text string) ([]byte, error) { // jsonxUnmarshal unmarshals jsonx into Go data. // // This process loses comments, trailing commas, formatting, etc. -func jsonxUnmarshal(text string, v interface{}) error { +func jsonxUnmarshal(text string, v any) error { data, err := jsonxToJSON(text) if err != nil { return err diff --git a/cmd/src/extsvc_list.go b/cmd/src/extsvc_list.go index 9303a2ce64..fbe6836c37 100644 --- a/cmd/src/extsvc_list.go +++ b/cmd/src/extsvc_list.go @@ -59,7 +59,7 @@ Examples: ctx := context.Background() client := cfg.apiClient(apiFlags, flagSet.Output()) - queryVars := map[string]interface{}{ + queryVars := map[string]any{ "first": first, } var result externalServicesListResult @@ -99,7 +99,7 @@ const externalServicesListQuery = ` // Typing here is primarily for ordering of results as we format them (maps are unordered). type externalServicesListResult struct { ExternalServices struct { - Nodes []map[string]interface{} + Nodes []map[string]any TotalCount int PageInfo struct { HasNextPage bool diff --git a/cmd/src/format.go b/cmd/src/format.go index 2c08d4fcc1..d817650bad 100644 --- a/cmd/src/format.go +++ b/cmd/src/format.go @@ -14,9 +14,9 @@ import ( func parseTemplate(text string) (*template.Template, error) { tmpl := template.New("") - tmpl.Funcs(map[string]interface{}{ + tmpl.Funcs(map[string]any{ "join": strings.Join, - "json": func(v interface{}) (string, error) { + "json": func(v any) (string, error) { b, err := marshalIndent(v) return string(b), err }, @@ -26,26 +26,20 @@ func parseTemplate(text string) (*template.Template, error) { "msDuration": func(ms int) time.Duration { return time.Duration(ms) * time.Millisecond }, - "repoNames": func(repos []map[string]interface{}) (names []string) { + "repoNames": func(repos []map[string]any) (names []string) { for _, r := range repos { names = append(names, r["name"].(string)) } return }, - "pad": func(value interface{}, padding int, padCharacter string) string { + "pad": func(value any, padding int, padCharacter string) string { val := fmt.Sprint(value) - repeat := padding - len(val) - if repeat < 0 { - repeat = 0 - } + repeat := max(padding-len(val), 0) return strings.Repeat(padCharacter, repeat) + val }, - "padRight": func(value interface{}, padding int, padCharacter string) string { + "padRight": func(value any, padding int, padCharacter string) string { val := fmt.Sprint(value) - repeat := padding - len(val) - if repeat < 0 { - repeat = 0 - } + repeat := max(padding-len(val), 0) return val + strings.Repeat(padCharacter, repeat) }, "indent": func(lines, indention string) string { @@ -60,7 +54,7 @@ func parseTemplate(text string) (*template.Template, error) { "addFloat": func(x, y float64) float64 { return x + y }, - "debug": func(v interface{}) string { + "debug": func(v any) string { data, _ := marshalIndent(v) fmt.Println(string(data)) @@ -111,7 +105,7 @@ func parseTemplate(text string) (*template.Template, error) { return tmpl.Parse(text) } -func execTemplate(tmpl *template.Template, data interface{}) error { +func execTemplate(tmpl *template.Template, data any) error { if err := tmpl.Execute(os.Stdout, data); err != nil { return err } @@ -120,6 +114,6 @@ func execTemplate(tmpl *template.Template, data interface{}) error { } // json.MarshalIndent, but with defaults. -func marshalIndent(v interface{}) ([]byte, error) { +func marshalIndent(v any) ([]byte, error) { return json.MarshalIndent(v, "", " ") } diff --git a/cmd/src/headers.go b/cmd/src/headers.go index ced23834ee..d282b19a35 100644 --- a/cmd/src/headers.go +++ b/cmd/src/headers.go @@ -34,9 +34,9 @@ func parseAdditionalHeadersFromEnviron(environ []string) map[string]string { // Most shell convert line breaks added to a string, so we need to replace all occurence of the stringified line // breaks to actual line breaks. headers = strings.ReplaceAll(headers, `\n`, "\n") - splitHeaders := strings.Split(headers, "\n") + splitHeaders := strings.SplitSeq(headers, "\n") - for _, h := range splitHeaders { + for h := range splitHeaders { p := strings.SplitN(h, ":", 2) if len(p) != 2 || p[1] == "" { continue diff --git a/cmd/src/main.go b/cmd/src/main.go index 58fd620b71..9f8ba4ca33 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -203,12 +203,7 @@ func readConfig() (*config, error) { urlSchemes := []string{"http", "https", "socks", "socks5", "socks5h"} isURLScheme := func(scheme string) bool { - for _, s := range urlSchemes { - if scheme == s { - return true - } - } - return false + return slices.Contains(urlSchemes, scheme) } scheme, address := parseEndpoint(cfg.Proxy) diff --git a/cmd/src/orgs_create.go b/cmd/src/orgs_create.go index 4afd49dabf..af00c0fd38 100644 --- a/cmd/src/orgs_create.go +++ b/cmd/src/orgs_create.go @@ -52,7 +52,7 @@ Examples: var result struct { CreateOrg Org } - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "name": *nameFlag, "displayName": *displayNameFlag, }).Do(context.Background(), &result); err != nil || !ok { diff --git a/cmd/src/orgs_delete.go b/cmd/src/orgs_delete.go index 02ec977850..7a00aa4478 100644 --- a/cmd/src/orgs_delete.go +++ b/cmd/src/orgs_delete.go @@ -57,7 +57,7 @@ Examples: var result struct { DeleteOrganization struct{} } - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "organization": *orgIDFlag, }).Do(context.Background(), &result); err != nil || !ok { return err diff --git a/cmd/src/orgs_get.go b/cmd/src/orgs_get.go index c867fec53b..39a1f508db 100644 --- a/cmd/src/orgs_get.go +++ b/cmd/src/orgs_get.go @@ -59,7 +59,7 @@ Examples: var result struct { Organization *Org } - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "name": *nameFlag, }).Do(context.Background(), &result); err != nil || !ok { return err diff --git a/cmd/src/orgs_list.go b/cmd/src/orgs_list.go index 0794b61c93..fdcc7d5348 100644 --- a/cmd/src/orgs_list.go +++ b/cmd/src/orgs_list.go @@ -70,7 +70,7 @@ Examples: Nodes []Org } } - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "first": api.NullInt(*firstFlag), "query": api.NullString(*queryFlag), }).Do(context.Background(), &result); err != nil || !ok { diff --git a/cmd/src/orgs_members_add.go b/cmd/src/orgs_members_add.go index d84efc7d43..cf09f5c0d1 100644 --- a/cmd/src/orgs_members_add.go +++ b/cmd/src/orgs_members_add.go @@ -52,7 +52,7 @@ Examples: var result struct { AddUserToOrganization struct{} } - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "organization": *orgIDFlag, "username": *usernameFlag, }).Do(context.Background(), &result); err != nil || !ok { diff --git a/cmd/src/orgs_members_remove.go b/cmd/src/orgs_members_remove.go index 5ffffb6441..6f6eb3171f 100644 --- a/cmd/src/orgs_members_remove.go +++ b/cmd/src/orgs_members_remove.go @@ -51,7 +51,7 @@ Examples: var result struct { RemoveUserFromOrg struct{} } - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "orgID": *orgIDFlag, "userID": *userIDFlag, }).Do(context.Background(), &result); err != nil || !ok { diff --git a/cmd/src/repos.go b/cmd/src/repos.go index 920327ebe0..d7131c6f87 100644 --- a/cmd/src/repos.go +++ b/cmd/src/repos.go @@ -117,7 +117,7 @@ func fetchRepositoryID(ctx context.Context, client api.Client, repoName string) ID string } } - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "repoName": repoName, }).Do(ctx, &result); err != nil || !ok { return "", err diff --git a/cmd/src/repos_add_metadata.go b/cmd/src/repos_add_metadata.go index 66356880cf..666e2f8868 100644 --- a/cmd/src/repos_add_metadata.go +++ b/cmd/src/repos_add_metadata.go @@ -80,7 +80,7 @@ Examples: } }` - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "repo": *repoID, "key": *keyFlag, "value": valueFlag, diff --git a/cmd/src/repos_delete.go b/cmd/src/repos_delete.go index 2057041a34..e6de1782ab 100644 --- a/cmd/src/repos_delete.go +++ b/cmd/src/repos_delete.go @@ -41,7 +41,7 @@ Examples: } }` var result struct{} - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "repoID": repoID, }).Do(ctx, &result); err != nil || !ok { return err diff --git a/cmd/src/repos_delete_metadata.go b/cmd/src/repos_delete_metadata.go index 612120cff4..168e0803e3 100644 --- a/cmd/src/repos_delete_metadata.go +++ b/cmd/src/repos_delete_metadata.go @@ -69,7 +69,7 @@ Examples: } }` - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "repo": *repoID, "key": *keyFlag, }).Do(ctx, nil); err != nil || !ok { diff --git a/cmd/src/repos_get.go b/cmd/src/repos_get.go index a80050412e..417f0416ac 100644 --- a/cmd/src/repos_get.go +++ b/cmd/src/repos_get.go @@ -56,7 +56,7 @@ Examples: var result struct { Repository Repository } - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "name": *nameFlag, }).Do(context.Background(), &result); err != nil || !ok { return err diff --git a/cmd/src/repos_list.go b/cmd/src/repos_list.go index b5660219e8..575c48dda9 100644 --- a/cmd/src/repos_list.go +++ b/cmd/src/repos_list.go @@ -106,7 +106,7 @@ Examples: Nodes []Repository } } - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "first": api.NullInt(*firstFlag), "query": api.NullString(*queryFlag), "cloned": *clonedFlag, diff --git a/cmd/src/repos_update_metadata.go b/cmd/src/repos_update_metadata.go index 75889f9590..888d3e470a 100644 --- a/cmd/src/repos_update_metadata.go +++ b/cmd/src/repos_update_metadata.go @@ -80,7 +80,7 @@ Examples: } }` - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "repo": *repoID, "key": *keyFlag, "value": valueFlag, diff --git a/cmd/src/sbom_utils.go b/cmd/src/sbom_utils.go index 40dae7b03e..5bae2c970c 100644 --- a/cmd/src/sbom_utils.go +++ b/cmd/src/sbom_utils.go @@ -299,8 +299,8 @@ func matchesImageFilter(patterns []string, imageName string) bool { } // Try matching against the image name without "sourcegraph/" prefix - if strings.HasPrefix(imageName, "sourcegraph/") { - shortName := strings.TrimPrefix(imageName, "sourcegraph/") + if after, ok := strings.CutPrefix(imageName, "sourcegraph/"); ok { + shortName := after if matched, _ := filepath.Match(pattern, shortName); matched { return true } diff --git a/cmd/src/search.go b/cmd/src/search.go index 69ff1995b9..385ac7c72d 100644 --- a/cmd/src/search.go +++ b/cmd/src/search.go @@ -259,7 +259,7 @@ Other tips: } } - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "query": api.NullString(queryString), }).Do(context.Background(), &result); err != nil || !ok { return err @@ -303,9 +303,9 @@ Other tips: // searchResults represents the data we get back from the GraphQL search request. type searchResults struct { - Results []map[string]interface{} + Results []map[string]any LimitHit bool - Cloning, Missing, Timedout []map[string]interface{} + Cloning, Missing, Timedout []map[string]any ResultCount int ElapsedMilliseconds int Alert searchResultsAlert @@ -335,18 +335,18 @@ func envSetDefault(env []string, key, value string) []string { return env } -func searchHighlightPreview(preview interface{}, start, end string) string { +func searchHighlightPreview(preview any, start, end string) string { if start == "" { start = ansiColors["search-match"] } if end == "" { end = ansiColors["nc"] } - p := preview.(map[string]interface{}) + p := preview.(map[string]any) value := p["value"].(string) var highlights []highlight - for _, highlightObject := range p["highlights"].([]interface{}) { - h := highlightObject.(map[string]interface{}) + for _, highlightObject := range p["highlights"].([]any) { + h := highlightObject.(map[string]any) line := int(h["line"].(float64)) character := int(h["character"].(float64)) length := int(h["length"].(float64)) @@ -355,7 +355,7 @@ func searchHighlightPreview(preview interface{}, start, end string) string { return applyHighlights(value, highlights, start, end) } -func searchHighlightDiffPreview(diffPreview interface{}) string { +func searchHighlightDiffPreview(diffPreview any) string { useColordiff, err := strconv.ParseBool(os.Getenv("COLORDIFF")) if err != nil { useColordiff = true @@ -388,7 +388,7 @@ func searchHighlightDiffPreview(diffPreview interface{}) string { } colorized := buf.String() var final []string - for _, line := range strings.Split(colorized, "\n") { + for line := range strings.SplitSeq(colorized, "\n") { // fmt.Println("LINE", line) // Find where the start-of-match token is in the line. somToken := strings.Index(line, uniqueStartOfMatchToken) @@ -498,10 +498,10 @@ func applyHighlights(input string, highlights []highlight, start, end string) st // one line, and the offets are relative to this line. When isPreview is false, // the lineNumber from the FileMatch data is used, which is relative to the file // content. -func convertMatchToHighlights(m map[string]interface{}, isPreview bool) (highlights []highlight) { +func convertMatchToHighlights(m map[string]any, isPreview bool) (highlights []highlight) { var line int - for _, offsetAndLength := range m["offsetAndLengths"].([]interface{}) { - ol := offsetAndLength.([]interface{}) + for _, offsetAndLength := range m["offsetAndLengths"].([]any) { + ol := offsetAndLength.([]any) offset := int(ol[0].(float64)) length := int(ol[1].(float64)) if isPreview { @@ -514,18 +514,18 @@ func convertMatchToHighlights(m map[string]interface{}, isPreview bool) (highlig return highlights } -var searchTemplateFuncs = map[string]interface{}{ - "searchSequentialLineNumber": func(lineMatches []interface{}, index int) bool { +var searchTemplateFuncs = map[string]any{ + "searchSequentialLineNumber": func(lineMatches []any, index int) bool { prevIndex := index - 1 if prevIndex < 0 { return true } - prevLineNumber := lineMatches[prevIndex].(map[string]interface{})["lineNumber"] - lineNumber := lineMatches[index].(map[string]interface{})["lineNumber"] + prevLineNumber := lineMatches[prevIndex].(map[string]any)["lineNumber"] + lineNumber := lineMatches[index].(map[string]any)["lineNumber"] return prevLineNumber.(float64) == lineNumber.(float64)-1 }, - "searchHighlightMatch": func(content, query, match interface{}) string { - m := match.(map[string]interface{}) + "searchHighlightMatch": func(content, query, match any) string { + m := match.(map[string]any) q := query.(string) var highlights []highlight if strings.Contains(q, "patterntype:structural") { @@ -537,11 +537,11 @@ var searchTemplateFuncs = map[string]interface{}{ return applyHighlights(preview, highlights, ansiColors["search-match"], ansiColors["nc"]) } }, - "searchHighlightPreview": func(preview interface{}) string { + "searchHighlightPreview": func(preview any) string { return searchHighlightPreview(preview, "", "") }, "searchHighlightDiffPreview": searchHighlightDiffPreview, - "searchMaxRepoNameLength": func(results []map[string]interface{}) int { + "searchMaxRepoNameLength": func(results []map[string]any) int { max := 0 for _, r := range results { if r["__typename"] != "Repository" { @@ -555,19 +555,19 @@ var searchTemplateFuncs = map[string]interface{}{ }, "htmlToPlainText": htmlToPlainText, "buildVersionHasNewSearchInterface": buildVersionHasNewSearchInterface, - "renderResult": func(searchResult map[string]interface{}) string { - searchResultBody := searchResult["body"].(map[string]interface{}) + "renderResult": func(searchResult map[string]any) string { + searchResultBody := searchResult["body"].(map[string]any) html := searchResultBody["html"].(string) markdown := searchResultBody["text"].(string) plainText := htmlToPlainText(html) highlights := searchResult["highlights"] isDiff := strings.HasPrefix(markdown, "```diff") && strings.HasSuffix(markdown, "```") - if _, ok := highlights.([]interface{}); ok { + if _, ok := highlights.([]any); ok { if isDiff { // We special case diffs because we want to display them with color. - return searchHighlightDiffPreview(map[string]interface{}{"value": plainText, "highlights": highlights.([]interface{})}) + return searchHighlightDiffPreview(map[string]any{"value": plainText, "highlights": highlights.([]any)}) } - return searchHighlightPreview(map[string]interface{}{"value": plainText, "highlights": highlights.([]interface{})}, "", "") + return searchHighlightPreview(map[string]any{"value": plainText, "highlights": highlights.([]any)}, "", "") } return markdown }, diff --git a/cmd/src/search_jobs.go b/cmd/src/search_jobs.go index d821386161..96c5d9070a 100644 --- a/cmd/src/search_jobs.go +++ b/cmd/src/search_jobs.go @@ -203,7 +203,7 @@ func displaySearchJobs(jobs []SearchJob, columns []string, asJSON bool) error { } // outputAsJSON outputs data as JSON -func outputAsJSON(data interface{}) error { +func outputAsJSON(data any) error { jsonBytes, err := json.MarshalIndent(data, "", " ") if err != nil { return err diff --git a/cmd/src/search_jobs_cancel.go b/cmd/src/search_jobs_cancel.go index 507cf3481f..c428d856f6 100644 --- a/cmd/src/search_jobs_cancel.go +++ b/cmd/src/search_jobs_cancel.go @@ -23,7 +23,7 @@ func cancelSearchJob(client api.Client, jobID string) error { } } - if ok, err := client.NewRequest(cancelSearchJobMutation, map[string]interface{}{ + if ok, err := client.NewRequest(cancelSearchJobMutation, map[string]any{ "id": jobID, }).Do(context.Background(), &result); err != nil || !ok { return err diff --git a/cmd/src/search_jobs_delete.go b/cmd/src/search_jobs_delete.go index 183ca2bf4e..2ac3803e7f 100644 --- a/cmd/src/search_jobs_delete.go +++ b/cmd/src/search_jobs_delete.go @@ -23,7 +23,7 @@ func deleteSearchJob(client api.Client, jobID string) error { } } - if ok, err := client.NewRequest(deleteSearchJobQuery, map[string]interface{}{ + if ok, err := client.NewRequest(deleteSearchJobQuery, map[string]any{ "id": jobID, }).Do(context.Background(), &result); err != nil || !ok { return err diff --git a/cmd/src/search_jobs_get.go b/cmd/src/search_jobs_get.go index e5c49aefc2..76c900cf08 100644 --- a/cmd/src/search_jobs_get.go +++ b/cmd/src/search_jobs_get.go @@ -25,7 +25,7 @@ func getSearchJob(client api.Client, id string) (*SearchJob, error) { Node *SearchJob } - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "id": api.NullString(id), }).Do(context.Background(), &result); err != nil || !ok { return nil, err diff --git a/cmd/src/search_jobs_list.go b/cmd/src/search_jobs_list.go index 608bf96ddc..e0f56455ff 100644 --- a/cmd/src/search_jobs_list.go +++ b/cmd/src/search_jobs_list.go @@ -36,7 +36,7 @@ func listSearchJobs(client api.Client, limit int, descending bool, orderBy strin } } - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "first": limit, "descending": descending, "orderBy": orderBy, diff --git a/cmd/src/search_stream.go b/cmd/src/search_stream.go index 7cdb9cea19..512e7f9f75 100644 --- a/cmd/src/search_stream.go +++ b/cmd/src/search_stream.go @@ -36,7 +36,7 @@ func streamSearch(query string, opts streaming.Opts, client api.Client, w io.Wri // jsonDecoder streams results as JSON to w. func jsonDecoder(w io.Writer) streaming.Decoder { // write json.Marshals data and writes it as one line to w plus a newline. - write := func(data interface{}) error { + write := func(data any) error { b, err := json.Marshal(data) if err != nil { return err @@ -316,7 +316,7 @@ const streamingTemplate = ` {{- end -}} ` -var streamSearchTemplateFuncs = map[string]interface{}{ +var streamSearchTemplateFuncs = map[string]any{ "streamSearchHighlightMatch": func(match streaming.ChunkMatch) string { var result []rune @@ -437,7 +437,7 @@ func streamSearchHighlightDiffPreview(diffPreview string, highlights []highlight } colorized := buf.String() var final []string - for _, line := range strings.Split(colorized, "\n") { + for line := range strings.SplitSeq(colorized, "\n") { // fmt.Println("LINE", line) // Find where the start-of-match token is in the line. somToken := strings.Index(line, uniqueStartOfMatchToken) diff --git a/cmd/src/snapshot_upload.go b/cmd/src/snapshot_upload.go index 86c141053b..a019858ecb 100644 --- a/cmd/src/snapshot_upload.go +++ b/cmd/src/snapshot_upload.go @@ -177,7 +177,7 @@ func parseFileArg(fileArg string) ([]string, error) { var filesToUpload []string // Parse comma-delimited list - for _, part := range strings.Split(fileArg, ",") { + for part := range strings.SplitSeq(fileArg, ",") { // Trim whitespace filename := strings.TrimSpace(part) @@ -292,7 +292,6 @@ func uploadFilesToBucket(client *gcsClient, args *uploadArgs, openedFiles []uplo // Upload each file in parallel for fileIndex, openedFile := range openedFiles { - fileIndex := fileIndex openedFile := openedFile uploadPool.Go(func(ctx context.Context) error { diff --git a/cmd/src/snapshot_upload_test.go b/cmd/src/snapshot_upload_test.go index 568e582111..9491096a62 100644 --- a/cmd/src/snapshot_upload_test.go +++ b/cmd/src/snapshot_upload_test.go @@ -101,8 +101,8 @@ func TestFileFilterValidation(t *testing.T) { // Empty is valid (defaults to all files) hasError = false } else { - parts := strings.Split(tt.fileFlag, ",") - for _, part := range parts { + parts := strings.SplitSeq(tt.fileFlag, ",") + for part := range parts { filename := strings.TrimSpace(part) if !slices.Contains(listOfValidFiles, filename) { @@ -193,8 +193,8 @@ func TestFileSelection(t *testing.T) { if tt.fileFilter == "" { filesToUpload = listOfValidFiles } else { - parts := strings.Split(tt.fileFilter, ",") - for _, part := range parts { + parts := strings.SplitSeq(tt.fileFilter, ",") + for part := range parts { filename := strings.TrimSpace(part) filesToUpload = append(filesToUpload, filename) } diff --git a/cmd/src/team_members_list.go b/cmd/src/team_members_list.go index 0090c88312..eb69d57719 100644 --- a/cmd/src/team_members_list.go +++ b/cmd/src/team_members_list.go @@ -81,7 +81,7 @@ Examples: } } } - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "name": *nameFlag, "first": api.NullInt(*firstFlag), "search": api.NullString(*queryFlag), diff --git a/cmd/src/teams_create.go b/cmd/src/teams_create.go index 013d204efa..fd64fded4e 100644 --- a/cmd/src/teams_create.go +++ b/cmd/src/teams_create.go @@ -67,7 +67,7 @@ Examples: var result struct { CreateTeam Team } - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "name": *nameFlag, "displayName": api.NullString(*displayNameFlag), "parentTeam": api.NullString(*parentTeamFlag), diff --git a/cmd/src/teams_delete.go b/cmd/src/teams_delete.go index df667204c3..ce89f19b9f 100644 --- a/cmd/src/teams_delete.go +++ b/cmd/src/teams_delete.go @@ -56,7 +56,7 @@ Examples: var result struct { DeleteTeam any } - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "name": *nameFlag, }).Do(context.Background(), &result); err != nil || !ok { return err diff --git a/cmd/src/teams_list.go b/cmd/src/teams_list.go index 8ba98a7bd1..37efd25bfc 100644 --- a/cmd/src/teams_list.go +++ b/cmd/src/teams_list.go @@ -95,7 +95,7 @@ Examples: } } } - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "first": api.NullInt(*firstFlag), "search": api.NullString(*queryFlag), "parentTeamName": api.NullString(*parentTeamFlag), diff --git a/cmd/src/teams_members_add.go b/cmd/src/teams_members_add.go index 9f4c3d24d2..ebc530cb4a 100644 --- a/cmd/src/teams_members_add.go +++ b/cmd/src/teams_members_add.go @@ -82,7 +82,7 @@ Examples: var result struct { AddTeamMembers Team } - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "teamName": *teamNameFlag, "skipUnmatchedMembers": *skipUnmatchedMembersFlag, "id": api.NullString(*idFlag), diff --git a/cmd/src/teams_members_remove.go b/cmd/src/teams_members_remove.go index 1a5dbbeb4c..fc52c32c34 100644 --- a/cmd/src/teams_members_remove.go +++ b/cmd/src/teams_members_remove.go @@ -82,7 +82,7 @@ Examples: var result struct { RemoveTeamMembers Team } - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "teamName": *teamNameFlag, "skipUnmatchedMembers": *skipUnmatchedMembersFlag, "id": api.NullString(*idFlag), diff --git a/cmd/src/teams_update.go b/cmd/src/teams_update.go index 549a254a29..ae5bdb2331 100644 --- a/cmd/src/teams_update.go +++ b/cmd/src/teams_update.go @@ -64,7 +64,7 @@ Examples: var result struct { UpdateTeam Team } - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "name": *nameFlag, "displayName": api.NullString(*displayNameFlag), "parentTeam": api.NullString(*parentTeamFlag), diff --git a/cmd/src/users_create.go b/cmd/src/users_create.go index 259cebc1cb..b33b5808ba 100644 --- a/cmd/src/users_create.go +++ b/cmd/src/users_create.go @@ -55,7 +55,7 @@ Examples: ResetPasswordURL string } } - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "username": *usernameFlag, "email": *emailFlag, }).Do(context.Background(), &result); err != nil || !ok { diff --git a/cmd/src/users_delete.go b/cmd/src/users_delete.go index e929814f05..c4b59b6c3f 100644 --- a/cmd/src/users_delete.go +++ b/cmd/src/users_delete.go @@ -92,7 +92,7 @@ Examples: var result struct { DeleteUser struct{} } - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "user": *userIDFlag, }).Do(context.Background(), &result); err != nil || !ok { return err diff --git a/cmd/src/users_get.go b/cmd/src/users_get.go index 47cebc5309..6b27865f19 100644 --- a/cmd/src/users_get.go +++ b/cmd/src/users_get.go @@ -64,7 +64,7 @@ Examples: var result struct { User *User } - if ok, err := client.NewRequest(query, map[string]interface{}{ + if ok, err := client.NewRequest(query, map[string]any{ "username": api.NullString(*usernameFlag), "email": api.NullString(*emailFlag), }).Do(context.Background(), &result); err != nil || !ok { diff --git a/cmd/src/users_list.go b/cmd/src/users_list.go index d9fd46b6b7..728b447917 100644 --- a/cmd/src/users_list.go +++ b/cmd/src/users_list.go @@ -56,7 +56,7 @@ Examples: if err != nil { return err } - vars := map[string]interface{}{ + vars := map[string]any{ "first": api.NullInt(*firstFlag), "query": api.NullString(*queryFlag), "tag": api.NullString(*tagFlag), diff --git a/cmd/src/users_prune.go b/cmd/src/users_prune.go index 8c78ef2b11..90de530c68 100644 --- a/cmd/src/users_prune.go +++ b/cmd/src/users_prune.go @@ -101,7 +101,7 @@ Examples: // paginate requests until all site users have been checked -- this includes soft deleted users for len(aggregatedUsers) < int(totalUsers.Site.Users.TotalCount) { - pagVars := map[string]interface{}{ + pagVars := map[string]any{ "offset": offset, "limit": limit, } @@ -208,7 +208,7 @@ func computeDaysSinceLastUse(user SiteUser) (timeDiff int, hasLastActive bool, _ // Issue graphQL api request to remove user func removeUser(user SiteUser, client api.Client, ctx context.Context) error { query := `mutation DeleteUser($user: ID!) { deleteUser(user: $user) { alwaysNil }}` - vars := map[string]interface{}{ + vars := map[string]any{ "user": user.ID, } if ok, err := client.NewRequest(query, vars).Do(ctx, nil); err != nil || !ok { @@ -231,10 +231,10 @@ func confirmUserRemoval(usersToDelete []UserToDelete, daysThreshold int, display t.AppendHeader(table.Row{"Username", "Email", "Days Since Last Active"}) for _, user := range usersToDelete { if user.User.Email != "" { - t.AppendRow([]interface{}{user.User.Username, user.User.Email, user.DaysSinceLastUse}) + t.AppendRow([]any{user.User.Username, user.User.Email, user.DaysSinceLastUse}) t.AppendSeparator() } else { - t.AppendRow([]interface{}{user.User.Username, "", user.DaysSinceLastUse}) + t.AppendRow([]any{user.User.Username, "", user.DaysSinceLastUse}) t.AppendSeparator() } } diff --git a/cmd/src/users_tag.go b/cmd/src/users_tag.go index 5270e3e859..4404c88c19 100644 --- a/cmd/src/users_tag.go +++ b/cmd/src/users_tag.go @@ -62,7 +62,7 @@ Related examples: } }` - _, err := client.NewRequest(query, map[string]interface{}{ + _, err := client.NewRequest(query, map[string]any{ "user": *userIDFlag, "tag": *tagFlag, "present": !*removeFlag, diff --git a/internal/api/api.go b/internal/api/api.go index a31fae55e4..4dfad40d3b 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -28,7 +28,7 @@ type Client interface { NewQuery(query string) Request // NewRequest creates a GraphQL request. - NewRequest(query string, vars map[string]interface{}) Request + NewRequest(query string, vars map[string]any) Request // NewHTTPRequest creates an http.Request for the Sourcegraph API. // @@ -47,13 +47,13 @@ type Request interface { // // If no data was available to be unmarshalled — for example, due to the // -get-curl flag being set — then ok will return false. - Do(ctx context.Context, result interface{}) (ok bool, err error) + Do(ctx context.Context, result any) (ok bool, err error) // DoRaw has the same behaviour as Do, with one exception: the result will // not be unwrapped, and will include the GraphQL errors. Therefore the // structure that is provided as the result should have top level Data and // Errors keys for the GraphQL wrapper to be unmarshalled into. - DoRaw(ctx context.Context, result interface{}) (ok bool, err error) + DoRaw(ctx context.Context, result any) (ok bool, err error) } // client is the internal concrete type implementing Client. @@ -66,7 +66,7 @@ type client struct { type request struct { client *client query string - vars map[string]interface{} + vars map[string]any } // ClientOpts encapsulates the options given to NewClient. @@ -137,7 +137,7 @@ func (c *client) NewQuery(query string) Request { return c.NewRequest(query, nil) } -func (c *client) NewRequest(query string, vars map[string]interface{}) Request { +func (c *client) NewRequest(query string, vars map[string]any) Request { return &request{ client: c, query: query, @@ -181,7 +181,7 @@ func (c *client) createHTTPRequest(ctx context.Context, method, p string, body i return req, nil } -func (r *request) do(ctx context.Context, result interface{}) (bool, error) { +func (r *request) do(ctx context.Context, result any) (bool, error) { if *r.client.opts.Flags.getCurl { curl, err := r.curlCmd() if err != nil { @@ -207,7 +207,7 @@ func (r *request) do(ctx context.Context, result interface{}) (bool, error) { } // Create the JSON object. - reqBody, err := json.Marshal(map[string]interface{}{ + reqBody, err := json.Marshal(map[string]any{ "query": r.query, "variables": r.vars, }) @@ -280,7 +280,7 @@ func (r *request) do(ctx context.Context, result interface{}) (bool, error) { // given result. If GraphQL errors are returned, then the returned error will be // an instance of GraphQlErrors. Other errors (such as HTTP or network errors) // will be returned as-is. -func (r *request) Do(ctx context.Context, result interface{}) (bool, error) { +func (r *request) Do(ctx context.Context, result any) (bool, error) { raw := rawResult{Data: result} ok, err := r.do(ctx, &raw) if err != nil { @@ -300,17 +300,17 @@ func (r *request) Do(ctx context.Context, result interface{}) (bool, error) { return true, nil } -func (r *request) DoRaw(ctx context.Context, result interface{}) (bool, error) { +func (r *request) DoRaw(ctx context.Context, result any) (bool, error) { return r.do(ctx, result) } type rawResult struct { - Data interface{} `json:"data,omitempty"` - Errors []interface{} `json:"errors,omitempty"` + Data any `json:"data,omitempty"` + Errors []any `json:"errors,omitempty"` } func (r *request) curlCmd() (string, error) { - data, err := json.Marshal(map[string]interface{}{ + data, err := json.Marshal(map[string]any{ "query": r.query, "variables": r.vars, }) diff --git a/internal/api/errors.go b/internal/api/errors.go index 278beef34f..e5ff8193ce 100644 --- a/internal/api/errors.go +++ b/internal/api/errors.go @@ -28,7 +28,7 @@ func (gg GraphQlErrors) Error() string { } // GraphQlError wraps a raw JSON error returned from a GraphQL endpoint. -type GraphQlError struct{ v interface{} } +type GraphQlError struct{ v any } // Code returns the GraphQL error code, if one was set on the error. func (g *GraphQlError) Code() (string, error) { @@ -55,15 +55,15 @@ func (g *GraphQlError) Error() string { // Extensions returns the GraphQL error extensions, if set, or nil if no // extensions were set on the error. -func (g *GraphQlError) Extensions() (map[string]interface{}, error) { - e, ok := g.v.(map[string]interface{}) +func (g *GraphQlError) Extensions() (map[string]any, error) { + e, ok := g.v.(map[string]any) if !ok { return nil, errors.Errorf("unexpected GraphQL error of type %T", g.v) } if e["extensions"] == nil { return nil, nil - } else if me, ok := e["extensions"].(map[string]interface{}); ok { + } else if me, ok := e["extensions"].(map[string]any); ok { return me, nil } return nil, errors.Errorf("unexpected extensions of type %T", e["extensions"]) diff --git a/internal/api/gzip_test.go b/internal/api/gzip_test.go index 1d6b3006ad..092ee93f9e 100644 --- a/internal/api/gzip_test.go +++ b/internal/api/gzip_test.go @@ -11,7 +11,7 @@ import ( func TestGzipReader(t *testing.T) { var uncompressed []byte - for i := 0; i < 20000; i++ { + for i := range 20000 { uncompressed = append(uncompressed, byte(i)) } diff --git a/internal/api/mock/api.go b/internal/api/mock/api.go index 43e7f795a7..710b11aff6 100644 --- a/internal/api/mock/api.go +++ b/internal/api/mock/api.go @@ -19,12 +19,12 @@ func (m *Client) NewQuery(query string) api.Request { return args.Get(0).(api.Request) } -func (m *Client) NewRequest(query string, vars map[string]interface{}) api.Request { +func (m *Client) NewRequest(query string, vars map[string]any) api.Request { args := m.Called(query, vars) return args.Get(0).(api.Request) } -func (m *Client) NewGzippedRequest(query string, vars map[string]interface{}) api.Request { +func (m *Client) NewGzippedRequest(query string, vars map[string]any) api.Request { args := m.Called(query, vars) return args.Get(0).(api.Request) } @@ -57,7 +57,7 @@ type Request struct { Response string } -func (r *Request) Do(ctx context.Context, result interface{}) (bool, error) { +func (r *Request) Do(ctx context.Context, result any) (bool, error) { args := r.Called(ctx, result) if r.Response != "" { if err := json.Unmarshal([]byte(r.Response), result); err != nil { @@ -67,7 +67,7 @@ func (r *Request) Do(ctx context.Context, result interface{}) (bool, error) { return args.Bool(0), args.Error(1) } -func (r *Request) DoRaw(ctx context.Context, result interface{}) (bool, error) { +func (r *Request) DoRaw(ctx context.Context, result any) (bool, error) { args := r.Called(ctx, result) if r.Response != "" { if err := json.Unmarshal([]byte(r.Response), result); err != nil { diff --git a/internal/batches/docker/info_test.go b/internal/batches/docker/info_test.go index 7e674dd555..c0f11e8c33 100644 --- a/internal/batches/docker/info_test.go +++ b/internal/batches/docker/info_test.go @@ -57,7 +57,7 @@ func Test_CurrentContext(t *testing.T) { func contextInspectSuccess(ncpu string) *expect.Expectation { return expect.NewLiteral( - expect.Behaviour{Stdout: []byte(fmt.Sprintf("%s\n", ncpu))}, + expect.Behaviour{Stdout: fmt.Appendf(nil, "%s\n", ncpu)}, "docker", "context", "inspect", "--format", "{{ .Name }}", ) } diff --git a/internal/batches/executor/coordinator_test.go b/internal/batches/executor/coordinator_test.go index 53e17c0fab..7c123d95d1 100644 --- a/internal/batches/executor/coordinator_test.go +++ b/internal/batches/executor/coordinator_test.go @@ -136,9 +136,9 @@ func TestCoordinator_Execute(t *testing.T) { stepResults: []execution.AfterStepResult{{ Version: 2, Diff: []byte(`dummydiff1`), - Outputs: map[string]interface{}{ + Outputs: map[string]any{ "output1": "myOutputValue1", - "output2": map[string]interface{}{ + "output2": map[string]any{ "subField": "subFieldValue", }, }, @@ -568,13 +568,13 @@ func (d *dummyExecutor) Wait() ([]taskResult, error) { // inMemoryExecutionCache provides an in-memory cache for testing purposes. type inMemoryExecutionCache struct { - cache map[string]interface{} + cache map[string]any mu sync.RWMutex } func newInMemoryExecutionCache() *inMemoryExecutionCache { return &inMemoryExecutionCache{ - cache: make(map[string]interface{}), + cache: make(map[string]any), } } @@ -585,7 +585,7 @@ func (c *inMemoryExecutionCache) size() int { return len(c.cache) } -func (c *inMemoryExecutionCache) getCacheItem(key cache.Keyer) (interface{}, bool, error) { +func (c *inMemoryExecutionCache) getCacheItem(key cache.Keyer) (any, bool, error) { k, err := key.Key() if err != nil { return execution.AfterStepResult{}, false, err diff --git a/internal/batches/executor/execution_cache.go b/internal/batches/executor/execution_cache.go index 24b7f91bc0..5b7b868ef7 100644 --- a/internal/batches/executor/execution_cache.go +++ b/internal/batches/executor/execution_cache.go @@ -35,7 +35,7 @@ func (c ExecutionDiskCache) cacheFilePath(key cache.Keyer) (string, error) { return filepath.Join(c.Dir, key.Slug(), keyString+cacheFileExt), nil } -func readCacheFile(path string, result interface{}) (bool, error) { +func readCacheFile(path string, result any) (bool, error) { if _, err := os.Stat(path); os.IsNotExist(err) { return false, nil } @@ -56,7 +56,7 @@ func readCacheFile(path string, result interface{}) (bool, error) { return true, nil } -func (c ExecutionDiskCache) writeCacheFile(path string, result interface{}) error { +func (c ExecutionDiskCache) writeCacheFile(path string, result any) error { raw, err := json.Marshal(result) if err != nil { return errors.Wrap(err, "serializing cache content to JSON") diff --git a/internal/batches/executor/execution_cache_test.go b/internal/batches/executor/execution_cache_test.go index 5357278420..20beb48cfc 100644 --- a/internal/batches/executor/execution_cache_test.go +++ b/internal/batches/executor/execution_cache_test.go @@ -62,7 +62,7 @@ func TestExecutionDiskCache_GetSet(t *testing.T) { ChangedFiles: git.Changes{ Added: []string{"README.md"}, }, - Outputs: map[string]interface{}{}, + Outputs: map[string]any{}, } cache := ExecutionDiskCache{Dir: t.TempDir()} diff --git a/internal/batches/executor/executor_test.go b/internal/batches/executor/executor_test.go index 2df8c21ea0..9fc96d927d 100644 --- a/internal/batches/executor/executor_test.go +++ b/internal/batches/executor/executor_test.go @@ -577,7 +577,7 @@ index 02a19af..c9644dd 100644 Version: 2, StepIndex: 0, Diff: cachedDiff, - Outputs: map[string]interface{}{}, + Outputs: map[string]any{}, }, Repository: testRepo1, } @@ -693,7 +693,7 @@ echo "previous_step.modified_files=${{ previous_step.modified_files }}" >> READM Version: 2, StepIndex: 2, Diff: cachedDiff, - Outputs: map[string]interface{}{ + Outputs: map[string]any{ "myOutput": "my-output.txt", }, ChangedFiles: git.Changes{ @@ -770,7 +770,7 @@ index 3040106..5f2f924 100644 Version: 2, StepIndex: 0, Diff: []byte(""), - Outputs: map[string]interface{}{}, + Outputs: map[string]any{}, ChangedFiles: git.Changes{}, Stdout: "hello world", Stderr: "", diff --git a/internal/batches/executor/run_steps.go b/internal/batches/executor/run_steps.go index 3d3bbd9d60..92d1966dd7 100644 --- a/internal/batches/executor/run_steps.go +++ b/internal/batches/executor/run_steps.go @@ -6,6 +6,7 @@ import ( "encoding/json" "fmt" "io" + "maps" "os" "os/exec" "path/filepath" @@ -213,7 +214,7 @@ func RunSteps(ctx context.Context, opts *RunStepsOpts) (stepResults []execution. StepIndex: i, Diff: stepDiff, // Those will be set below. - Outputs: make(map[string]interface{}), + Outputs: make(map[string]any), } // Set stepContext.Step to current step's results before rendering outputs. @@ -222,9 +223,7 @@ func RunSteps(ctx context.Context, opts *RunStepsOpts) (stepResults []execution. if err := setOutputs(step.Outputs, lastOutputs, &stepContext); err != nil { return stepResults, errors.Wrap(err, "setting step outputs") } - for k, v := range lastOutputs { - stepResult.Outputs[k] = v - } + maps.Copy(stepResult.Outputs, lastOutputs) stepResults = append(stepResults, stepResult) previousStepResult = stepResult @@ -420,7 +419,7 @@ func executeSingleStep( return stdout, stderr, nil } -func setOutputs(stepOutputs batcheslib.Outputs, global map[string]interface{}, stepCtx *template.StepContext) error { +func setOutputs(stepOutputs batcheslib.Outputs, global map[string]any, stepCtx *template.StepContext) error { for name, output := range stepOutputs { var value bytes.Buffer @@ -430,7 +429,7 @@ func setOutputs(stepOutputs batcheslib.Outputs, global map[string]interface{}, s switch output.Format { case "yaml": - var out interface{} + var out any // We use yamlv3 here, because it unmarshals YAML into // map[string]interface{} which we need to serialize it back to // JSON when we cache the results. @@ -440,7 +439,7 @@ func setOutputs(stepOutputs batcheslib.Outputs, global map[string]interface{}, s } global[name] = out case "json": - var out interface{} + var out any if err := json.NewDecoder(&value).Decode(&out); err != nil { return err } @@ -664,7 +663,7 @@ func (e stepFailedErr) Error() string { out.WriteString(fmt.Sprintf("run: %s\ncontainer: %s\n", fmtRun(e.Run), e.Container)) printOutput := func(output string) { - for _, line := range strings.Split(output, "\n") { + for line := range strings.SplitSeq(output, "\n") { if e.TmpFilename != "" { line = strings.ReplaceAll(line, e.TmpFilename+": ", "") } diff --git a/internal/batches/executor/ui.go b/internal/batches/executor/ui.go index 547a2fb1f1..8a89593112 100644 --- a/internal/batches/executor/ui.go +++ b/internal/batches/executor/ui.go @@ -45,7 +45,7 @@ type StepsExecutionUI interface { StepOutputWriter(context.Context, *Task, int) StepOutputWriter - StepFinished(idx int, diff []byte, changes git.Changes, outputs map[string]interface{}) + StepFinished(idx int, diff []byte, changes git.Changes, outputs map[string]any) StepFailed(idx int, err error, exitCode int) } @@ -65,7 +65,7 @@ func (noop NoopStepsExecUI) StepStarted(step int, runScript string, env map[stri func (noop NoopStepsExecUI) StepOutputWriter(ctx context.Context, task *Task, step int) StepOutputWriter { return NoopStepOutputWriter{} } -func (noop NoopStepsExecUI) StepFinished(idx int, diff []byte, changes git.Changes, outputs map[string]interface{}) { +func (noop NoopStepsExecUI) StepFinished(idx int, diff []byte, changes git.Changes, outputs map[string]any) { } func (noop NoopStepsExecUI) StepFailed(idx int, err error, exitCode int) { } diff --git a/internal/batches/log/disk_manager.go b/internal/batches/log/disk_manager.go index e3ef43ddf2..f1340fc42b 100644 --- a/internal/batches/log/disk_manager.go +++ b/internal/batches/log/disk_manager.go @@ -32,7 +32,7 @@ func (lm *DiskManager) AddTask(slug string) (TaskLogger, error) { func (lm *DiskManager) Close() error { var errs errors.MultiError - lm.tasks.Range(func(_, v interface{}) bool { + lm.tasks.Range(func(_, v any) bool { logger := v.(*FileTaskLogger) if err := logger.Close(); err != nil { @@ -48,7 +48,7 @@ func (lm *DiskManager) Close() error { func (lm *DiskManager) LogFiles() []string { var files []string - lm.tasks.Range(func(_, v interface{}) bool { + lm.tasks.Range(func(_, v any) bool { files = append(files, v.(*FileTaskLogger).Path()) return true }) diff --git a/internal/batches/log/disk_task_logger.go b/internal/batches/log/disk_task_logger.go index ce8d809b2e..d627d7be2e 100644 --- a/internal/batches/log/disk_task_logger.go +++ b/internal/batches/log/disk_task_logger.go @@ -51,8 +51,8 @@ func (tl *FileTaskLogger) Log(s string) { fmt.Fprintf(tl.f, "%s %s\n", time.Now().Format(time.RFC3339Nano), s) } -func (tl *FileTaskLogger) Logf(format string, a ...interface{}) { - fmt.Fprintf(tl.f, "%s "+format+"\n", append([]interface{}{time.Now().Format(time.RFC3339Nano)}, a...)...) +func (tl *FileTaskLogger) Logf(format string, a ...any) { + fmt.Fprintf(tl.f, "%s "+format+"\n", append([]any{time.Now().Format(time.RFC3339Nano)}, a...)...) } func (tl *FileTaskLogger) MarkErrored() { @@ -85,7 +85,7 @@ func (pw *prefixWriter) Write(p []byte) (int, error) { // Hello Sourcegraph // t := bytes.TrimSuffix(p, []byte("\n")) - for _, line := range bytes.Split(t, []byte("\n")) { + for line := range bytes.SplitSeq(t, []byte("\n")) { pw.logger.Logf("%s | %s", pw.prefix, string(line)) } return len(p), nil diff --git a/internal/batches/log/logger.go b/internal/batches/log/logger.go index 0949e1ba32..4403f152ac 100644 --- a/internal/batches/log/logger.go +++ b/internal/batches/log/logger.go @@ -11,7 +11,7 @@ type LogManager interface { type TaskLogger interface { Close() error Log(string) - Logf(string, ...interface{}) + Logf(string, ...any) MarkErrored() Path() string PrefixWriter(prefix string) io.Writer diff --git a/internal/batches/log/noop_task_logger.go b/internal/batches/log/noop_task_logger.go index 114a8bf704..6de5e332a5 100644 --- a/internal/batches/log/noop_task_logger.go +++ b/internal/batches/log/noop_task_logger.go @@ -12,7 +12,7 @@ func (tl *NoopTaskLogger) Close() error { func (tl *NoopTaskLogger) Log(s string) {} -func (tl *NoopTaskLogger) Logf(format string, a ...interface{}) {} +func (tl *NoopTaskLogger) Logf(format string, a ...any) {} func (tl *NoopTaskLogger) MarkErrored() {} diff --git a/internal/batches/mock/logger.go b/internal/batches/mock/logger.go index ec8e36fe1e..a86af75c28 100644 --- a/internal/batches/mock/logger.go +++ b/internal/batches/mock/logger.go @@ -13,7 +13,7 @@ type TaskNoOpLogger struct{} func (tl TaskNoOpLogger) Close() error { return nil } func (tl TaskNoOpLogger) Log(string) {} -func (tl TaskNoOpLogger) Logf(string, ...interface{}) {} +func (tl TaskNoOpLogger) Logf(string, ...any) {} func (tl TaskNoOpLogger) MarkErrored() {} func (tl TaskNoOpLogger) Path() string { return "" } func (tl TaskNoOpLogger) PrefixWriter(prefix string) io.Writer { return &bytes.Buffer{} } diff --git a/internal/batches/service/remote.go b/internal/batches/service/remote.go index 8db0e09e45..71678ff898 100644 --- a/internal/batches/service/remote.go +++ b/internal/batches/service/remote.go @@ -41,7 +41,7 @@ func (svc *Service) UpsertBatchChange( } `json:"upsertEmptyBatchChange"` } - if ok, err := svc.client.NewRequest(upsertEmptyBatchChangeQuery, map[string]interface{}{ + if ok, err := svc.client.NewRequest(upsertEmptyBatchChangeQuery, map[string]any{ "name": name, "namespace": namespaceID, }).Do(ctx, &resp); err != nil || !ok { @@ -88,7 +88,7 @@ func (svc *Service) CreateBatchSpecFromRaw( } `json:"createBatchSpecFromRaw"` } - if ok, err := svc.client.NewRequest(createBatchSpecFromRawQuery, map[string]interface{}{ + if ok, err := svc.client.NewRequest(createBatchSpecFromRawQuery, map[string]any{ "batchSpec": batchSpec, "namespace": namespaceID, "allowIgnored": allowIgnored, @@ -260,7 +260,7 @@ func (svc *Service) ExecuteBatchSpec( } `json:"executeBatchSpec"` } - if ok, err := svc.client.NewRequest(executeBatchSpecQuery, map[string]interface{}{ + if ok, err := svc.client.NewRequest(executeBatchSpecQuery, map[string]any{ "batchSpec": batchSpecID, "noCache": noCache, }).Do(ctx, &resp); err != nil || !ok { @@ -301,7 +301,7 @@ func (svc *Service) GetBatchSpecWorkspaceResolution(ctx context.Context, id stri } `json:"node"` } - if ok, err := svc.client.NewRequest(batchSpecWorkspaceResolutionQuery, map[string]interface{}{ + if ok, err := svc.client.NewRequest(batchSpecWorkspaceResolutionQuery, map[string]any{ "batchSpec": id, }).Do(ctx, &resp); err != nil || !ok { return nil, err diff --git a/internal/batches/service/remote_test.go b/internal/batches/service/remote_test.go index 5e18b5e847..d35114eb3f 100644 --- a/internal/batches/service/remote_test.go +++ b/internal/batches/service/remote_test.go @@ -41,7 +41,7 @@ func TestService_UpsertBatchChange(t *testing.T) { { name: "New Batch Change", mockInvokes: func() { - client.On("NewRequest", mock.Anything, map[string]interface{}{ + client.On("NewRequest", mock.Anything, map[string]any{ "name": "my-change", "namespace": "my-namespace", }). @@ -62,7 +62,7 @@ func TestService_UpsertBatchChange(t *testing.T) { { name: "Failed to upsert batch change", mockInvokes: func() { - client.On("NewRequest", mock.Anything, map[string]interface{}{ + client.On("NewRequest", mock.Anything, map[string]any{ "name": "my-change", "namespace": "my-namespace", }). @@ -121,7 +121,7 @@ func TestService_CreateBatchSpecFromRaw(t *testing.T) { { name: "Create batch spec", mockInvokes: func() { - client.On("NewRequest", mock.Anything, map[string]interface{}{ + client.On("NewRequest", mock.Anything, map[string]any{ "batchSpec": "abc", "namespace": "some-namespace", "allowIgnored": false, @@ -149,7 +149,7 @@ func TestService_CreateBatchSpecFromRaw(t *testing.T) { { name: "Failed to create batch spec", mockInvokes: func() { - client.On("NewRequest", mock.Anything, map[string]interface{}{ + client.On("NewRequest", mock.Anything, map[string]any{ "batchSpec": "abc", "namespace": "some-namespace", "allowIgnored": false, diff --git a/internal/batches/service/service.go b/internal/batches/service/service.go index 9c8339e3c3..031788ef9a 100644 --- a/internal/batches/service/service.go +++ b/internal/batches/service/service.go @@ -107,7 +107,7 @@ func (svc *Service) ApplyBatchChange(ctx context.Context, spec graphql.BatchSpec var result struct { BatchChange *graphql.BatchChange `json:"applyBatchChange"` } - if ok, err := svc.client.NewRequest(applyBatchChangeMutation, map[string]interface{}{ + if ok, err := svc.client.NewRequest(applyBatchChangeMutation, map[string]any{ "batchSpec": spec, }).Do(ctx, &result); err != nil || !ok { return nil, err @@ -136,7 +136,7 @@ func (svc *Service) CreateBatchSpec(ctx context.Context, namespace, spec string, var result struct { CreateBatchSpec graphql.CreateBatchSpecResponse } - if ok, err := svc.client.NewRequest(createBatchSpecMutation, map[string]interface{}{ + if ok, err := svc.client.NewRequest(createBatchSpecMutation, map[string]any{ "namespace": namespace, "spec": spec, "changesetSpecs": ids, @@ -170,7 +170,7 @@ func (svc *Service) CreateChangesetSpec(ctx context.Context, spec *batcheslib.Ch ID string } } - if ok, err := svc.client.NewRequest(createChangesetSpecMutation, map[string]interface{}{ + if ok, err := svc.client.NewRequest(createChangesetSpecMutation, map[string]any{ "spec": string(raw), }).Do(ctx, &result); err != nil || !ok { return "", err @@ -224,7 +224,7 @@ func (svc *Service) ResolveWorkspacesForBatchSpec(ctx context.Context, spec *bat SearchResultPaths []string } } - if ok, err := svc.client.NewRequest(resolveWorkspacesForBatchSpecQuery, map[string]interface{}{ + if ok, err := svc.client.NewRequest(resolveWorkspacesForBatchSpecQuery, map[string]any{ "spec": string(raw), }).Do(ctx, &result); err != nil || !ok { return nil, nil, err @@ -566,7 +566,7 @@ func (svc *Service) GenerateExampleSpec(ctx context.Context, fileName string) er author.Email = gitAuthorEmail } - err = tmpl.Execute(f, map[string]interface{}{"Author": author}) + err = tmpl.Execute(f, map[string]any{"Author": author}) if err != nil { return errors.Wrap(err, "failed to write batch spec to file") } @@ -637,9 +637,9 @@ func (svc *Service) ResolveNamespace(ctx context.Context, namespace string) (Nam URL string } } - Errors []interface{} + Errors []any } - if ok, err := svc.client.NewRequest(namespaceQuery, map[string]interface{}{ + if ok, err := svc.client.NewRequest(namespaceQuery, map[string]any{ "name": namespace, }).DoRaw(ctx, &result); err != nil || !ok { return Namespace{}, err @@ -670,7 +670,7 @@ query Repository($name: String!, $queryCommit: Boolean!, $rev: String!) { func (svc *Service) resolveRepositoryName(ctx context.Context, name string) (*graphql.Repository, error) { var result struct{ Repository *graphql.Repository } - if ok, err := svc.client.NewRequest(repositoryNameQuery, map[string]interface{}{ + if ok, err := svc.client.NewRequest(repositoryNameQuery, map[string]any{ "name": name, "queryCommit": false, "rev": "", diff --git a/internal/batches/service/service_test.go b/internal/batches/service/service_test.go index 33030b5f18..14afc7e002 100644 --- a/internal/batches/service/service_test.go +++ b/internal/batches/service/service_test.go @@ -185,7 +185,7 @@ func TestEnsureDockerImages(t *testing.T) { steps := []batcheslib.Step{} total := 100 - for i := 0; i < total; i++ { + for i := range total { name := strconv.Itoa(i) if i%25 == 0 { images[name] = &mock.Image{EnsureErr: wantErr} diff --git a/internal/batches/ui/json_lines.go b/internal/batches/ui/json_lines.go index 36ae989570..d5c36c8da2 100644 --- a/internal/batches/ui/json_lines.go +++ b/internal/batches/ui/json_lines.go @@ -333,7 +333,7 @@ func (ui *stepsExecutionJSONLines) StepOutputWriter(ctx context.Context, task *e return NewIntervalProcessWriter(ctx, stepFlushDuration, sink) } -func (ui *stepsExecutionJSONLines) StepFinished(step int, diff []byte, changes git.Changes, outputs map[string]interface{}) { +func (ui *stepsExecutionJSONLines) StepFinished(step int, diff []byte, changes git.Changes, outputs map[string]any) { logOperationSuccess( batcheslib.LogEventOperationTaskStep, &batcheslib.TaskStepMetadata{ @@ -371,19 +371,19 @@ func (ui *JSONLines) UploadingWorkspaceFilesSuccess() { // No workspace file upload required for executor mode. } -func logOperationStart(op batcheslib.LogEventOperation, metadata interface{}) { +func logOperationStart(op batcheslib.LogEventOperation, metadata any) { logEvent(batcheslib.LogEvent{Operation: op, Status: batcheslib.LogEventStatusStarted, Metadata: metadata}) } -func logOperationSuccess(op batcheslib.LogEventOperation, metadata interface{}) { +func logOperationSuccess(op batcheslib.LogEventOperation, metadata any) { logEvent(batcheslib.LogEvent{Operation: op, Status: batcheslib.LogEventStatusSuccess, Metadata: metadata}) } -func logOperationFailure(op batcheslib.LogEventOperation, metadata interface{}) { +func logOperationFailure(op batcheslib.LogEventOperation, metadata any) { logEvent(batcheslib.LogEvent{Operation: op, Status: batcheslib.LogEventStatusFailure, Metadata: metadata}) } -func logOperationProgress(op batcheslib.LogEventOperation, metadata interface{}) { +func logOperationProgress(op batcheslib.LogEventOperation, metadata any) { logEvent(batcheslib.LogEvent{Operation: op, Status: batcheslib.LogEventStatusProgress, Metadata: metadata}) } diff --git a/internal/batches/ui/task_exec_tui.go b/internal/batches/ui/task_exec_tui.go index 43243324ed..b90df64fe9 100644 --- a/internal/batches/ui/task_exec_tui.go +++ b/internal/batches/ui/task_exec_tui.go @@ -3,7 +3,7 @@ package ui import ( "context" "fmt" - "sort" + "slices" "strings" "sync" "time" @@ -125,10 +125,7 @@ func (ui *taskExecTUI) Start(tasks []*executor.Task) { ui.statuses[t] = status } - ui.numStatusBars = ui.numParallelism - if len(tasks) < ui.numStatusBars { - ui.numStatusBars = len(tasks) - } + ui.numStatusBars = min(len(tasks), ui.numParallelism) statusBars := make([]*output.StatusBar, 0, ui.numStatusBars) for i := 0; i < ui.numStatusBars; i++ { @@ -370,7 +367,7 @@ func verboseDiffSummary(fileDiffs []*diff.FileDiff) ([]string, error) { fileStats[name] = fmt.Sprintf("%d %s", num, diffStatDiagram(stat)) } - sort.Slice(fileNames, func(i, j int) bool { return fileNames[i] < fileNames[j] }) + slices.Sort(fileNames) for _, name := range fileNames { stats := fileStats[name] @@ -471,7 +468,7 @@ func (ui stepsExecTUI) StepOutputWriter(ctx context.Context, task *executor.Task return executor.NoopStepOutputWriter{} } -func (ui stepsExecTUI) StepFinished(idx int, diff []byte, changes git.Changes, outputs map[string]interface{}) { +func (ui stepsExecTUI) StepFinished(idx int, diff []byte, changes git.Changes, outputs map[string]any) { // noop right now } func (ui stepsExecTUI) StepFailed(idx int, err error, exitCode int) { diff --git a/internal/batches/ui/task_exec_tui_test.go b/internal/batches/ui/task_exec_tui_test.go index f368cb7993..ec0783995f 100644 --- a/internal/batches/ui/task_exec_tui_test.go +++ b/internal/batches/ui/task_exec_tui_test.go @@ -333,10 +333,7 @@ func (t *ttyBuf) Write(b []byte) (int, error) { case 'D': // *d*elete cursor by amount - t.column = t.column - int(digit) - if t.column < 0 { - t.column = 0 - } + t.column = max(t.column-int(digit), 0) case 'm': // noop diff --git a/internal/batches/watchdog/watchdog_test.go b/internal/batches/watchdog/watchdog_test.go index 49b1574e95..eab02a28f5 100644 --- a/internal/batches/watchdog/watchdog_test.go +++ b/internal/batches/watchdog/watchdog_test.go @@ -27,7 +27,7 @@ func TestWatchDog(t *testing.T) { } go w.Start() - for i := 0; i < expectedCount; i++ { + for range expectedCount { wg.Add(1) ticker.BlockingAdvance(5 * time.Minute) } diff --git a/internal/batches/workspace/bind_workspace.go b/internal/batches/workspace/bind_workspace.go index 55a1e4dcb4..3519e6f13c 100644 --- a/internal/batches/workspace/bind_workspace.go +++ b/internal/batches/workspace/bind_workspace.go @@ -318,7 +318,7 @@ func ensureAll(base, path string, perm os.FileMode) error { // In plain English: for each directory in the path parameter, we should // chmod that path to the permissions that are expected. acc := []string{base} - for _, element := range strings.Split(path, string(os.PathSeparator)) { + for element := range strings.SplitSeq(path, string(os.PathSeparator)) { acc = append(acc, element) if err := os.Chmod(filepath.Join(acc...), perm); err != nil { errs = errors.Append(errs, err) diff --git a/internal/batches/workspace/bind_workspace_test.go b/internal/batches/workspace/bind_workspace_test.go index 3a6ab3fd8d..5fe05c2edf 100644 --- a/internal/batches/workspace/bind_workspace_test.go +++ b/internal/batches/workspace/bind_workspace_test.go @@ -3,6 +3,7 @@ package workspace import ( "archive/zip" "context" + "maps" "os" "path/filepath" "strings" @@ -134,12 +135,8 @@ func TestDockerBindWorkspaceCreator_Create(t *testing.T) { } wantFiles := map[string]string{} - for name, content := range filesInZip { - wantFiles[name] = content - } - for name, content := range additionalFiles { - wantFiles[name] = content - } + maps.Copy(wantFiles, filesInZip) + maps.Copy(wantFiles, additionalFiles) if !cmp.Equal(wantFiles, haveUnzippedFiles) { t.Fatalf("wrong files in workspace:\n%s", cmp.Diff(wantFiles, haveUnzippedFiles)) } diff --git a/internal/cmderrors/errors.go b/internal/cmderrors/errors.go index ded5a7e778..1358c1522d 100644 --- a/internal/cmderrors/errors.go +++ b/internal/cmderrors/errors.go @@ -16,7 +16,7 @@ func Usage(msg string) *UsageError { return &UsageError{errors.New(msg)} } -func Usagef(f string, args ...interface{}) *UsageError { +func Usagef(f string, args ...any) *UsageError { return &UsageError{fmt.Errorf(f, args...)} } diff --git a/internal/streaming/client_test.go b/internal/streaming/client_test.go index 2af482acbb..01da2ba548 100644 --- a/internal/streaming/client_test.go +++ b/internal/streaming/client_test.go @@ -11,7 +11,7 @@ import ( func TestDecoder(t *testing.T) { type Event struct { Name string - Value interface{} + Value any } want := []Event{{ diff --git a/internal/streaming/writer.go b/internal/streaming/writer.go index ea4b4d540a..e9f7835094 100644 --- a/internal/streaming/writer.go +++ b/internal/streaming/writer.go @@ -46,7 +46,7 @@ func NewWriter(w http.ResponseWriter) (*Writer, error) { } // Event writes event with data json marshalled. -func (e *Writer) Event(event string, data interface{}) error { +func (e *Writer) Event(event string, data any) error { encoded, err := json.Marshal(data) if err != nil { return err diff --git a/internal/validate/install/insight.go b/internal/validate/install/insight.go index 2b24d03c23..86a46ba1f1 100644 --- a/internal/validate/install/insight.go +++ b/internal/validate/install/insight.go @@ -9,20 +9,20 @@ import ( ) func createInsight(ctx context.Context, client api.Client, insight Insight) (string, error) { - var dataSeries []map[string]interface{} + var dataSeries []map[string]any for _, ds := range insight.DataSeries { - var series = map[string]interface{}{ + var series = map[string]any{ "query": ds["query"], - "options": map[string]interface{}{ + "options": map[string]any{ "label": ds["label"], "lineColor": ds["lineColor"], }, - "repositoryScope": map[string]interface{}{ + "repositoryScope": map[string]any{ "repositories": ds["repositoryScope"], }, - "timeScope": map[string]interface{}{ - "stepInterval": map[string]interface{}{ + "timeScope": map[string]any{ + "stepInterval": map[string]any{ "unit": ds["timeScopeUnit"], "value": ds["timeScopeValue"], }, @@ -42,8 +42,8 @@ func createInsight(ctx context.Context, client api.Client, insight Insight) (str } }`, variables: jsonVars{ - "input": map[string]interface{}{ - "options": map[string]interface{}{"title": insight.Title}, + "input": map[string]any{ + "options": map[string]any{"title": insight.Title}, "dataSeries": dataSeries, }, }, diff --git a/internal/validate/install/install.go b/internal/validate/install/install.go index 9b3966190c..b86aaab0fb 100644 --- a/internal/validate/install/install.go +++ b/internal/validate/install/install.go @@ -11,7 +11,7 @@ import ( "github.com/sourcegraph/sourcegraph/lib/errors" ) -type jsonVars map[string]interface{} +type jsonVars map[string]any type clientQuery struct { opName string @@ -56,7 +56,7 @@ func Validate(ctx context.Context, client api.Client, config *ValidationSpec) er totalCount } }` - executorVars := map[string]interface{}{ + executorVars := map[string]any{ "query": "", "active": true, "first": 100, @@ -81,7 +81,7 @@ func Validate(ctx context.Context, client api.Client, config *ValidationSpec) er smtpQuery := `mutation sendTestEmail($to: String!) { sendTestEmail(to: $to) }` - smtpVars := map[string]interface{}{ + smtpVars := map[string]any{ "to": config.Smtp.To, } @@ -116,7 +116,7 @@ func Validate(ctx context.Context, client api.Client, config *ValidationSpec) er return nil } -func checkExecutors(ctx context.Context, client api.Client, query string, variables map[string]interface{}) (int, error) { +func checkExecutors(ctx context.Context, client api.Client, query string, variables map[string]any) (int, error) { q := clientQuery{ opName: "CheckExecutorConnection", query: query, @@ -199,7 +199,7 @@ func searchMatchCount(ctx context.Context, client api.Client, searchExpr string) return result.Search.Results.MatchCount, nil } -func checkSmtp(ctx context.Context, client api.Client, query string, variables map[string]interface{}) (string, error) { +func checkSmtp(ctx context.Context, client api.Client, query string, variables map[string]any) (string, error) { q := clientQuery{ opName: "CheckSmtpConfig", query: query, diff --git a/internal/validate/kube/eks.go b/internal/validate/kube/eks.go index 745be69f22..3a65ba0448 100644 --- a/internal/validate/kube/eks.go +++ b/internal/validate/kube/eks.go @@ -5,6 +5,7 @@ import ( "fmt" "log" "path/filepath" + "slices" "strings" corev1 "k8s.io/api/core/v1" @@ -182,14 +183,12 @@ func validateEbsCsiDrivers(testers EbsTestObjects) (result []validate.Result) { } func validateAddons(addons []string) (result []validate.Result) { - for _, addon := range addons { - if addon == "aws-ebs-csi-driver" { - result = append(result, validate.Result{ - Status: validate.Success, - Message: "EKS: 'aws-ebs-csi-driver' present in addons", - }) - return result - } + if slices.Contains(addons, "aws-ebs-csi-driver") { + result = append(result, validate.Result{ + Status: validate.Success, + Message: "EKS: 'aws-ebs-csi-driver' present in addons", + }) + return result } result = append(result, validate.Result{ diff --git a/internal/validate/kube/eks_test.go b/internal/validate/kube/eks_test.go index f008034669..bda70a3b4c 100644 --- a/internal/validate/kube/eks_test.go +++ b/internal/validate/kube/eks_test.go @@ -44,7 +44,6 @@ func TestValidateVpc(t *testing.T) { } for _, tc := range cases { - tc := tc t.Run(tc.name, func(t *testing.T) { vpc := testVPC() if tc.vpc != nil { @@ -114,7 +113,6 @@ func TestValidateAddons(t *testing.T) { } for _, tc := range cases { - tc := tc t.Run(tc.name, func(t *testing.T) { addons := testAddonOutput() if tc.addons != nil { @@ -185,7 +183,6 @@ func TestValidateServiceAccount(t *testing.T) { } for _, tc := range cases { - tc := tc t.Run(tc.name, func(t *testing.T) { sa := testServiceAccount() if tc.sa != nil { @@ -258,7 +255,6 @@ func TestValidateRolePolicy(t *testing.T) { } for _, tc := range cases { - tc := tc t.Run(tc.name, func(t *testing.T) { rp := testEBSCSIRole() if tc.rp != nil { diff --git a/internal/validate/kube/kube_test.go b/internal/validate/kube/kube_test.go index cd8a778cec..fbc83c77ad 100644 --- a/internal/validate/kube/kube_test.go +++ b/internal/validate/kube/kube_test.go @@ -141,7 +141,6 @@ func TestValidatePod(t *testing.T) { } for _, tc := range cases { - tc := tc t.Run(tc.name, func(t *testing.T) { pod := testPod() if tc.pod != nil { @@ -220,7 +219,6 @@ func TestValidateService(t *testing.T) { } for _, tc := range cases { - tc := tc t.Run(tc.name, func(t *testing.T) { service := testService() if tc.service != nil { @@ -275,7 +273,6 @@ func TestValidatePVC(t *testing.T) { } for _, tc := range cases { - tc := tc t.Run(tc.name, func(t *testing.T) { pvc := testPVC() if tc.pvc != nil {